Showing posts with label interview. Show all posts
Showing posts with label interview. Show all posts

Tuesday, November 19, 2013

Interview Question at narus

1. What is virtual memory and advantage and disadvantage of virtual memory
2.  how compiler manage scoping of static variable
3. difference between macro and const variable
4. network buffers : linux
5. how watchdog run how do find that some CPU is locked
6. who restrict size of virtual memory
7. what is kernal memory size , can it be virtual
8. static gloabl and same static local variable in function is possible
9. what is volatile
10. fork what all it do

Tuesday, May 8, 2012

Data structure


http://www.data-structure-definition.blogspot.in/

Wednesday, February 29, 2012

netapp

1. mbuf and sk buff
2. read or load , which is costely
3. const int a;
int const a;
const int const a;
what is difference between above 3
4. spanning tree

Monday, January 30, 2012

Linux networking stack

http://www.6test.edu.cn/~lujx/linux_networking/index.html?page=0131777203_ch17lev1sec4.html

http://www.ecsl.cs.sunysb.edu/elibrary/linux/network/LinuxKernel.pdf : good link

http://e-university.wisdomjobs.com/linux/chapter-208-277/receiving-data-in-the-transport-layer-udp-and-tcp.html

http://hsnlab.tmit.bme.hu/twiki/pub/Targyak/Mar11Cikkek/Network_stack.pdf : very good

Thursday, January 26, 2012

Merge Sort vs. Quick Sort: Overview

Merge Sort vs. Quick Sort: Overview
Merge Sort
Quick Sort
Time complexity (Average): O(n log n) Time complexity (Average): O(n log n)
Time complexity (Worst): O(n log n) Time complexity (Worst): O(n^2)
(Occurs when list is sorted)
Stable sort

Not dependent on any factors
Average case = Worst Case Not a stable sort

Dependent on randomness of list
Memory: O(n)
Additional memory space required Memory: O(log n)
Memory Complexity (Best): O(1)
Little additional memory space required

When to use Merge Sort? When additional memory usage is not a problem and list could be partial sorted


When to use Quick Sort? When additonal memory usage is a problem and the list is randomized.

[Source: Sorting Algorithm]

Wednesday, January 25, 2012

Interview Mcafee

1. Is MSS optional or not
2. how traceroute work
3. implementation of hash funation
4. insert in binary search tree : try to write a program by urself
5. IPC machenism
6. shared memory
7. how kernel pass information to process
8. try to look at linux kernel path

Juniper
1. Mirror image of binary tree
2. How to write state machine using function pointer
3. how to write word alligned data.
4. If data is present in stack then is there any padding

Saturday, January 21, 2012

Patricia tree

Must read : http://books.google.co.in/books?id=ESM3CWY5xRYC&pg=PA562&lpg=PA562&dq=patricia+tree+routing&source=bl&ots=b4pXXGtACY&sig=TISdjQMrPkEPDjorJMQelA9zx7U&hl=en&sa=X&ei=PZAbT9lw0IisB4Pa4eQN&ved=0CDwQ6AEwBDgK#v=onepage&q=patricia%20tree%20routing&f=false

Patricia stands for "Practical algorithm to retrieve information coded in alphanumeric",

Trie : A tree for storing strings in which there is one node for every common prefix. The strings are stored in extra leaf nodes

Node : (1) A unit of reference in a data structure. Also called a vertex in graphs and trees. (2) A collection of information which must be kept at a single memory location.

Child : An item of a tree referred to by a parent item. See the figure at tree. Every item, except the root, is the child of some parent.


A Patricia tree is related to a Trie. The problem with Tries is that when the set of keys is sparse, i.e. when the actual keys form a small subset of the set of potential keys, as is very often the case, many (most) of the internal nodes in the Trie have only one descendant. This causes the Trie to have a high space-complexity.

Patricia tree : Binary digital tree
Specs :

n external nodes with key values
n-1 internal nodes




---------

Tries were invented by E. Fredkin in 1960

Patricia trees Patricia stands for "Practical algorithm to retrieve information coded in alphanumeric", invented by D. R. Morrison, 1968

The idea is to take a trie and get rid of any nodes that only have one child. Instead, each remaining node is labeled with a character position number which would have given that node's depth in the original uncompressed trie. We now have the problem that keys are no longer uniquely specified by the search path, so we have to store the key itself in the appropriate leaf. The storage requirement is now kn pointers, where n is the number of keys and k is the size of the alphabet. This is often significantly less than s(k + 1), particularly if the keys are very long.

A Patricia tree alone is far from efficient.

Monday, January 16, 2012

multicasting

http://www.h3c.com/portal/Products___Solutions/Technology/Security_and_VPN/Technology_Introduction/200701/195605_57_0.htm

Sunday, January 15, 2012

Atomic operation and spin lock

http://en.wikipedia.org/wiki/Linearizability

spin lock : http://www.csie.dyu.edu.tw/~swang/LDD/ch5_p2.pdf

Friday, January 6, 2012

mtries

http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=usingTries

Wednesday, January 4, 2012

Interview

http://placementsindia.blogspot.com/2007/12/solutions-to-few-google-top-interview.html

variable number of argument

va_arg takes a va_list and a variable type, and returns the next argument in the list in the form of whatever variable type it is told. It then moves down the list to the next argument. For example, va_arg ( a_list, double ) will return the next argument, assuming it exists, in the form of a double. The next time it is called, it will return the argument following the last returned number, if one exists. Note that you need to know the type of each argument--that's part of why printf requires a format string! Once you're done, use va_end to clean up the list: va_end( a_list );

To show how each of the parts works, take an example function:

#include
#include

/* this function will take the number of values to average
followed by all of the numbers to average */
double average ( int num, ... )
{
va_list arguments;
double sum = 0;

/* Initializing arguments to store all values after num */
va_start ( arguments, num );
/* Sum all the inputs; we still rely on the function caller to tell us how
* many there are */
for ( int x = 0; x < num; x++ )
{
sum += va_arg ( arguments, double );
}
va_end ( arguments ); // Cleans up the list

return sum / num;
}

int main()
{
/* this computes the average of 13.2, 22.3 and 4.5 (3 indicates the number of values to average) */
printf( "%f\n", average ( 3, 12.2, 22.3, 4.5 ) );
/* here it computes the average of the 5 values 3.3, 2.2, 1.1, 5.5 and 3.3
printf( "%f\n", average ( 5, 3.3, 2.2, 1.1, 5.5, 3.3 ) );
}

Tuesday, January 3, 2012

prime number test

What is a prime number?

Prime number is a number, which have exactly two distinct natural number divisors, 1 and itself. The most naive approach to check whether a number is prime is to follow the definition. Algorithm to check number's n primality:

if number is 1, return false;
otherwise, for all integers m from 2 to n - 1, check if n is divisible by m. If it is, n is composite;
if no divisors were found, we can conclude, that n is prime.
Note. The 1 is not a prime number, because it doesn't satisfy the definition.

Improving the method

Can we make this simple approach better? Yes. First, let us notice, that we can check divisors less or equal to square root of n only. The proof follows.

Statement. If n has a divisor d (1 < d < n), than it has a divisor d0 (1 < d0 < √n).

If n is divided by square root entirely, than it is a perfect square and not prime. Otherwise, assume, that first found divisor is d1, √n < d1 < n. But n is divided entirely by d2 = n / d1, which is less than √n. Therefore, the assumption is false and if there are a divisor greater than √n, than there is a "pair" less than √n. Statement is proven.

One more improvement

We should mention one more improvement. Assume, than n is odd (2 is not a divisor). If n is not divisible by 2 without remainder, than it is not divisible entirely by any other even number. The algorithm after those two improvements changes:

if number is 1, return false;
if number is 2, return true;
if number is even, return false;
otherwise, for all odd integers m from 3 to √n, check if n is divisible by m. If it is, n is composite;
if no divisors were found, we can conclude, that n is prime.
Generalization of this idea is when algorithm checks prime divisors only.


C++ implementation

bool isPrime(int number) {
if (number == 1)
return false;
if (number == 2)
return true;
if (number % 2 == 0)
return false;
for (int d = 3; d <= (int)sqrt((double)number); d++)
if (number % d == 0)
return false;
return true;
}

sorting

http://www.sorting-algorithms.com
http://www.algolist.net/Algorithms/Sorting/Selection_sort
http://www.cs.oswego.edu/~mohammad/classes/csc241/samples/sort/Sort2-E.html
http://en.wikipedia.org/wiki/Sorting_algorithm

good quick sort :

http://www.algolist.net/Algorithms/Sorting/Quicksort

Algorithm

The divide-and-conquer strategy is used in quicksort. Below the recursion step is described:
Choose a pivot value. We take the value of the middle element as pivot value, but it can be any value, which is in range of sorted values, even if it doesn't present in the array.
Partition. Rearrange elements in such a way, that all elements which are lesser than the pivot go to the left part of the array and all elements greater than the pivot, go to the right part of the array. Values equal to the pivot can stay in any part of the array. Notice, that array may be divided in non-equal parts.
Sort both parts. Apply quicksort algorithm recursively to the left and the right parts.
Partition algorithm in detail

There are two indices i and j and at the very beginning of the partition algorithm i points to the first element in the array and j points to the last one. Then algorithm moves i forward, until an element with value greater or equal to the pivot is found. Index j is moved backward, until an element with value lesser or equal to the pivot is found. If i ≤ j then they are swapped and i steps to the next position (i + 1), j steps to the previous one (j - 1). Algorithm stops, when i becomes greater than j.

After partition, all values before i-th element are less or equal than the pivot and all values after j-th element are greater or equal to the pivot.

Example. Sort {1, 12, 5, 26, 7, 14, 3, 7, 2} using quicksort.

void quickSort(int arr[], int left, int right) {
int i = left, j = right;
int tmp;
int pivot = arr[(left + right) / 2];

/* partition */
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};

/* recursion */
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}

Friday, December 30, 2011

Interview

Redisis Interview

1. function pointer
2. Difference between strcpy and memcopy
3. question on char *="abcd"
4. setps of socket apis for client and server
5. multithreaded server

Tuesday, December 27, 2011

google interview

Telephonic round

1. no. of byte in mac address
2. dns record for Ipv6
3. number of max host if mask is 23
4. three way hand shake

5. 0x2f convert to decimal
6. 11 convert to binary
7 quick sort best and worst case
8. fastes to slowets : read from register , read from memory , read from disk, context switch

citrix interview

Next higher number with same number of binary bits set

Ans : http://www.slideshare.net/gkumar007/bits-next-higher-presentation


Program Design:

We need to note few facts of binary numbers. The expression x & -x will isolate right most set bit in x (ensuring x will use 2′s complement form for negative numbers). If we add the result to x, right most string of 1′s in x will be reset, and the immediate ’0′ left to this pattern of 1′s will be set, which is part [B] of above explanation. For example if x = 156, x & -x will result in 00000100, adding this result to x yields 10100000 (see part D). We left with the right shifting part of pattern of 1′s (part A of above explanation).

There are different ways to achieve part A. Right shifting is essentially a division operation. What should be our divisor? Clearly, it should be multiple of 2 (avoids 0.5 error in right shifting), and it should shift the right most 1′s pattern to right extreme. The expression (x & -x) will serve the purpose of divisor. An EX-OR operation between the number X and expression which is used to reset right most bits, will isolate the rightmost 1′s pattern.

A Correction Factor:

Note that we are adding right most set bit to the bit pattern. The addition operation causes a shift in the bit positions. The weight of binary system is 2, one shift causes an increase by a factor of 2. Since the increased number (rightOnesPattern in the code) being used twice, the error propagates twice. The error needs to be corrected. A right shift by 2 positions will correct the result.

The popular name for this program is same number of one bits.

#include

using namespace std;

typedef unsigned int uint_t;

// this function returns next higher number with same number of set bits as x.
uint_t snoob(uint_t x)
{

uint_t rightOne;
uint_t nextHigherOneBit;
uint_t rightOnesPattern;

uint_t next = 0;

if(x)
{

// right most set bit
rightOne = x & -(signed)x;

// reset the pattern and set next higher bit
// left part of x will be here
nextHigherOneBit = x + rightOne;

// nextHigherOneBit is now part [D] of the above explanation.

// isolate the pattern
rightOnesPattern = x ^ nextHigherOneBit;

// right adjust pattern
rightOnesPattern = (rightOnesPattern)/rightOne;

// correction factor
rightOnesPattern >>= 2;

// rightOnesPattern is now part [A] of the above explanation.

// integrate new pattern (Add [D] and [A])
next = nextHigherOneBit | rightOnesPattern;
}

return next;
}

int main()
{
int x = 156;
cout<<"Next higher number with same number of set bits is "<
getchar();
return 0;
}
Usage: Finding/Generating subsets.

Variations:

Write a program to find a number immediately smaller than given, with same number of logic 1 bits? (Pretty simple)
How to count or generate the subsets available in the given set?
References:

A nice presentation here.
Hackers Delight by Warren (An excellent and short book on various bit magic algorithms, a must for enthusiasts)
C A Reference Manual by Harbison and Steele (A good book on standard C, you can access code part of this post here).
Thanks to Venki for contribution. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.







11 comments so far

Agniswar says:
October 13, 2011 at 10:03 AM
Hi,i solved in this way..though not so efficient but pretty simple one..
Link- http://ideone.com/NBMTG

Reply
pappu says:
October 12, 2011 at 3:55 PM
int nextNumber(int x)
{
int u = log(x & -x);
int y = x >> u;
int z = log( ~y & -(~y));
int k = pow(2, z) - 1;

y = ((y >> 2) + 1) << (z + u);
return y + k;
}

Reply
AJ says:
July 26, 2011 at 10:56 PM
For immediate smaller number with same number of bits:

int next_lowest(int x)
{
int removeones = (x + 1) & x;
int isolate = removeones & ~(removeones - 1);
int shifted = (removeones ^ isolate) | (isolate >> 1);
int temp = (x + 1) & ~x;
int factor = (shifted & ~(shifted - 1)) / (temp);
int toadd = (temp - 1) * factor;

return toadd|shifted;
}
Reply
Manish Mishra says:
June 12, 2011 at 7:37 AM
To get the immediate lower number, just use this-

int nextsmallest(int n)
{
return ~nextlargest(~n);
}
Reply
Imran Amjad says:
May 31, 2011 at 4:31 PM
Hi GeeksforGeeks,

from the same logic to get the next higher number of same set bits, how i'll reverse these steps to get immediate lower number? please give a brief explanation. Thanks

Reply
sutendra mirajkar says:
April 19, 2011 at 8:39 PM
#include
#include

int main(int argc,char *argv[])
{
int a,i,temp,bin,count=0,fcount=0,flag=0;

if(argc != 2)
{
printf("IMPROPER EXECUTION,PLEASE TYPE IN THE NUMBER AFTER ./a.out_ _\n");
}

a=atoi(argv[1]);

int t=a;

while(flag == 0)
{

count=0;
for(i=8*sizeof(t)-1;i>=0;i--)
{
temp=1< bin=t & temp;
if(bin != 0)
{
if(t == a)
fcount++;
else
count++;
}
}
if(count == fcount)
{
printf("\nTHE NEXT HIGHEST NUMBER WITH SAME NO BITS TURNED ON IS:%d\n",t);
flag=1;
}
t+=1;

}

return 0;
}
Reply
naveen kolati says:
February 24, 2011 at 4:12 PM
#include
int naveen(int );
void main()
{
int p=0,k,n;
printf("enter the number");
scanf("%d",&n);
k = naveen(n);
while(k!=p)
p=naveen(++n);
printf("\n next number is %d",n);
getch();
}

int naveen(int n)
{
int count=0;
while(n!=0)
{
n=n&(n-1);
count++;
}
return count;
}
Reply
Himanshu says:
February 9, 2011 at 12:19 PM
Another method to find the lexicographical next permutation is given at following URL:

http://graphics.stanford.edu/~seander/bithacks.html#NextBitPermutation

Reply
Preetam says:
February 8, 2011 at 6:11 PM
for 5 what is the next higher number?
please write few more samples

Reply
Venki says:
February 8, 2011 at 8:50 PM
@Preetam, Use the sample program for generation of sets. You can see output for an input of 5 on http://ideone.com/W1D5E.

Reply
naveen koati says:
February 26, 2011 at 8:10 PM
6 is the next highest number after 5
6(110),5(101)

Reply
Comment

Name (Required)

Email (Required)

Website URI

Your Comment (Writing code? please paste your code between sourcecode tags)


Notify me of followup comments via e-mail

Type the two words:




Subscribe without commenting
E-Mail:



Popular Tags
GATE
Java
Dynamic Programming
Divide & Conquer
Backtracking
Pattern Searching
Operating Systems
Recursion

Forum Latest Discussion
C/ Java programming
Last Post By: Vinay
Inside: Interview Questions
Amazon Interview Question for Software Engineer/Developer (0 - 2 Years) about Al [...]
Last Post By: algogeek
Inside: Interview Questions
Reversing doubly linked list
Last Post By: kartik
Inside: Linked List specific questions
c array question
Last Post By: karthik
Inside: C/C++ Programming Questions
Microsoft Interview Question for Software Engineer/Developer (Fresher) about CPu [...]
Last Post By: karthik
Inside: Interview Questions
Directi Interview Question for Software Engineer/Developer about Aptitiude
Last Post By: Ashish
Inside: Interview Questions
Merge Vs Quick Sort
Last Post By: karthik
Inside: Java specific Questions
Adobe Interview Question for Software Engineer/Developer (Fresher) about Aptitiu [...]
Last Post By: vengat
Inside: Interview Questions
Popular Posts
The two repeating elements in an array
Tree traversal without recursion and without stack!
All permutations of a given string
Next Greater Element
Check if array elements are consecutive
The first missing number
Intersection point of two Linked Lists
Lowest Common Ancestor in a BST.
Check if a binary tree is BST or not
Median of two sorted arrays
k largest elements in an array
Forum Categories
Interview Questions
C/C++ Programming Questions
Algorithms
Trees specific questions
Linked List specific questions
Multiple Choice Questions
Object oriented queries
GPuzzles
Operating Systems
Miscellaneous
Java specific Questions
Perl specific Questions
Subscribe
Recent Comments
Arpit Gupta on Write a C program to print all permutations of a given string
venky on Remove all duplicates from the input string.
Himanshu on Check if a binary tree is subtree of another binary tree
tuhin on Run Length Encoding
dejavu on Check if a binary tree is subtree of another binary tree
dejavu on Check if a binary tree is subtree of another binary tree
Steve on Write a function to get the intersection point of two Linked Lists.
Hemil on Get Level of a node in a Binary Tree


Wednesday, December 8, 2010

list palindrome

int check_palindrome(node_type *root)
{
int ret_val;
if(root)
{
ret_val=check_palindrome(root->next);
if(root->data != hroot->data)
return FALSE;
hroot=hroot->next;
return ret_val;
}
return TRUE;
}

LCA : lowest common ancestor

tree_node_type *LowestCommonAncestor( tree_node_type *root , tree_node_type *p , tree_node_type *q) { tree_node_type *l , *r , *temp; if(root==NULL) { return NULL; }

if(root->left==p || root->left==q || root->right ==p || root->right ==q)
{
return root;
}
else
{
l=LowestCommonAncestor(root->left , p , q);
r=LowestCommonAncestor(root->right , p, q);

if(l!=NULL && r!=NULL)
{
return root;
}
else
{
temp = (l!=NULL)?l:r;
return temp;
}
}
}
====================================================

Good and easy solution

Algorithm:
The main idea of the solution is — While traversing Binary Search Tree from top to bottom, the first node n we encounter with value between n1 and n2, i.e., n1 < n < n2 is the Lowest or Least Common Ancestor(LCA) of n1 and n2 (where n1 < n2). So just traverse the BST in pre-order, if you find a node with value in between n1 and n2 then n is the LCA, if it's value is greater than both n1 and n2 then our LCA lies on left side of the node, if it's value is smaller than both n1 and n2 then LCA lies on right side.

Implementation:

#include
#include

/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};

struct node* newNode(int );

/* Function to find least comman ancestor of n1 and n2 */
int leastCommanAncestor(struct node* root, int n1, int n2)
{
/* If we have reached a leaf node then LCA doesn't exist
If root->data is equal to any of the inputs then input is
not valid. For example 20, 22 in the given figure */
if(root == NULL || root->data == n1 || root->data == n2)
return -1;

/* If any of the input nodes is child of the current node
we have reached the LCA. For example, in the above figure
if we want to calculate LCA of 12 and 14, recursion should
terminate when we reach 8*/
if((root->right != NULL) &&
(root->right->data == n1 || root->right->data == n2))
return root->data;
if((root->left != NULL) &&
(root->left->data == n1 || root->left->data == n2))
return root->data;

if(root->data > n1 && root->data < n2)
return root->data;
if(root->data > n1 && root->data > n2)
return leastCommanAncestor(root->left, n1, n2);
if(root->data < n1 && root->data < n2)
return leastCommanAncestor(root->right, n1, n2);
}

/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

====================================================
http://goursaha.freeoda.com/DataStructure/LowestCommonAncestor.html

Find Lowest Common Ancestor in Binary Tree

Question:-You have a Binary Tree and Two node p , q.
You have to find the first common parent of p and q.


tree_node_type *LowestCommonAncestor(
tree_node_type *root , tree_node_type *p , tree_node_type *q)
{
tree_node_type *l , *r , *temp;
if(root==NULL)
{
return NULL;
}

if(root->left==p || root->left==q || root->right ==p || root->right ==q)
{
return root;
}
else
{
l=LowestCommonAncestor(root->left , p , q);
r=LowestCommonAncestor(root->right , p, q);

if(l!=NULL && r!=NULL)
{
return root;
}
else
{
temp = (l!=NULL)?l:r;
return temp;
}
}
}

hight of binary tree

Height of a Binary Tree
For a tree with just one node, the root node, the height is defined to be 0, if there are 2
levels of nodes the height is 1 and so on. A null tree (no nodes except the null node)
is defined to have a height of –1.
The following height function in pseudocode is defined recursively as discussed in
class. It should be easily to add a C++ version to the program binTree1.cpp.
int height( BinaryTree Node t) {
if t is a null tree
return -1;
hl = height( left subtree of t);
hr = height( right subtree of t);
h = 1 + maximum of hl and hr;
return h;
{