Вы находитесь на странице: 1из 143

Given a 4GB file of numbers. You are asked to find the product of K largest numbers.

The size of the main memory is 1 GB. Give an efficient method to find. 10 Tags: Amazon Data Structures SDE in test Question #9708961 (Report Dup) | Edit | History AL on July 06, 2011 External sort. Also k-select may handle this. Anonymous on July 06, 2011 but what about the products, i mean overflow?? If_else on July 06, 2011 How about min-heap? Reply to Comment Dan on July 06, 2011 Depending on how big the K is, we would split 4 into 1GB (or less) chunks. Then partition-select(k) each. O(n) Merge 4 pieces O(n), O(K) space. Again, partition-select(k). O(n) Multily.O(1) External sort is not the most effecient solution as you don't really need the whole file sorted. Reply to Comment Anonymous on July 06, 2011 Create Int32 array in size of 134217728, to get a bit for each possible number might be represented as Int32 (this array initiated as default to all 0). Read numbers from file one after the other (assuming there is a single number per line) For each number read set its corresponding bit (in case it wasn't set already) in the array (calculate appropriate location of corresponding int within the array and set the bit within) At all times maintain the maximum number you facing after finishing reading the all file go over all int numbers in arrays (starting from the int represents the bit of the largest number backwards), for each int != 0, print corresponding number represented by each set bit, until K bits where observed (or you finished searching the all array). Dan on July 06, 2011 Good one if numbers are int32 or less. Wouldn't work if longs or floats. Reply to Comment WgpShashank on July 07, 2011 we can do it using minHeap :) lest say file size is s=2^32 byte so number of integer it can have will be N=s/32 Algorithm 1.create min-heap of size K 2. for remaining elements read from file one by one compare it with root of heap if its greatre then root then replace it with root & call heapify 3. repeat whole algo until EOF our heap will contain the k largest elements , return product of all the elemnmts in heap will give us answer Time Complexity (O(k)+O(n-k)logk) Do Notify me if i am wrong or any other algo ?? Shashank

swathi on July 10, 2011 how do you calculate the product... Finding the k largest elements is easy and it can be easily done with bit arrays.. but the key point here is how do you do the calculation of k largest elements?? WgpShashank on July 10, 2011 @swathi if i am not wrong finally our heap will contain the k largest element then we can easily multiple them isn't it ?? you can do it using any tree traversal :) orted Array Merge Problem: Design an algorithm to merge two sorted positive integer arrays A and B. Size of array A is n and size of array B is m. Array A has m empty blocks(-1) at random places. Merge array B into A such that array A is sorted and does not have empty blocks. 16

Tags: Amazon Data Structures Software Engineer / Developer Question #9626448 (Report Dup) | Edit | History Anonymous on June 26, 2011 #include <stdio.h> void merge(int* pA, int* pB, int szA, int szB) { int i=0,j=0,k=0; /* First Assemble all -1s in the last of the array preserving the array sorted. */ while((i<szA)&&(j<szA)) { while((i<szA)&&(pA[i] != -1)) i++; while((j<szA)&&(j<i)) j++; while(pA[j]==-1) j++; if((j<szA)&&(i<szA)) { int temp = pA[i]; pA[i]=pA[j]; pA[j]=temp; } } i=szA-szB-1; j=szB-1; k=szA-1; /*merge from back side*/ while((k>=0)&&((i>=0)||(j>=0))) { if(i<0)

} } int main() { int A[]={-1,-1,8,19,-1,-1,-1,31,-1,38,65,-1,85,-1,-1,110,150,-1}; int B[]={24,51,90,130,140,180,190,220,250,260}; int i=0; merge(A,B,sizeof(A)/sizeof(int),sizeof(B)/sizeof(int)); while(i<(sizeof(A)/sizeof(int))) { printf("[%d]",A[i]); i++; } printf("\n"); } Time O(n), space O(1) lol on June 27, 2011 Just noticed your solution, and found our approach is same in principle. However, I used a queue to partition first array. I'm eager to hear your explanation how do you do it in O(1) space. Thanks. @lol on June 27, 2011 I don't expect this type of question from you. As u can c that code is not using any memory that is dependent on the size of any of the array. Both the array are sorted. Big array contains -1 at as many places as the size of small array. In big array to put all -1 at the end, I am swapping the -1 with first positive element which is after this current -1. So in this way all positive elements will bubble up together and all -1 will go at end. Since for any -1 the elements before -1 are smaller than the elements after -1 and I am choosing the first positive element after -1 therefore array will remain sorted after this step. lol on June 27, 2011

} else if(j<0) { pA[k]=pA[i]; i--; } else if(pA[i]<pB[j]) { pA[k]=pB[j]; j--; } else { pA[k]=pA[i]; i--; } k--;

pA[k]=pB[j]; j--;

Sorry to disappointed you. I was damn sleepy, had a quick nap, and now seems my brain is working :) I managed it in much simpler way (before reading your reply). Here's it : ideone.com/dITsA @lol on June 27, 2011 more readable and beautiful than mine. O(1) on June 29, 2011 nice solution Reply to Comment leeym on June 26, 2011 #include <stdio.h> void merge(int A[], unsigned int lA, int B[], unsigned int lB) { int i = 0, j = 0, k = 0; while (k < lA) { while (A[i] < 0) i++; if (i == lA) A[k++] = B[j++]; else if (j == lB) A[k++] = A[i++]; else if (A[i] < B[j]) A[k++] = A[i++]; else A[k++] = B[j++]; } } int main() { int A[] = { -1, -1, 8, 19, -1, -1, -1, 31, -1, 38, 65, -1, 85, -1, -1, 110, 150, -1}; int B[] = {24, 51, 90, 130, 140, 180, 190, 220, 250, 260}; int i = 0; merge(A, sizeof(A) / sizeof(int), B, sizeof(B) / sizeof(int)); while (i < (sizeof(A) / sizeof(int))) { printf("[%d]", A[i]); i++; } printf("\n"); } Anonymous on June 26, 2011 your solution is not working in many cases. I think you should merge from last otherwise u'll overwrite and loss the array element. check with this: int A[]={8,19,31,38,65,85,110,150,-1,-1,-1,-1,-1,-1,-1,-1-1,-1}; int B[]={24,51,90,130,140,180,190,220,250,260}; Reply to Comment someone on June 26, 2011

It seems same as its trivial counterpart. Start merging arrays from the back, means start comparing from the highest elements of both arrays. 1) i = m-1 and j = k = n-1. while(A[j]==-1) j-2) run loop till k>=0 3) if(A[j] == B[i]) A[k] = A[k-1] = A[j]; k = k-2; i--; while(A[j]==-1) j--; 4) else if(A[j] > B[j]) A[k] = A[j]; k--; while(A[j]==-1) j--; 5) else A[k] = B[i]; k--; i--; Reply to Comment lol on June 27, 2011 Using a deque (to keep track of sorted index of -1), array A can be rearranged such that all -1s are at end, and the rest are sorted. It takes O(n) time. Now, merge from back. lol on June 27, 2011 a correction: a queue is sufficient here. deque would be overkill. lol on June 27, 2011 Ignore this stupid post. It's too obvious to find O(1) space solution. If interested, look here : ideone.com/dITsA Reply to Comment iCoder on June 28, 2011 IMO, the solutions above are O(n+m) time. Reply to Comment Anonymous on June 29, 2011 /* The class name doesn't have to be Main, as long as the class is not public. */ class Main { public static void merge(int[] big, int[] small) { if (big == null || small == null) { return; } // Shift all positive numbers in bigger array to right. keep them sorted. for (int i = big.length - 1, j = i; j >= small.length; i--) { if (big[i] > 0) { big[j--] = big[i]; } } // Merge till the small array is exhausted. for (int i = 0, pBig = small.length, pSmall = 0; pSmall < small.length; i++) { if (pBig >= big.length) { big[i] = small[pSmall++]; } else { big[i] = big[pBig] <= small[pSmall] ? big[pBig++] : small[pSmall++]; } } }

public static void main (String[] args) throws java.lang.Exception { int[] big = {2, -1, 7, -1, 10, -1, 11, -1, 18, -1, 22, -1, 24, -1, 27, -1, 29}; int[] small = {4, 13, 24, 27, 28, 28, 30, 30}; System.out.println(Arrays.toString(big)); System.out.println(Arrays.toString(small)); merge(big, small); System.out.println(Arrays.toString(big)); }

Reply to Comment Anonymous on July 05, 2011 void mergeArrays(int* a, int sizeOfa, int* b, int sizeOfb) { int i = sizeOfa - 1; int j; int x = i; while (a[i] != -1 && i >=0) { i--; x--; } while (i >= 0) { while (a[i] == -1) i--; if (i >= 0) { exchange(a, i, x); i--; x--; } } i = x + 1; x = 0; j = 0; while (j < sizeOfb && i < sizeOfa) { if (a[i] <= b [j]) { exchange(a, x, i); x++; i++; }

else { a[x] = b[j]; x++; j++; }

while (j < sizeOfb) { a[x] = b[j]; x++; j++; } } Read a file of this format: japan usa japan russia usa japan japan australia Print the output in the following format: <country> : <count> So for above file output would be: japan : 4 usa : 2 australia : 1 russia : 1 Note that since australia and russia both have count as 1, the name are sorted, 'a' before 'r'. Do it in the most efficient way. 15 Tags: Amazon Data Structures Software Engineer / Developer Question #9538861 (Report Dup) | Edit | History Vikas on June 19, 2011 import java.util.*; public class hash { public static void main(String[] args) { String str[] = {"russia","japan","russia","india"}; int len = 4; Hashtable ht = new Hashtable();

int i=0; while(i<len) { String c = str[i]; System.out.println("c :"+c); Integer intg = (Integer) ht.get(c); if(intg ==null) ht.put(c,new Integer(1)); else ht.put(c,new Integer(intg.intValue()+1)); i++; } Enumeration k = ht.keys(); while(k.hasMoreElements()){ String key = (String) k.nextElement(); System.out.println( key + " > "+ ht.get(key) ); } } } Upt on June 19, 2011 Solution is incomplete. You are not sorting the same value members. Anonymous on June 20, 2011 why we need to sort ..?...same value members are getting hashed together... @vikas on June 20, 2011 the output of your solution will vary based on the different combination of same input. but as per the question, the output: 1. should show the <country>:<count> based on the decreasing order of count. 2. and if there is a tie then show the country which comes first in alphabetic order. Anonymous on June 22, 2011 What if you had japan and jamaica ? Both will be hased togather Anonymous on June 22, 2011 What if you had japan and jamaica ? Both will be hased togather Reply to Comment Upt on June 19, 2011 After inserting all of them in the hashMap we can make tree sets of the same value types. Reply to Comment Anonymous on June 20, 2011 Correct algorithm is TRIE tree Reply to Comment memo on June 20, 2011 Most efficient doesn't mean anything. Most efficient in space, time, what? Reply to Comment scot on June 21, 2011 This solution takes too much memory but the average time complexity is O(n log n) Have a hash table with words as the key and its frequency as the value. Then have a binary search on the frequency of words, each node in the binary search tree will have two values one is the

frequency of words on which the binary search tree is built and the other is reference to another binary search tree which contains the words for this frequency. When ever we encounter insert a word into the hash table insert it in the binary search tree also and whenever a word s frequency is altered in the hash table , lets say a word 'japan' frequency is increased from 2 to 3 , then delete japan from the 'word binary search tree' which referenced by the 'frequency binary search tree' node which has the value of 2 and insert into the 'word binary search tree' referenced by the 'frequency binary search tree' node which has got the value 3 in it. To display the the output in the desired format do post-order traversal of the 'frequency binary search tree' and in-order traversal of the corresponding 'word binary search tree' pointed each node of the 'frequency binary search tree' mohit89mlnc on July 11, 2011 the time complexity should be O(mlogn) (upper bound) where m is length of largest string in the set. In O("n"logn) first n does not make any sense.Tell me if i am wrong. A string is well formed if for every "(" left parenthesis you have matching right one ")".In the same way every ")" should have a preceding "(".write a program finds if a string is wellformed . This is for the written test 19 [Full Interview Report] Tags: Amazon Data Structures Software Engineer / Developer Question #9447750 (Report Dup) | Edit | History Anonymous on June 12, 2011 #include <stdio.h> #include <string.h> const char* isValidString(char* pStr) { int len=strlen(pStr), index=0, count=0; if(pStr[index]==')') return "INVALID STR"; for(;index<len;index++) { if(pStr[index]=='(') count ++; if(pStr[index]==')') count --; if(count < 0) return "INVALID STR"; } return (count == 0)?("VALID STR"):("INVALID STR"); } int main() { char str[100]; gets(str); printf("%s\n",isValidString(str)); return 0; } ani on June 12, 2011 nice Reply to Comment whataheck on June 12, 2011

a) push when u encouter ( b)pop when u encounter ) c)It means before evry push the stack shud be empty else return false .. pansophism on June 13, 2011 classic Reply to Comment Anonymous on June 12, 2011 @whataheck - Your would not handle case like '((()))'...it is good for case '()()()' only Rakesh Kumar on June 13, 2011 he just needs to check at the end whether stack is empty or not and not before every push Reply to Comment UT on June 13, 2011 Assumption: The string ONLY contains '(' and ')'. bool check_valid_or_not( string* s) { int counter_for_left_paren = 0; int counter_for_right_paren = 0; for(int i = 0; i< s.length(); i++) { if(s[i] == '(') counter_for_left_paren++; else counter_for_right_paren++; if( counter_for_right_paren > counter_for_left_paren) return false; } return (counter_for_left_paren==counter_for_right_paren); } Time Complexity:O(n) Space complexity:O(1) If anything is wrong, feel free to correct me. Thanks in advance. Srik on June 13, 2011 Hey, what about a string "()))((" . Above string is not wellformed. I prefer to go for using stack data structure UT on June 13, 2011 my solution will return false with your case you mentioned. what is wrong with that? Reply to Comment Whataheck on June 13, 2011 I think the stack approach wud work because the question clearly says .. for every ")" should have a preceding "(". Hence the case '((()))' need not be considered .Wat say ? someone on June 13, 2011 'preceding' does not necessarily imply that it would be 'immediately preceding' it. so the condition to be checked is simply 'when you pop, stack should not be empty already' Which data structure is fast when you want to sort or search Linked List or Array? 5 [Full Interview Report] Tags: Amazon Data Structures Software Engineer / Developer Question #9289896 (Report Dup) | Edit | History

Anonymous on June 11, 2011 Both have their limitations but being said the elements are arranged either in array or in linked list, the answer should be array. Because it has index associated with each element and also swapping is easy. Reply to Comment Anonymous on June 12, 2011 array has cache invalidation problems if you're trying to update...i would have said linked list for sort and array for search... Reply to Comment someone on June 13, 2011 for searching both take linear time.. for sorting array seems faster but with skip list (complex implementation compared to array) can reach very near to array's sort. Anonymous on June 14, 2011 Searching an unsorted array takes linear time, but you can do binary search on a sorted array. Reply to Comment Anonymous on July 02, 2011 for sorting both are equivallent i think because in both cases we can do o(nlgn) optimal solution one exception is that we can apply the counting sort in arrys in O(n) time if the ranges of numbers are given but not in linked list as far as searching is concerned i think array is much better ecause many times we have a sorted raay and to serach that by binary search we can do the binary serach in o(lg n) time but this will not going to be possible in the case of the linked lists. Reply to What is Hashtable, using which data structure hash table is implemented 4 [Full Interview Report]

Tags: Amazon Data Structures Software Engineer / Developer Question #9114360 (Report Dup) | Edit | History unknown on June 11, 2011 i feel that it will be implemented using an array.. Reply to Comment Algorithmist on June 13, 2011 Depends on collision resolution strategy. If open addressing, then array of nodes. If separate chaining with list, then array of list. If Separate chaining with other structures like bst, then array of trees Anonymous on June 21, 2011 hey algorithmist, collision resolution comes after first building the hashtable. First for building the hashtable only array will be used. So, if collision occurs then we can use list or tree to traverse the different values for the same key, but still the slot will be only in the array.. Reply to Comment Anonymous on June 22, 2011 hashtables are also built using self balancing binary trees

Given a binary matrix of N X N of integers , you need to return only unique rows of binary arrays eg: 01001 10110 01001 11100 ans: 01001 10110 11100 28

Tags: Google Algorithm Coding, Data Structures, Algorithms Data Structures Matrix Software Engineer Question #9478119 (Report Dup) | Edit | History Ishan on June 09, 2011 Find the value of each row, as in 2^(n-1)*a[0][i]+2^(n-2)*a[1][i]+...+2^(0)*a[n][i] then compare values and write rows which have difft values nee.agl on June 09, 2011 basically you are hashing the values. But then comparing those values takes the major time.. O(nlogn) bec we'll have to sort the hashed values. We can use the hashing scheme as you suggested or simply sort them directly as string.. we can just directly sort in O(nlogn) n then print unique values in O(n) times.. nee.agl on June 09, 2011 Sorting n items of n length string would be O(n*nlogn). so better use hashing... Anonymous on June 13, 2011 Wouldnt it overflow if n is greater than bits in word of the platform. mnit.rohit on June 15, 2011 TO find the hash u need to read all the digits in a row for all rows that means total digits accessed is n^2.Hence O(n^2) rahul on June 21, 2011 @ishan sorry didnt get u , can u plz explian with example how u came to this fact "Find the value of each row, as in 2^(n-1)*a[0][i]+2^(n-2)*a[1][i]+...+2^(0)*a[n][i] then compare values and write rows which have difft values" & also u r saying to add row by but u r adding column by column as a[0][i]+a[1][i]...a[n][i]..please reply asap.. Thanks in advance rahul on June 24, 2011 @all sorry didnt get u , can u plz explian with example how u came to this fact "Find the value of each row, as in 2^(n-1)*a[0][i]+2^(n-2)*a[1][i]+...+2^(0)*a[n][i] then compare values and write rows which have difft values" & also u r saying to add row by but u r adding column by column as a[0][i]+a[1][i]...a[n][i]..please reply asap.. Thanks in advance Reply to Comment Rakesh Kushwaha on June 09, 2011

BinaryTree { int info ; int *left ; int *right ; vector<int> rowNoVec; // Row Number it belongs to ,same path can belong to more than one row }; Vector<BinaryTree> VectorofTree; // We need to have vector of n trees root Number 1 to N. //Working above data structure , leaf Node we have information how many row it belongs, we can delete them. Reply to Comment Anonymous on June 09, 2011 TRIE data structure can work fine for this problem!!! asdf on June 09, 2011 how to implement it? Anonymous on June 09, 2011 ukkonen could do that in O(n)! google the algorithm (Ukkonen suffix tree online). the only change to do = count leaf nodes during tree building process Reply to Comment Anonymous on June 09, 2011 xor each row with every other. nee.agl on June 09, 2011 O(N^2)! Rakesh Kushwaha on June 09, 2011 Please note that problem is talking about 0 to N number , not binary number nee.agl on June 10, 2011 Ya.. so wud be O(n^3)... Reply to Comment Anonymous on June 10, 2011 We can't solve this problem quickly than O(n * n), because we must at least review all digits. My solution is create HashSet then do cycle for each row and calculate its hash if HashSet not contain current hash we write this row and add it to HashSet. Reply to Comment KVF on June 10, 2011 We can't solve this problem quickly than O(n * n), because we must at least review all digits. My solution is create HashSet then do cycle for each row and calculate its hash if HashSet not contain current hash we write this row and add it to HashSet. Anonymous on June 12, 2011 can you please elaborate please how to store the above data in HashSet, do you mean store hashes of each element? if that's the case collisions might occur Orr on June 13, 2011 How to store the above data in a HashSet: Calculate the decimal representation of the binary number represented by the string of bits. Use this number as the hash key. Reply to Comment Supraja on June 12, 2011 Hi

The return should be inplace ? And Java has Arrays.equals(arr1, arr2); Thanks S Reply to Comment Supraja on June 12, 2011 Also constructing a trie if N is not very big is not so optimal I guess ? How much is optimization important in interviews ? Anyone ? Thanks S Abhi on June 14, 2011 Constructing a TRIE will take O(log(n)) for every string in the average case and O(n) for the worst case. So total time taken will be O(n*log(n)) in average case and O(n^2) for worst case Abhi on June 14, 2011 My bad. Looking up for a binary string in a TRIE will take O(n) time and not O(logn). So the whole operation will be O(n^2). Anonymous on June 14, 2011 Space requirement for TRIE will be O(n^2) whereas will be lesser for hashing So, hashing seems to be a more viable option.Correct me i I am wrong Reply to Comment Abhi on June 14, 2011 Here is my code for this..taking N=5 here for example #include<stdio.h> #define N 5 int main() { int a[N]={0,0,0,0,0},b[N]={-1,-1,-1,-1,-1},p,i,j; int A[][N] = { {1,1,0,0,1}, {1,1,0,0,1}, {1,0,0,0,1}, {1,1,0,0,1}, {1,0,0,0,0} }; // a=(int *)malloc(5 * sizeof(int)); for(i=0;i<N;i++) {for(j=N-1;j>=0;j--) {if(A[i][j] == 1) {a[i] += pow(2,(N-1)-(j));} }//printf("%d\n",a[i]); } //b=(int *)malloc(5 * sizeof(int)); // b={-1,-1,-1,-1,-1}; for(i=0;i<N;i++) {

j=a[i] % N; p=0; while(b[j] != -1) { if(b[j] != a[i]) j = (j+1)%N; else { p=1; break; } } if(p!=1) { for(p=0;p<N;p++) printf("%d ",A[i][p]); b[j] = a[i]; printf("\n");

} } getch(); return 0; }

Computing decimal equivalent takes O(n^2) time and so does hashing.. rahul on June 26, 2011 @Abhi Please Explain the Algorithm With Example Gud Work.. Please reply asap... Learner on July 06, 2011 @abhi algorithm to rahul he is computing the hash of each of the rows by converting them to decimal numbers in matrix and saving it a matrix a. He is using hash table array b. he is using hashing with linear probing to check if the the current row value is colliding in the hash table if its colliding he is ignoring that, if not he is printing the row. Reply to Comment Anonymous on June 15, 2011 since the matrix is of size NxN, the maximum value of each row when computed will always lie between 0 to 2^N-1. Hence using an extra space of size 2N-1, we can solve it in O(N). A rooted binary tree with keys in its nodes has the binary search tree property (BST property) if, for every node, the keys in its left subtree are smaller than its own key, and the keys in its right subtree are larger than its own key. It has the heap property if, for every node, the keys of its children are all smaller than its own key. You are given a set of n binary tree nodes that each contain an integer i and an integer j. No two i values are equal and no two j values are equal. We must assemble the nodes into a single binary tree where the i values obey the BST property and the j values obey the

heap property. If you pay attention only to the second key in each node, the tree looks like a heap, and if you pay attention only to the first key in each node, it looks like a binary search tree.Describe a recursive algorithm for assembling such a tree 19

Tags: Google Algorithm Data Structures Trees and Graphs Software Engineer Question #9249473 (Report Dup) | Edit | History Vipul on June 09, 2011 I think we can do it the following way: Sort the nodes in decreasing order of their j values and then simply build the BST according to the i values starting from the first node in the obtained sorted list. The first node will be the root. For example, let the given nodes (i,j pairs) be: (12,6) (18,25) (19,10) (17,5) (19,10) i.e. 5 nodes nodes after sorting in decreasing order according to j values: (18,25) (16,11) (19,10) (12,6) (17,5) So the tree would be something like this: (18,25) | || (16,11) (19,10) | || (12,6) (17,5) As we can see, the i values obey BST property and the j values obey MaxHeap property. Tell me, what do u think? Vipul on June 09, 2011 Sorry for the previous messed up tree.... For example, let the given nodes (i,j pairs) be: (12,6) (18,25) (19,10) (17,5) (19,10) i.e. 5 nodes nodes after sorting in decreasing order according to j values: (18,25) (16,11) (19,10) (12,6) (17,5) So the tree would be something like this: (18,25) | | | (16,11) (19,10) | | | (12,6) (17,5) Rahul on June 09, 2011 @vipul can write the code for it..i need to aware for Time Complexity ..???

Reply to Comment Rahul on June 09, 2011 @vipul can write the code for it..i need to aware for Time Complexity ..??? Vipul on June 09, 2011 Time complexity will be O(nlog n) Rohit on June 09, 2011 But the requirement is of a recursive solution Vipul on June 09, 2011 Here is my recursive solution: #include<stdio.h> #include<stdlib.h> struct node { int i; int j; struct node *left; struct node *right; }; void mySwap(struct node **n1, struct node **n2) { struct node *tmp; tmp = *n1; *n1 = *n2; *n2 = tmp; } struct node *myInsert(struct node *root, struct node *nodeToInsert) { if(root == NULL) { return nodeToInsert; } else { if(nodeToInsert->i <= root->i) { root->left = myInsert(root->left,nodeToInsert); } else { root->right = myInsert(root->right,nodeToInsert); } return root;

void myFunc(struct node *arr[], struct node **resultTree, int size) { if(!size) return; int ind; int maxInd = 0; for(ind=0;ind<size ind++) //Finding the node with maximum j if(arr[ind]->j > arr[maxInd]->j) maxInd = ind; *resultTree = myInsert(*resultTree,arr[maxInd]);//inserting node with maximum j value mySwap(&arr[maxInd],&arr[size-1]); myFunc(arr,resultTree,size-1); } int main() { int n; struct node *arr[100]; scanf("%d",&n); int ind; int ival,jval; struct node *result = NULL; for(ind=0;ind<n;ind++) { arr[ind] = (struct node*)malloc(sizeof(struct node)); printf("Enter the i and j values for the %dth node.\n",ind); scanf("%d%d",&ival,&jval); arr[ind]->i = ival; arr[ind]->j = jval; arr[ind]->left = NULL; arr[ind]->right = NULL; } myFunc(arr,&result,n); //levelOrderTraversal(result); //PreOrderTraversal(result); for(ind=0;ind<n;ind++) free(arr[ind]); return 0; } Plz find bugs if any :) V.Krestyannikov on June 10, 2011 Your time complexity will be O(n * n) in the worse case. rahul on June 21, 2011 @vipul Awesome work Man Keep it up...:)

Reply to Comment JuvN on June 11, 2011 This Solution is similar to above one, but more easier to understand in recursion point of view: 1. Find nodes with biggest j (we call it pivot) in node array. 2. Partition the array into two parts, all elements in left part have i smaller than i of pivot while all elements in right part have i bigger than i of pivot. 3. Use pivot as root of tree. 4. set left sub-tree of root as a tree built from left part of array. 5. set right sub-tree of root as a tree built from right part of array. 6. return root. Average time complexity: O(NlogN) Worst time complecity: O(N^2) Anonymous on June 13, 2011 Maybe I don't understand completely your solution, but in the following case: (3,7)(2,6)(5,5)(1,4)(4,3) partitioning values according step 2, in the first place the node (4,3) will be put in the right tree while it should be put in the left tree. Could you help me to understand your solution? thank you Reply to Comment Mobile Lover on June 13, 2011 If the tree has heap property, we should just concentrate on creating the heap. We can create only one heap from a node set while there are n different BST. If at any time it does not follow BST property, then such a tree cannot be created through the given set of nodes. Reply to Comment china.taoqin on June 14, 2011 1. Sort the node by the first value and keep it in array 1, coz the mid-order reversal of a binary search tree is a fully sorted array. 2. Sort the node by the second value and keep it in array 2. So the process becomes to keep finding the node in array 1 which has the smallest value in array 2, the left-side of that node in array 1 is its left subtree and the right-side is the right subtree. Recursive alogrithm in array 1 would be more complex in time because for each part it is necessary to find the node which has the smallest second value in the sub-part. But if you recursively construct the tree via array 2 and take a note of parrent node, the time complexity should be O(nlogn + n) = O(nlogn) totally. Reply to Comment china.taoqin on June 14, 2011 Using the array2, construct BST O(nlogn + nlogn). Sorry:) Reply to Comment Solution Part 1 on June 17, 2011 package org.nrec.probs; import java.util.Comparator; public class MNodeI implements Comparator<MNode>{ @Override public int compare(MNode arg0, MNode arg1) { if(arg0.i > arg1.i){ return 1; }else if(arg0.i < arg1.i){ return -1; }

return 0; } } Sorry for bad formatting on June 17, 2011

package org.nrec.probs; import java.util.Comparator; public class MNodeI implements Comparator<MNode>{ @Override public int compare(MNode arg0, MNode arg1) { if(arg0.i > arg1.i){ return 1; }else if(arg0.i < arg1.i){ return -1; } return 0; } }

Reply to Comment Solution Part 2 on June 17, 2011

package org.nrec.probs; import java.util.Comparator; public class MNodeJ implements Comparator<MNode>{ @Override public int compare(MNode arg0, MNode arg1) { if(arg0.j > arg1.j){ return -1; }else if(arg0.j < arg1.j){ return 1; }

} }

return 0;

Reply to Comment Solution Part 3 on June 17, 2011

package org.nrec.probs; import java.util.ArrayList; import java.util.List; import java.util.Collections; import java.util.Stack; public class MNode { public MNode(int i ,int j){ this.i = i; this.j = j; } public MNode(){ } public MNode(MNode temp){ this.i = temp.i; this.j = temp.j; } public String toString(){ return " i :: " + i + " j :: " + j; } public int i; public int j; MNode left; MNode right; public MNode createBSTHeap(List<MNode> numbers){ if(numbers == null || numbers.size() == 0){ return null;

} Collections.sort(numbers,new MNodeJ()); MNode temp = numbers.get(0); Collections.sort(numbers,new MNodeI()); int index = numbers.indexOf(temp); System.out.println("index :: "+index); System.out.println("temp :: "+temp); System.out.println("Total :: "+numbers); List<MNode> leftSubTree = null; try{ leftSubTree = (List<MNode>) numbers.subList(0, index); }catch(Exception e){

leftSubTree = null; } List<MNode> rightSubTree = null; try{ rightSubTree = (List<MNode>) numbers.subList(index+1, }catch(Exception e){ rightSubTree = null; } MNode root = new MNode(temp); System.out.println("this node :: "+ root); System.out.println("leftSubTree "+leftSubTree); System.out.println("rightSubTree "+rightSubTree); if(leftSubTree != null) root.left = createBSTHeap(leftSubTree); else root.left = null;

numbers.size());

if(rightSubTree != null) root.right = createBSTHeap(rightSubTree); else root.right = null; System.out.println("Returning back \n node :: "+ root); System.out.println("Left :: "+root.left); System.out.println("Right :: "+root.right); return root; } public void preorderI(MNode root){

if(root!=null){ preorderI(root.left); System.out.print(root.i+","); preorderI(root.right); }

public void preorderJ(MNode root){ if(root!=null){ preorderJ(root.left); System.out.print(root.j+","); preorderJ(root.right); } } // public static void main(String[] args){ (12,6) (18,25) (19,10) (17,5) (19,10) MNode mnode1 = new MNode(12,6); MNode mnode2 = new MNode(18,25); MNode mnode3 = new MNode(19,10); MNode mnode4 = new MNode(17,5); MNode mnode5 = new MNode(19,10); List<MNode> list = new ArrayList<MNode>(); list.add(mnode1); list.add(mnode2); list.add(mnode3); list.add(mnode4); list.add(mnode5); MNode mnode = new MNode(); MNode root = mnode.createBSTHeap(list); System.out.println(""+root.left); System.out.println(""+root.right);

mnode.preorderI(root); System.out.println(""); mnode.preorderJ(root); } }

Reply to Comment Edit on June 17, 2011 The traversal is inorder .... although by mistake I have named it as preorder !!! Suggest a DS for web server to store history of visited pages. The server must maintain data for last n days. It must show the most visited pages of the current day first and then the most visited pages of next day and so on. 9

Tags: Google Algorithm Data Structures Software Engineer Question #9464167 (Report Dup) | Edit | History Rakesh Kushwaha on June 08, 2011 struct linkInfo { char *link; uint refcount; }; struct Historydata { uint linkInfoVecIndx; // uint let unsingned uint time_t timestamp; // let say there is time_t type }; vector<Historydata *> HInfovec; vector<linkInfo *> LinkInfovec; Hashmap<char *,uint,<hashfun>> Hmap; int RecordlinkIntoHis(char *hreflink, time_t timestamp) { Hashmap<char *,uint,<hashfun>>::iterator it; if ((it = Hmap.find(hreflink)) != Hmap.end() ) // strinf found in haspmap { LinkInfovec[it->second]->refcount++ // it->second has index to vecor } else { linkInfo *l = new linkInfo; Historydata *h = new Historydata; l->link = hreflink; l->refcount = 1; LinkInfovec.push_back(l); Hmap[link] = LinkInfovec.size() -1; // store indx h->linkInfoVecIndx = LinkInfovec.size() -1; h->timestamp =h->timestamp; } } anonymous on June 08, 2011 When you care to take a problem seriously, and code it; isn't it better if you kindly post code with proper formatting using " " and " ". Also, why don't you give some details how the data structures interact. Thanks. Anonymous on June 09, 2011 You have to sort the vector based on ref count to give the most visited pages per day Reply to Comment

krishna on June 09, 2011 I think struct day { int day ; MaxHeap h; struct day* next; }; this will do . while heap stores the pages, update,delete and insert takes O(logn)time . Reply to Comment krishna on June 09, 2011 I think struct day { int day ; MaxHeap h; struct day* next; }; this will do . while heap stores the pages, update,delete and insert takes O(logn)time . Reply to Comment Ashish Kaila on June 09, 2011 Heaps won't work here since updates need to happen fast as well. To find an element in a heap takes O(n). So I would keep a list of B-Tree or BST with keys equal to the hit count. To report pages in decreasing order of hits, traverse the BST in the inverse in-order manner printing right subtree, then parent node and then left subtree. Hence you an update, search and insert in O(logn) time. Then you can maintain a list of these trees with each tree representing page hits per day. Reply to Comment Supraja on June 12, 2011 Hi Wont something like a leaky stack work here ? or will that kind of implementation be considered ? A normal with tos as today but when stack becomes full remove the bottommost page. Thanks S Reply to Comment sudo on June 12, 2011 A hashmap of hashmaps. Outer hmap key is the date and inner level map key is the link to the site with the value being the hit count. Reply to Comment kkishore on June 15, 2011 Splay trees??? Write a data structure to count number of connections on web server in last 1 minute. 6

Tags: Google Algorithm Data Structures Software Engineer / Developer Software Engineer Question #9405544 (Report Dup) | Edit | History

bylike on June 04, 2011 red-black tree. Use the connection starting time as the key. Also keep the number of nodes that are later than the current node as an additional information (can be maintained in logn). Whenever you want to get the count of connections within the last time t, just use the time as an index and find the first node. The number of nodes information on it will be the answer. It can be done also in logn. Reply to Comment Ashish Kaila on June 05, 2011 I would use a circular array with cumulative connections stored in indices. To calculate how many connections are on web server in last minute, just take difference between the current index and the previous one. wgpshashank on June 22, 2011 seems to fine to me. Reply to Comment Harshit on June 05, 2011 Ill suggest using a multimap with the key as the time when the connection was established and value as the connection id and the status(closed or open). Given a time , go through all the keys and retrieve the keys under the given time frame. Can be done in O( N log N ) worst case. Reply to Comment rsl on June 05, 2011 circular array + sum integer. On new entry (x = number of connections in last second): add entry to array (index 0) sum = sum+x sum = sum - array(current index - 60); remove last entry from array. Reply to Comment krishna on June 09, 2011 a hash vector of size 60 will do i guess . ie int count[60]. Reply to Comment How to find the median from a randomly generated 1 billion integers? Hint: To think of using specific data structure or approach so that the entire integer need not be sorted (to identity integer such that half the integers fall to the left and other half fall to the right of it) 10

Tags: Amazon Algorithm Data Structures Software Engineer / Developer Question #9406138 (Report Dup) | Edit | History loser on June 04, 2011 median of medians recursively? pansophism on June 06, 2011 smart choice Reply to Comment Anonymous on June 04, 2011

selection algorithm? Reply to Comment DarkLord on June 04, 2011 It can be done by modifying the partition algo of quicksort... Reply to Comment swathi on June 05, 2011 it should be an external sort Reply to Comment molla on June 05, 2011 it should be an AVL tree,then root is always the median. Reply to Comment Anonymous on June 06, 2011 Select Algorithm...no need to sort the array..linear time Reply to Comment Ashish Kaila on June 09, 2011 Modify quick sort and partition until you reach the middle: 1. int index = Partition (A[1,N], billion / 2); 2. if index < billion/2 => Partition(A[index + 1, N, billion / 2 - index); 3. if index > billion/2 => Partition(A[0, N, index - billion/2); 4. if index == billion / 2 => Find index1 in A[index+1, N] such that index1 is min 5. Return (index + index1) / 2; Reply to Comment Anonymous on June 14, 2011 Use two heaps. I am assuming that you have two classes available (minheap and maxheap) and they each have a size method. public double findMedian(final int[] numbers) { MinHeap min = new MinHeap(numbers.length); MaxHeap max = new MaxHeap(); for (int i = 0; i < number.length; i++) { min.push(numbers[i]); } //now even out the sizes as close as possible if (min.size() % 2 == 0) { while (min.size() > max.size()) { max.push(min.pop()); } return ((min.pop() + max.pop()) / 2); } else { while (min.size() > max.size()+1) { max.push(min.pop()); } return min.pop(); } } Anonymous on June 21, 2011 @ above, Do you know the meaning of median? Median is not mean. What is the meaning of this statement "return ((min.pop() + max.pop()) / 2)" ---> don't try to return the average.

Don't just copy the code from any book and paste it here.. Design a system to calculate the number of unique words in a file.. 1) What if the file is huge ? (i.e cannot fit in the main memory) 2) Assuming that you have more than one computers available, how can you distribute the problem ? 10 [Full Interview Report]

Tags: Facebook Data Structures Software Engineer Question #9382096 (Report Dup) | Edit | History Anonymous on June 02, 2011 1) Merge sort 2) Hadoop + Hive Reply to Comment S on June 02, 2011 1. I think you are thinking of external sorting. In any case, you don't need to sort the words... just use a hash-map to store the occurrences of each word. Reply to Comment Yashwanth Redd y on June 02, 2011 have a Counter and a hashmap in the external memory. Whenever a new word comes in add it to hastable and increment the counter . Do the process and increment the counter only if the word is not present in Hashtable . Reply to Comment Ashutosh on June 02, 2011 Divide the file in chunks. Use Map reduce methodology And Apply Merge sort on each chunk. ss (the person who posted this problem) on June 02, 2011 "Use map reduce methodology" <<-- Thats too high level. The interviewer was interested in the inner workings of the 'reduce' phase. Ashutosh on June 03, 2011 There Can be multiple ways to implement 'reduce' phase. Moreover it depends on your algorithm too. Suppose, You are dividing the file chunks on different nodes. and the nodes are removing the duplicate nodes i.e A,B,C,D,C,A ===> B,D Now in 'reduce' phase: reassemble the data and divide into chunks then re-distribute on nodes. This works in similar ways as your merge sort works. At the end you will get only unique nodes. Total complexity is N(log N). Better solutions welcome. lol on June 04, 2011 As the interviewer asked about "reduce phase" in details, here's my approach: 1. split the file in equal size. each computer will get it's chunk.

2. for each chunk, create hash table. 3. union two hash tables of computers (i) and (i+1) 4. continue step 3, in a binary tree format (bottom-up fashion). complexity analysis: n = total # of words in file k = # of computers step 1 : O(n) step 2 : average complexity O(n) step 3 & 4: there are total O(log k) levels in the tree each level costs average O(n) time so, total complexity O(n log k) Reply to Comment Anonymous on June 04, 2011 why not simply inserting all your words in a Set, i.e. HashSet and then mySet.size() when the computation is ended? In a multi-threaded environment you can safely use ConcurrentSkipListSet unless there are some sort of compound operations. If the number of words is N, the complexity is O(N) (if an HashSet is used) or O(NlogN) if a SkipList is used. anon on June 04, 2011 Probably you overlooked the thing of "huge" file. You can have a 5GB file which won't be fitted into your memory. Reply to Comment bothell on June 05, 2011 using hash counting and then map-reduce for the size issue. There's an array in sorted order. But it has been rotated by N positions. The value of N can be anything from 0, and is unknown to us. In this scenario, how will you find a number X efficiently. Give a solution that works for O(n). I suggested for 2 searches of log n. But interviewer wanted more better solution. 17

Tags: Amazon Data Structures Software Engineer Question #9286473 (Report Dup) | Edit | History lol on May 23, 2011 Are you sure? I think there exists NO algorithm to solve it < O (logn) time. sanjeevsince90 on May 23, 2011 I was asked to do so. I don't really know. I tried my level best to make it as optimized as possible. Pandit on June 22, 2011 @sanjeevsince90, with extra space we can do less than O(lg n), but without that we cannot Reply to Comment Anonymous on May 23, 2011 it can be done in only one binary search pass. let start =0, end = n-1 look at the middle.

2 CASES: a)either the first half is again a rotated sorted array and the second half is sorted... b)the first half is sorted and the second half is rotated sorted array. in either case we can throw away one half and work with the othe half... we dont need to find the pivot element. Anonymous on May 24, 2011 Can you post some sample code to achieve this? Reply to Comment Kishore on May 24, 2011 When a sorted array is rotated, we end up with two parts. ASC sorted and a DESC sorted. So when we get a pivot, we end up with three cases. //Case I, where pivot ended in ASC array. Binary search in arr[pivot-1] < arr[pivot] < arr[pivot+1] //Case II, where pivot is in DESC array arr[pivot-1] > arr[pivot] > arr[pivot+1] //Case III, where pivot is first element of the initial array before rotation. So chose either Left or Right array based on search value. arr[pivot-1] > arr[pivot] < arr[pivot+1] e.g. 13,10,9,7,5, 2,3,4 |---DESC-----|--ASC--| Writing binary search program is same if we take care of above cases. bool search(arr, start, end, value) { if(start < end) return false; pivot = start+end/2; if(pivot == value) found; int case = GetPivotCase(); //utility function that would return 1,2,3 based on our above conditions. switch(case) { case 1: //ASC array if(value > arr[pivot]) search(arr, pivot+1, end, value); else search(arr, start, pivot-1, value); case 2: //DESC array if(value < arr[pivot]) search(arr, pivot+1, end, value); else search(arr, start, pivot-1, value); case 3: if(value > arr[pivot]) //arr[pivot] is smallest element in array search(arr, pivot+1, end, value); else if(value < arr[pivot-1]) //NOTE: we are comparing with arr[pivot-1] as it would be the largest element in array. search(arr, start, pivot-1, value); else return false; }

if(pivot } Anonymous on May 24, 2011 that's not a rotated array.. original array: 2,3,4,5,6 rotated array: 4,5,6,2,3 Anonymous on June 09, 2011 Very nice... good job.. Reply to Comment Anonymous on May 24, 2011 Sorry forgot to remove the last line if(pivot) { Reply to Comment Anonymous on May 24, 2011 first find the pivot element with binary search that requires logn complexity. then we have 2 arrays one increasing other decreasing. so now do binary search for both ascending and descending sub arrays so total time complexity is logn+logn1+logn2=logn where n1,n2 are less than n. correct me if i am wrong Reply to Comment kumarasvn on May 26, 2011 public static int search(int a[], int l, int u, int x) { while (l <= u) { int m = (l + u) / 2; if (x == a[m]) { return m; } else if (a[l] <= a[m]) { if (x > a[m]) { l = m+1; } else if (x >=a [l]) { u = m-1; } else { l = m+1; } } else if (x < a[m]) u = m-1; else if (x <= a[u]) l = m+1; else u = m - 1; } return -1; } Reply to Comment sid on May 27, 2011 #include<stdio.h> #include<conio.h> int search() {

int high=11,low=0,mid; int a[12]={3,4,5,6,7,8,9,10,12,0,1,2}; while(high!=(low+1)) { mid=(low+high)/2; if(a[mid]>a[high]) low=mid; if(a[mid]<a[high]) high=mid; } return (high+1); } void main() { clrscr(); printf("the roated array starts with %dth element\n",search()); getch(); } Reply to Comment toajay.iitd on May 30, 2011 You need to search the max element rank. That will partition the array into 2 parts. First part higher values. Second part lower values. Its like a1<a2<a3<a4>b1<b2<b3. Have a track for a1 and a4. This can be done in O(n). Once you partition the arrays you can use counting sort based on the number it falls into. The complexity is again O(n). So its order of O(n). Reply to Comment Anonymous on June 02, 2011 int normal_binary_search(int a[],int left,int right,int no) { int mid=(left+right)/2.0; if(no==a[mid]) return mid; if(no>a[mid]) return normal_binary_search(a,mid+1,right,no); if(no<a[mid]) return normal_binary_search(a,left,mid-1,no); } int find_rotation(int a[],int left,int right,int no) { int mid= (left+right)/2.0; if(no==a[mid]) return mid; if(a[mid]<a[right]) { if(no>a[mid] && no <= a[right]) return normal_binary_search(a,mid+1,right,no); if(no<a[mid] || no>a[right]) return find_rotation(a,left,mid-1,no); } else {

if(no<a[mid] && no >= a[left]) return normal_binary_search(a,left,mid-1,no); if(no>a[mid] || no<a[left]); return find_rotation(a,mid+1,right,no); } }; main() { int array[14]={2,3,4,5,6,7,8,9,10,11,12,13,14,1}; int number; cout<<"Enter number\n"; cin>>number; int index; index= find_rotation(array,0,13,number); cout<<index<<"\n"; } Reply to Comment neh on June 02, 2011 Check the code.. which i uploaded above.. its an o(log n)..Search can't be done in less than o(log n) or else everyone would convert the sorted array to a rotated one and search in less than o(log n) ;) Reply to Comment Amm on June 06, 2011 int binary_search( int *list, int start, int end, int x ) { int mid; while (start <= end) { mid = (start+end)/2; if (list[mid]==x) return mid; else if (list[mid] < x) { start = mid+1; } else end = mid-1; } return -1; } //FIND X IN SORTED ROTATED ARRAY int binary_search_sorted_rotated( int *list, int start, int end, int x ) { if (start>end) return -1;

int mid = (start+end)/2; if (list[mid] == x)

return mid; else if (list[mid] <= list[end] ) { //last half sorted if (x >= list[mid] && x <= list[end]) return binary_search(list,mid+1,end,x); else return binary_search_sorted_rotated( list, start, mid-1, x ); } else { if (x >= list[start] && x <= list[mid]) return binary_search(list,start,mid-1,x); else return binary_search_sorted_rotated( list, mid+1,end, x ); }

} Convert a Binary Search Tree into a sorted Linked List. Head of the linked list has to be returned. The node structure used for BST contains an extra pointer *next which is initially pointing to null. The whole process has to happen in space. One or two variables are allowed tho. 6

Tags: Amazon Data Structures Software Engineer Question #9303687 (Report Dup) | Edit | History ankit on May 23, 2011 this can be done without recursion sanjeevsince90 on May 23, 2011 They asked me to try using recursion when I was trying without... Reply to Comment Anonymous on May 23, 2011 LinkedListNode* toLinkedList (Node *curr_node) { if (curr_node == NULL) return NULL; LinkedListNode * myLLN = (LinkedListNode*)malloc(sizeof(LinkedListNode)); LinkedListNode * myLList = toLinkedList(curr_node->left); LinkedListNode * myRList = toLinkedList(curr_node->right); LinkedListNode * retList = myLLN; if (myLList != NULL) { myLList->next = myLLN; retList = myLList; } retList->next = myRList;

return retList; } This is recursive solution. Without using recursive solution, you should use stack I think.... sanjeevsince90 on May 23, 2011 A very good attempt. But does your solution return the head node of the linked list? wfchiang on May 24, 2011 oh.... yes your point is correct.... Thanks. I attempt to return the header. So when I try to connect left list, root node, and the right list, I need to traverse to the end of the list and assign the "next" point. The code need to be modified.... Well, the traversal could cause extra time complexity... Maybe we can pair up the head and the tail together in the return val How to serialize/de-serialize a binary tree? 8 [Full Interview Report]

Tags: Google Data Structures Software Engineer Question #9253182 (Report Dup) | Edit | History Orr on May 20, 2011 Binary trees can be represented as arrays, as opposed to Nodes with references to children. In such a representation, the root of the tree is located at index 0 of the array. Descending from the root downwards, the left child of a node is stored in the array at index ((2 * [current node's index]) + 1), and its right child is mapped to ((2 * [current node's index])) + 2). To serialize the Tree, map it to an array and then serialize the array. To unserialize, use element 0 as the root, and use the formulas above to restore the left and right children for each node. Thus, given a tree with height H, create an array of size 2^H. Insert the root at location 0, then its left child at location ((2 * 0) +1) and it's right child at ((2 * 0)+2). As you descend towards the leaves, repeat the process. Reply to Comment Googler on May 20, 2011 When we say serialize and de-serialize what do we mean?? We are trying to save the data contained in the node of binary tree on secondary storage in a manner so that same data with same structure can be retrieved. The key(data) in the node of binary tree could be a pointer (e.g. pointer to character array) or double pointer. So to serialize/de-serialize we must know the structure of node of binary tree, structure of serialized data and data pointed by some pointer in the node or the data (if not pointer) contained in the node. Now come to the question: We can serialize the binary tree by saving the data in pre/post + in order traversal on secondary storage. For de-serialization we can easily build the binary tree by using these two traversal. Also we can do it as posted by Orr but it will consume lot of space which is useless (saving the NULLs, consider completely skewed tree) but we can afford it because secondary storage is cheap :)

I hope I am clear. Any comments are welcome. krish.maurya on May 20, 2011 Correct, we can use Inorder & Preorder traversal also to store the data can construct same tree again. Reply to Comment wfchiang on May 20, 2011 I have an idea but I don't know whether it works or not.... We can just serialize by pre-order. (only by pre-order) But we record a "NULL" node when we traverse to an "end" For example, a tree with root 'a' and its two children 'b' and 'c', it will be recorded as a b NULL c NULL If there is a unbalanced tree such as a -> b and c b -> d (only one child) Then it will be recorded as a b d NULL NULL c NULL In this case, we can de-serialize the tree properly.... Reply to Comment rusl on May 21, 2011

void serializeTree(Node root, OutputStream out) throws IOException { //root can be null too! if (out == null) { out.write(0); //this is null node. left and right written too. return; } byte[] data = root.data; out.write(data.length); out.write(data); serializeTree(root.left, out); serializeTree(root.right, out); } Node deserializeTree(InputStream in) throws IOException { int size = in.read(); //gets size of data. if (size == 0) { return null; } byte[] data = new byte[size]; in.read(data, 0, data.length); Node n = new Node(data);

n.left = deserializeTree(in); n.right = deserializeTree(in); return n; } Reply to Comment Roxanne on May 25, 2011 Why not do a BFS and store level order info? If the node doesn't have one of the childs, store Dummy Node instead..it ought to work. Think... Reply to Comment Anonymous on May 26, 2011 Sorry to hijack the thread. I was asked the same question but on n-ary tree( ie how do you serialize an n-ary tree) neep on June 01, 2011 Use a preorder traversal. Emit (key, child1index, child2index,...) for each node where childindex of -1 is null and nonnegative child indices indicate children in the order they where emitted (previously because you are using an preorder traversal). How can we sort one unsorted int array with O(n). Unsorted : {4,2,6,1,5,5,1,2,45,444,44,45,4,1} Sorted : {1,1,1,2,2,4,4,5,5,6,44,45,45,444} 42

Tags: Microsoft Data Structures Software Engineer in Test Question #9106620 (Report Dup) | Edit | History Anonymous on May 15, 2011 i don think there's any sorting technique in O(n) time Adi on June 12, 2011 Given extra space, make use of SortedDictionary. Traverse the list once and store in SortedDictionary's value the number of times the key appears. Loop over the SortedDictionary. foobar on June 14, 2011 sorted dictionary uses binary tree internally which would cost O(nlogn). Reply to Comment Anonymous on May 15, 2011 i don think there's any sorting technique in O(n) time Reply to Comment Anonymous on May 15, 2011 i don think there's any sorting technique in O(n) time Reply to Comment celicom on May 15, 2011 Use any "Non-comparison sorts" (see wiki) Reply to Comment Anonymous on May 15, 2011

counting sort Anonymous on May 17, 2011 see the range of values and assumption made in counting sort........... counting sort fails on large range Ashish Kaila on June 16, 2011 Radix sort does not suffer from large range of numbers and its O(n) Reply to Comment Here is the solution with o(2n) ~ O(n) on May 15, 2011 static void sortUnsortedArray() { int[] arr = new int[] { 1,3,2,1,6,45,6,7,3,67,43,499,9 }; int i=0, j=0, count = 0; int[] tempArr=new int[500]; for (i = 0; i < arr.Length - 1; i++) { j = arr[i]; tempArr[j] = tempArr[j] + 1; } arr = new int[12]; int intAdd=0; for (i = 0; i < tempArr.Length; i++) { if (tempArr[i] > 0) { count = tempArr[i]; while (count != 0) { arr[intAdd] = i; count -= 1; intAdd += 1; } } } } Please correct this answer if any deviation. ianam on May 16, 2011 That's not O(2N), it's O(N+M), where M is the max value in the array. And how did you magically arrive at M (500) without any work? Counting sorts are good when the range of the values is given, but that's not the case here. Reply to Comment azgirlcoder on May 15, 2011 Bucket sort should work anonymous on May 16, 2011 To sort integers, I think most efficient way is using radix/bucket sort. It needs O(kn) time where k is < 20 for 64 bit int. So, we can claim that it's O(n) indeed. It needs O(n) space like merge sort & counting sort. Counting sort is a lot simpler than radix sort, but it needs space of O(max-min) where max (min) is largest (smallest) item in the array. Anonymous on May 16, 2011 O(n) is a deception. Cos k is not a constant its arbitrary Anonymous on May 16, 2011

O(n) is a deception. Cos k is not a constant its arbitrary ianam on May 17, 2011 Nonsense, Anonymous. Anonymous on May 17, 2011 @ianam which anonymous u refer to? Anonymous on May 17, 2011 @ianam which anonymous u refer to? magritte128 on July 09, 2011 To do bucket sort you need the assumption that the numbers are uniformly distributed within a certain range. Even then, the analysis only gives *expected* linear time.. Reply to Comment Anonymous on May 16, 2011 counting sort , Reply to Comment Anonymous on May 16, 2011 what about using hashing technique ? Reply to Comment Anonymous on May 16, 2011 Hash the elements into a table.. Since there are duplicate values, associate a counter with each hash entry.. if there is a collision, increment the counter.. Once done (O(n)), read the table entry sequentially and multiply by counter and display the number that many number of times.. ianam on May 16, 2011 "read the table entry sequentially" -- requires sorting the keys; you lose. Reply to Comment Anonymous on May 16, 2011 But, the precondition to produce expected result by reading table entries sequentially is that the entries are sorted. Your solution shows no magic how it will happen without a non-linear sorting process involved. Reply to Comment guru on May 16, 2011 1. set the appropiate bits in a bit array 2. print the array index whoes bit is set. Anonymous on May 16, 2011 Though it's O(n) in term of time complexity, but it's O((max-min) space complexity, where max-min can be the full range of integer type. amit5624 on May 16, 2011 isnt it O(max-min) in time too? ianam on May 16, 2011 Fails for duplicate values (which the original problem contains). Also, it's not O(N), it's O(M), where M is the max value. Reply to Comment Infinity on May 17, 2011 Why not create build a multimap from the elements and print it out. I think keys in the map data structure are sorted?? ianam on May 17, 2011 You must believe in magic. An O(1) map is not sorted, and a sorted map is not O(1). Infinity on May 18, 2011 The insertion into a map if it is implemented based on Red Black tree would be log(n) to search and another log(n) to insert. And while printing it would again be logarithmic. Reply to Comment

jay on May 17, 2011 Following are the steps to solve it in O(n): 1) Create a BST for the array 2) do inorder traversal Please correct me if I am wrong foobar on June 14, 2011 you cant build a BST in O(n). any kinda comparison sort algorithm have the lower bound of O(nlogn). Reply to Comment Anonymous on May 18, 2011 @jay - The best insert complexity for any "balanced" tree is min O(log n) amortized...and unbalanced BST has worst case O(n)...so your solution wont be O(n)...it might be worst case O(N^2) itself... only counting sort/bucket sort would be O(n) worst case.. BTW its not written in question that we need worst case complexity? Reply to Comment Anonymous on May 18, 2011 In my opinion, Radix sort is good enough for this question... Reply to Comment VIP on May 18, 2011 Radix sort will do it in O(kn) where k = max possible no. of digits in an element. for the example case1 1 1 2 2 4 444 44 5 5 45 45 6 1 1 1 2 2 4 4 5 5 6 444 44 45 45 1 1 1 2 2 4 4 5 5 6 44 45 45 444 Each of the above three steps takes O(n) So the total time complexity becomes O(3n) which is basically O(n) sidhartha.mahapatro on May 19, 2011 This approach will fail if all are dupilicate. Then result will be O(nXn). Orr on May 27, 2011 Radix sort doesn't perform any comparisons, so the fact that every element in the array is the same should have no effect on the algorithm. And, in fact, the algorithm doesn't decay to O(n^2) if all elements are duplicates. Reply to Comment appscan on May 23, 2011 I guess it is radix sort, which in this case is O(3n). Reply to Comment Ashish Kaila on June 09, 2011 Counting sort works. Keep a bit vector representing the values and hash the count in hash table. Then check bit vector and pull count from hash table and print the number as many times as count. Reply to Comment foobar on June 14, 2011 OK, there are lot of misinformation with the comments and answer. First thing you need to know is that any kinda comparison sorting algorithm you pick will have a lower bound of O(nlogn), you cant do any better than that. In that case, you will need to use bucket sort, count sort or radix sort. Which will amortize O(n) solution. I see answers like O(3n), there is no such notion in algorithm. O(n) == O(3n)== O(100n). there are all same. linear time. So the answer is non comparison sorting algorithms. Easy answer would be, I find the max element and then create a dictionary from 0 to max.

Keys will be the sequence from 0 to max, and values would be the occurences. At the end, you traverse the dictionary once and voila. Reply to Comment Sathish on June 15, 2011 The answer is "Spaghetti Sort" which is possible using quantum computing. Check the wikipedia page (I can't paste the links here) Give a non recursive algorithm that performs an inorder traversal without using a stack or any extra space. 6

Tags: Amazon Algorithm Data Structures Software Engineer / Developer Question #8875952 (Report Dup) | Edit | History jobsearch99 on May 01, 2011 threaded binary tree representation helps with inorder tree traversal, without stacks - at minimum storing a space for flags for left and/or right thread for avoiding endless loops. Another implementation without using stack is by storing an additional pointer to the parent per node - which is costly. Reply to Comment abcd on May 01, 2011 Morris Traversal Reply to Comment mersulo on May 02, 2011 Thanks to abcd, found Morris traversal on StackOverflow. Didn't expect the structure can be modified. Elegant solution. Reply to Comment RV on May 04, 2011 How about using array to store Binary Tree instead of nodes structure. And simply display the array.. This would be your inorder traversal only. DarkLord on May 25, 2011 Its mentioned no extra space.... Reply to Comment Anonymous on June 24, 2011 public void morisTravel(Node localRoot){ Node current=localRoot; while(current!=null){ if(current.leftChild==null){ System.out.print(current.key+ " "); current=current.rightChild; } else{

// Find Inorder predecessor Node pre=current.leftChild; while(pre.rightChild!=null && pre.rightChild!=current) pre=pre.rightChild; // Set Links if(pre.rightChild==null){ pre.rightChild=current; current=current.leftChild; // Make current to predecessor of current } // Restore else{ pre.rightChild=null; System.out.print(current.key+" "); current=current.rightChild; } } } Its moris travel algorithm. Create link to inorder successor for each leaf node. after traversing break it.Concept of threaded binary tree. If I have a string like www.bing.com/abc/asd/asdffg/../asdasd/.../asda/../.../ this is a example , if you have /../ then dont remove the letters and / before , just remove /../ www.bing.com/abc/asd/asdffg/asdasd/.../asda/.../ Another example if you have /.../ then remove the letters before and itself www.bing.com/abc/asd/asdffg/../../ 2 }

//

Tags: Microsoft Data Structures Software Engineer / Developer Question #8344017 (Report Dup) | Edit | History Anonymous on May 12, 2011 As far as i understand the question, you want to get rid of (.)+/ This can be done easily by a perl using split print "Enter the string \n"; $a = <>;

@b = split(/\.\.+\//,$a); print "The modified string is \n"; print @b; Reply to Comment Anonymous on July 11, 2011 Split it with '/' Use a stack and push elements in the stack, whenever you encounter a ..., pop the last element out of the stack. Whenever u get .. then ignore it then pop everything and prepend it When would you use a hash table? Specific situations were asked 1 [Full Interview Report]

Tags: NVIDIA C Data Structures General Questions and Comments Software Engineer / Developer Question #8075494 (Report Dup) | Edit | History shivam on June 10, 2011 Hash Table is used when we have large range of integers to store but only few are present in that. Esample:We have a mobile number 9305898934,7889675645 so we can store this in a[2] using hash functio 2nd phone screen) reverse pair of elements in a linked list. eg. abcdef shouldbecome badcfe 17 [Full Interview Report]

Tags: Amazon Data Structures Software Engineer in Test Question #7920663 (Report Dup) | Edit | History woohoo on February 28, 2011 In C void swap_every_two(node **head) { node *current = *head; node *next = NULL; node *prev = NULL; if (head == NULL) return; if (*head == NULL) /* no elements */ return;

if ((*head)->next == NULL) /* only one element */ return; *head = current->next; /* update the head pointer */ next = current->next; current->next = next->next; next->next = current; prev = current; current = current->next; while (current != NULL && current->next != NULL) { next = current->next; current->next = next->next; next->next = current; prev->next = next; prev = current; current = current->next; } } johnny on July 02, 2011 nice solution ! Reply to Comment PKT on March 01, 2011 divide linklist into two parts: a->c->e->g... and b->d->f->h.... now change the order subLinkList secondListNode->firstListNode b->a->d->c->f->e->.... Reply to Comment WgpShashank on March 02, 2011 /* Recursive function to pairwise swap elements of a linked list */ void pairWiseSwap(struct node *head) { /* There must be at-least two nodes in the list */ if(head != NULL && head->next != NULL) { /* Swap the node's data with data of next node */ swap(&head->data, &head->next->data); /* Call pairWiseSwap() for rest of the list */ pairWiseSwap(head->next->next); } } Reply to Comment rj on March 02, 2011 @pkt how u divide the list.. using 2 pointers ? still it'll be O(n) Guys i feel we shud ask the interviewer whether we need to swap on data of nodes in pair or the entire node itself. Reply to Comment

Anonymous on March 02, 2011 Node<V> pairReverse(Node<V> head) { if(head!=null) { Node<V> prev, cur,bk=null; prev = head; cur = head.next; head = cur; do { if(bk!=null) bk.next = cur; prev.next = cur.next; cur.next = prev; bk=prev; prev = prev.next; if(prev!=null) cur=prev.next; } return head; }while(prev!=null);

Anonymous on March 03, 2011 Using double pointers will be more efficient Reply to Comment Anonymous on March 08, 2011 string reverse(string rev){ for(int i = 0; i < rev.length()/2 i++){ char temp = rev[length - i]; rev[length - i] = rev[i]; rev[i] = temp; } } Anonymous on March 08, 2011 forgot to add return rev so string reverse(string rev){ for(int i = 0; i < rev.length()/2 i++){ char temp = rev[length - i]; rev[length - i] = rev[i]; rev[i] = temp;

} return rev; } Reply to Comment Somdip on March 20, 2011 #include<iostream> #include<conio.h> using namespace std; struct node { int data; node *next; }; node *list; void insert() { int num; node *tmp; node *a; cout<<"enter data : "; cin>>num; if(list == NULL) { list = (struct node *)malloc(sizeof(struct node)); list->data = num; list->next = NULL; } else { tmp = list; while(tmp->next != NULL) tmp = tmp->next; a = (struct node *)malloc(sizeof(struct node)); a->data = num; tmp->next = a; a->next = NULL; } } void display() {

node *tmp = list; while(tmp != NULL) { cout<<tmp->data<<" -> "; tmp = tmp->next; } cout<<"null\n";

void pairSwap() { node *tmp = list; while(tmp != NULL && tmp->next != NULL) { int a = tmp->next->data; tmp->next->data = tmp->data; tmp->data = a; tmp = tmp->next->next; } } int main() { int ch; do{ cout<<"************************** MENU **************************\n\n"; cout<<"\t\t1. Wana add more data to the list \n"; cout<<"\t\t2. Wana display \n"; cout<<"\t\t3. Swap pairs in list \n"; cout<<"\t\t4. Empty the list \n"; cout<<"\t\t5. Exit \n\n"; cin>>ch; switch(ch) { case 1: insert();break; case 2: display();getch();break; case 3: pairSwap();break; case 4: list = NULL;break; case 5: exit(1); default: cout<<"Wrong choice... Try again \n\n"; } system("cls"); }while(1); system("pause"); return 0; } Full code written. Please comment if you don't understand or its taking too much time to execute or its not what was asked for.

Thanks in advance... Dhawal on March 26, 2011 Nice!! Reply to Comment Sachin on March 31, 2011 Simple recursive solution {{public Node swap (Node root) { if (root==null) return null; if (root.next==null) return root; Node first, second; first = root; second = root.next; first.next= swap(second.next); second.next=first; return second; }}} Reply to Comment Anonymous on March 31, 2011 ignore extra braces at start and end Reply to Comment akash.kotadiya2000@gmail.com on June 26, 2011 public void reversePair(){ LinkedListNode previous=head.link; // First Element LinkedListNode current=head.link.link; // Second Element LinkedListNode tmp=null; LinkedListNode tmp2=null; head.link=current; while(previous.link!=null && current.link!=null){ tmp=current.link; tmp2=previous; previous.link=current.link.link; current.link=previous; previous=tmp; current=tmp.link; } if(previous.link!=null){ previous.link=current.link; current.link=previous; } else{ tmp2.link=previous; } } Reply to Comment Anonymous on July 12, 2011

// 1-2-3-4-5-6-7 // 2-1-4-3-6-5-7 ListNode* PairReversal(ListNode* root) { ListNode* nodeToReturn = root->mNext; while (root != NULL && root->mNext != NULL) { ListNode* nextNode = root->mNext; ListNode* nextNext = nextNode->mNext; nextNode->mNext = root; if (nextNext->mNext != NULL) { root->mNext = nextNext->mNext; } else { root->mNext = nextNext; } root = nextNext; } return nodeToReturn; } Reply to Comment Anonymous on July 12, 2011 // 1-2-3-4-5-6-7 // 2-1-4-3-6-5-7 ListNode* PairReversal(ListNode* root) { ListNode* nodeToReturn = root->mNext; while (root != NULL && root->mNext != NULL) { ListNode* nextNode = root->mNext; ListNode* nextNext = nextNode->mNext; nextNode->mNext = root; if (nextNext->mNext != NULL) { root->mNext = nextNext->mNext; } else { root->mNext = nextNext; } root = nextNext; } return nodeToReturn; } Anonymous on July 12, 2011 One minor correction and recursive function too. // 1-2-3-4-5-6-7 // 2-1-4-3-6-5-7 ListNode* PairReversal(ListNode* root)

ListNode* nodeToReturn = root->mNext; while (root != NULL && root->mNext != NULL) { ListNode* nextNode = root->mNext; ListNode* nextNext = nextNode->mNext; nextNode->mNext = root; if (nextNext != NULL && nextNext->mNext != NULL) { root->mNext = nextNext->mNext; } else { root->mNext = nextNext; } root = nextNext; }

return nodeToReturn; } // 1-2-3-4-5-6-7 // 2-1-4-3-6-5-7 ListNode* PairReversalRecursive(ListNode* root) { if (root == NULL || root->mNext == NULL) return NULL; ListNode* nextNode = root->mNext; ListNode* nextNext = nextNode->mNext; nextNode->mNext = root; if (nextNext != NULL && nextNext->mNext != NULL) { root->mNext = nextNext->mNext; } else { root->mNext = nextNext; } PairReversalRecursive(nextNext); return nextNode; } Implement Queue using Stack. Help to get a code with resolving complexity. 12 [Full Interview Report] Tags: Microsoft Data Structures SDE in test Question #7886668 (Report Dup) | Edit | History

woohoo on February 26, 2011

You will need two stacks. Everytime you want to enqueue, push into s1. When you want to dequeue, push all of s1 into s2, and pop from s2. As long as you continue to dequeue, pop from s2. If you receive any more enqueue commands, push all of s2 into s1 before pushing into s1. As long as you continue to enqueue, just push into s1. That should cover all of the general cases. Check for empties, etc. of course! Anurag Singh on February 26, 2011 A little optimization in above (It's NEVER required to move elements from s2 to s1. Also move from s1 to s2 is needed only when s2 is EMPTY) 1. Have two stacks, s1 and s2. 2. If Enqueue, push into s1 3. If Dequeue, pop from s2 (if s2 is not empty). If s2 is empty, move all elements from s1 to s2 (pop from s1 and push in s2). Now pop from s2. Enqueue Cost: O(1) Dequeue Cost: O(1) -- Amortized woohoo on February 26, 2011 Ah good call. Thank you for that! PKT on February 26, 2011 Awesome approch...! sidhartha.mahapatro on February 26, 2011 WOW.. Appreciated. Good logic. If anybody publish some code then that will really help. sidhartha.mahapatro on February 26, 2011 WOW.. Appreciated. Good logic. If anybody publish some code then that will really help. Lavanya on March 13, 2011 Can you tell me what's the optimization in anurag singh's answer over nugarp's. nugarp on March 13, 2011 I had additional popping when not necessary

Searching on April 20, 2011 @Anurag Singh, good approach!!!! Reply to Comment Anonymous on February 27, 2011 public class QeueUsingTwoStacks { Stack pushStack = new Stack(); Stack popStack = new Stack(); public void Enqueue(int data) { Console.WriteLine("Enqueued:{0}", data); pushStack.Push(data); } public SinglyNode Dequeue() { if (popStack.isEmpty()) { while (!pushStack.isEmpty()) popStack.Push(pushStack.Pop().data); } return popStack.Pop(); } } sidhartha.mahapatro on February 27, 2011 Awesome! Thanks for the elegant code snippet. Reply to Comment Anonymous on March 13, 2011 #include <iostream> using namespace std;

const int Max = 10;

class stack {

public: int arr[Max],top; stack(); void push(int item); int pop(); };

stack::stack() { top = -1; }

void stack::push (int data) { if (top == Max-1) { cout << "\n the stack is full"; return; }

top++; arr[top] = data; }

int stack::pop() { if (top == -1) { cout << "\n the stack is empty"; return NULL; } int data = arr[top]; top--; return data; }

void main() { stack *S1,*S2;

S1 = new stack(); S2 = new stack();

void enqueue (stack *S1, int item); int dequeue(stack *S1, stack *S2); void displayQueue(stack *S1,stack *S2); enqueue(S1,1); enqueue(S1,2); enqueue(S1,3); displayQueue(S1,S2); dequeue(S1,S2);

enqueue(S1,4); enqueue(S1,5);

displayQueue(S1,S2);

dequeue(S1,S2); dequeue(S1,S2); dequeue(S1,S2); dequeue(S1,S2); displayQueue(S1,S2);

enqueue(S1,6); enqueue(S1,7); enqueue(S1,8); displayQueue(S1,S2);

dequeue(S1,S2);

displayQueue(S1,S2); }

void enqueue(stack *S1,int item) { S1->push (item); }

int dequeue(stack *S1, stack *S2) { if (S2->top == -1) { for (int i=S1->top;i>-1;i--) { S2->push(S1->pop()); } } int data = S2->pop(); cout << "\n the dequeued element is" << data; return (data); }

void displayQueue(stack *S1,stack *S2) { if (S2->top ==-1) { if (S1->top == -1) { cout << "\n the Queue is empty"; return; } else { for (int i=0;i<=S1->top;i++) { cout << "\n the" << i+1<<"th element is"<<S1->arr[i] ; } } }

else { for (int j=S2->top;j>-1;j--) { cout << "\n the" << S2->top-j+1<<"th element is"<<S2->arr[j] ; } for (int k=S1->top;k>-1;k--) { cout << "\n the" << S2->top+2+S1->top-k << "th element is" << S1->arr[S1>top-k]; } } }

questions about hashtable. what affects lookup speed? 3 [Full Interview Report]

Tags: JP Morgan Data Structures Software Engineer / Developer Question #7801682 (Report Dup) | Edit | History Anonymous on February 23, 2011 collision, and quality of hash function Reply to Comment Anonymous on February 27, 2011 load factor Reply to Comment Anonymous on March 05, 2011 When the hash function keep on targeting the same position in HashTable In case of h(k) is always same, example we take %2 and all numbers are even so it always go into the even slot of hashTable. Quality of Hash function Depends on your data so you can never blame such thing, rather quality can differ from Data to Data even with highly efficient hash technique . Design a data structure for storing Movies and their ratings given by users. Ex: similar to netflix or Imdb 6

Tags: Amazon Data Structures Software Engineer / Developer Question #7801675 (Report Dup) | Edit | History Hamed on February 25, 2011 may be a simple hash map: <movie's name, ratings>. depends on needs, ratings could be a single number, or a an array list of different rates. Anonymous on February 27, 2011 dont we need to store a 'movie_id' field as well to handle duplicate movie names? Reply to Comment amm on February 25, 2011 something similar to like adjacency list....use hashing to get a index (hash value) for the movie name and store the rating of each user as a node in the list. iven a BST in a language where memory must be handled manually, how do you completely remove BST from memory? Recursion is not allowed. Was later told that desired solution had O(N) time and O(1) space. 16 [Full Interview Report]

Tags: Amazon Data Structures Software Engineer / Developer Question #7711690 (Report Dup) | Edit | History

ali on February 17, 2011 Maintain 2 stacks one for the parent and other for the sibling.... keep throwing the root and the sibling in the stacks(maintain some info if the sibling is present or not) if the node is not left with any children remove it and move ot its sibling in the other stack. Do this in a while loop and the siblings will move into the main root stack. Tulley on February 17, 2011 @Ali: space is O(n) in your case. Reply to Comment Anonymous on February 17, 2011 it can be done in O(n) and O(1) space by manipulating the left/right child pointers. Below is pseudo code: *** I haven't compiled this.

void DeleteTree (node* root) { node* tempRoot = root; node* tempLeft = root->left; node* tempRight = root->right; node* tempNode = NULL;

while (tempLeft || tempRight) { if (tempLeft) { tempNode = tempLeft->left; tempLeft->left = tempRoot; tempRoot = tempLeft; tempLeft = tempNode; continue; /*this is important*/ } tempRight = tempRoot->right;

if (tempLeft == NULL && tempRight == NULL) { tempNode = tempRoot->left; delete (tempRoot); tempRoot = NULL; tempRoot = tempNode; tempLeft = tempRoot->right; }

else { tempNode = tempRight->left; tempRight->left = tempRoot; tempLeft = tempNode; tempRoot = tempRight; } } delete (tempRoot); }

Reply to Comment shreyas.behera on February 17, 2011 1. Convert BST to single Pointer LL. --- O(N) 2. Start delete node from LL one after another. --- O(N) Total Complexity: O(2N) Is the above solution Aceptable ? shreyas.behera on February 18, 2011 void DeleteBSTree (Node *Root) { Node *Temp, *TRight; Temp = Roor; while(Temp)// Go to the Right most node { TRight = Temp;

Temp = Temp->Right; } while(Root) { if(Root->Left) //Convert to LL TRight->Right = Root->Left;

DeleteNode = Root; Root = Root->Right; Free(DeleteNode) } } Reply to Comment Sathya on February 17, 2011 Node temp=root,trash; while(root){ while(root.right!=null) temp=root.right; if(root==temp){ trash=root; root=root.left; temp=root; free(trash); continue; } temp.right=root.left; trash=root; root=root.right; free(trash) } krishna on June 09, 2011 Nice Solution :) Reply to Comment swap1712 on February 18, 2011 Correct me if i am wrong, but in languages like java, an object that is not referred to by any other object is deleted, so root.finalize() should be enough rest all will be taken care by the java garbage collector. Any views?

swap1712 on February 18, 2011 I didn't read the "memory must be handled manually" requirement at first, ignore the previous comment. Reply to Comment aragorn on February 20, 2011 I think that deleting the nodes as they are encountered in a breadth first search(BFS) would work. Depth first search cannot be used because then we cannot delete nodes as we encounter them but for BFS this is possible. The time complexity would be O(n) since each node is visited exactly once and deleted. Piyush on February 23, 2011 Will below solution work. First delete Left subtree then right subtree. Then free the Node. I guess complexity will be O(n) only. delect (Node root) { if(root->left !=null) delete(root->left); if(root->right != null) delete(root->right); free(root) } Arijit on April 06, 2011 Read the question.It says recursion is not allowed Reply to Comment Rip on February 24, 2011 Can't it be solved just by a postorder tree walk? ashish on February 26, 2011 I am also thinking same because if we delete root first then we loss the access to others..but if we do postorder then we can delete tree easily.It will use system stack and recursion. ashish on February 26, 2011 if you want to do postorder without recursion then we can do it by using stack and flag. Anonymous on March 03, 2011 Post-order is what is usually done, but the conditions of the problem prevented this. No recursion is specifically stated, as is O(1) memory so no stack is possible.

<round 3> 9. Array A[n] it contains numbers from 1 to n but 1 number repeated. Find out missing number. ---------------------I have not answered this question and manager not happy with my performance. THIS THE END OF THE BATTLE. 37 [Full Interview Report] Tags: Amazon Data Structures Software Engineer / Developer Question #7670665 (Report Dup) | Edit | History

Anonymous on February 08, 2011 The above does not work because there is a repeated number. koundi on February 08, 2011 1 2 3 4 5 6 7 sum 28 1 2 3 4 5 7 7 sum 29 difference = 1 repeated num = 7 abs(difference) - repeated number =6 doesnt exist in array so it is missing number But this case? 1 2 3 4 sum 10 1 2 2 3 sum 8 difference = 2 repeated num = 2 abs(difference) + repeated nmber = 4 i think we can check abs(difference) - repeated number Reply to Comment Anonymous on February 08, 2011 There is nothing said like numbers will be from 1 to n in sorted order. It can be in any order Reply to Comment Sathya on February 08, 2011 int sum=0,sqsum=0; for(int i=0;i<n;i++){ sum+=a[i]; sqsum+=sqsum+a[i]*a[i]; } Now [n*(n+1)/2]-sum=Missing no - Repeated no

[n*(n+1)*(2n+1)/6]-sqsum=Missing no^2 - Repeated no^2...now solve for missing and repeated no:s and traverse the array to find out the ans...O(n) time O(1) space Sathya on February 08, 2011 sorry typo should be sqsum+=a[i]*a[i]; not sqsum+=sqsum+a[i]*a[i]; siva.sai.2020 on February 09, 2011 Great answer S on February 09, 2011 Yes, indeed a great answer but you should be careful with the final formula. Let dif = [n*(n+1)/2] - sum Let DIF = [n*(n+1)*(2n+1)/6]-sqsum If dif = 0, no number is missing. Else m-r = dif => r = m - dif m^2-r^2 = DIF = m^2 - (m^2 - 2*m*dif + dif^2)=> m = (DIF + dif^2)/(2*dif) If the sign of DIF is 1, then the formula work fine. Otherwise, the missing number will be -m. So, you will have to multiply it by -1 or call Abs(m). Reply to Comment Code Saviour on February 08, 2011 The following algorithm has O(n) time complexity and O(1) space complexity. Let the number that was repeated be x and the number that was missed be y. a) Since, n is given, we calculate sum of numbers, requiredsum = n(n+1)/2 b) We add all the numbers in the array to get givensum. Now, requiredsum = givensum - x + y. Hence y - x = requiredsum - givensum. c) Calculate the product of all numbers, requiredproduct = n! d) Multiple all the elements in the array to get givenproduct which is (n! * x)/y Now, (requiredproduct * x) / y = givenproduct. So, x = givenproduct * y / requiredproduct. Substitute in original equation to get the value of y. GekkoGordan on February 08, 2011 ya.. but you would need a special datatype or a BIG integer to store the product. Normal datatypes in (atleast C++) wont work with factorials greater than 171 (double in C++)

siva.sai.2020 on February 09, 2011 @Code saviour, great answer chennavarri on February 09, 2011 ya, as @gekko says; thats not a good answer. LIO on February 20, 2011 @code savior: childish ans.... wt if 'n' is big no. Reply to Comment Anurag Singh on February 08, 2011 If no space issue, we can just use index array (say idx), initialize it to ZERO. then for each element in array (Say a), increment index array. At the end, index with ZERO value is missing (And index with value 2 is repeated). idx[n]={0}; for(i=0;i<n;i++) idx[a[i]]++; for(i=0;i<n;i++) { if(idx[i]==0) printf("%d is missing",i); else if(idx[i]==2) printf("%d is repeated",i); } siva.sai.2020 on February 09, 2011 without using extra space, we have to find missing number. Anonymous on February 09, 2011 who said than we can`t use extra space? Reply to Comment Anonymous on February 09, 2011 compute sum, y-x = sum - n*(n+1)/2 compute sum of squared y^2 - x^2 = sum of squared - n*(n+1)*(2*n+1)/6 from there you would know x and y 2009radha9 on March 13, 2011 I think of a simple method. add the sum of array elt.s, find the sum of first n elt.s and subtract the difference from n. we get the missing elt. please tell me if i'm wrong and in what way. Reply to Comment

Anonymous on February 09, 2011 Let x be the missing number which is repeated and y be the repeated number. If you XOR all the numbers int the array and subtract if from n(n+1)/2 you will get x+y If you add all the numbers in the array and subtract if from n(n+1)/2 you will get x-y Then solve the 2 simultaneous equations. Let n=3 A[1,2,1] 1 is repeated twice and 3 is missing. n(n+1)/2 = 6 XOR A =2 x+y=4 Solving we get both missing number and repeated number. Add A = 4 x-y=2 Guest on February 10, 2011 I think Xor solution does not work. Let's say x is missing number and y is repeated number and n = 5 Array is {1,2,3,4,4}. Here x = 5, y = 4 Sum you have mentioned is = n(n+1)/2 = 15 Xor of all the numbers is (1^2^3^4^4) = 0 Difference between Sum and Xor is = 15 - 0 = 15 which is not equal to (x+y) i.e. (5 + 4) = 9 Hence your solution did not work. Reply to Comment Anonymous on February 09, 2011 We can use xor for this problem.. For eg: let n be 3 and the given numbers be 1 2 2 Let y = (xor all the numbers from 1 to 3) xor (xor all the given numbers) so y would be the missing number xor the repeated number (3 ^ 2) let i be the last set bit in y xor all the numbers from 1 to n and numbers in the given set whose ith bit is set. xor this number with y, this would give either missing number or duplicated. is the number we got here is not in the array then it is the missing number or this is the duplicated number. we get the missing number by xoring this number with y..

comments pls.. Guest on February 10, 2011 This solution does not work. Lets say n = 5, Array = {1,2,3,4,4} Xor from 1 to 5 = {1^2^3^4^5} Xor of all given nos. = {1,2,3,4,4} So y = 1^2^3^4^5^1^2^3^4^4 = 4^5 = Repeated ^ Missing.= 1 Last bit set in y(1) is 0th bit Here xor all the numbers from 1 to n = {1^2^3^4^5} and numbers in the given set whose ith bit is set is = {1^3} Thus whole Xor gives, {2^4^5} Here, y is {4^5} and whole Xor {2^4^5} Xoring above gives 2 which is neither missing nor repeated element. Reply to Comment chennavarri on February 09, 2011 Here's a O(n) without any extra space and without multiplication or addition (because factorial requires special datatype/datastructure)

// since we know there are n numbers in an array of size n all we want is to swap the numbers to their corresponding positions i.e. move '1' to 0th position, move '2' to 1st position ...etc. if the number already exists in its position then its a duplicate and we set it to (n+1) or -1 i.e. something we can identify. Basically 2 traversals will give u the missing spot.

-> for(i=0;i<n;++i){ if(array[i]<0) //is less than zero only when we set the duplicate to -1, look below continue; if array[i]==i+1 //in the right position continue; else{ if(array[i]==array[array[i]-1]) //then its a duplicate, set it to -1 array[i] = -1 else swap(array[i],array[array[i]-1]) } }

//by the end of the above loop we have all elements in their corresponding positions and -1 in the place of the missing number -> traverse the array and print out the position+1 of the the element with value == -1 //complexity analysis: no matter what the for loop will run 'n' times --> (n) //traversal for finding the missing spot --> (n) total complexity: O(n) Anonymous on February 09, 2011 Good answer.. Anonymous on February 09, 2011 ya... I think this is the best one for this problem PKT on February 20, 2011 awesome chennavarri...! Reply to Comment Guess who?? on February 09, 2011 Since the Question says that array contains only +ve numbers(and that too from 1 to N), we can use the original array itself to keep track of the numbers that have been visited. This can be done by making the entry at any index -ve whenever we encounter any element while traversing it. At the end values at all the indexes will be -ve except the missing number. Time complexity: O(N) Space Complexity: O(1) Here is the C method to do the same:

void remove_duplicates(int *arr, int size) { int i; int sum = 0; int missing, repeated; REP(i,1,size) { int idx = arr[i]; if(idx<0)idx *= -1; if(arr[idx]<0) { repeated = abs(arr[i]); } else arr[idx] = -arr[idx];

} REP(i,1,size) { if(arr[i]>0) { missing = i; break; } } printf("Repeated: %d\nMissing: %d\n",repeated, missing); }

Hope that helps!!! Anurag Singh on February 09, 2011 This is probably the most efficient solution. souravghosh.btbg on February 13, 2011 Simply amazing! The simplicity! kk on March 26, 2011 Simply amazing, I love it Reply to Comment godblessme on February 10, 2011 @Test public void findMissing() { int n=3; int[] a=new int[n]; a[0]=2;a[1]=3;a[2]=3; Hashtable m=new Hashtable(); for(int i=1;i<=n;i++) { m.put(i+"", i); } for(int i=0;i<a.length;i++) { if(m.containsKey(a[i]+"")) { m.remove(a[i]+"");

} } //only one item left System.out.println( m.values().iterator().next() );

} Anonymous on February 11, 2011 This is O(n) time and O(n) space solution Reply to Comment Anonymous on February 11, 2011 #include <stdio.h> #include <conio.h> #define N 10 int main() { int a[10]={1,2,3,4,5,6,7,2,9,10}; int sumr=(N*(N+1))/2,sumi=0,rpt,sumdiff; for(int i=0;i<N;i++) {sumi=sumi+a[i]; for(int j=i+1;j<N;j++) {if(a[i]==a[j])rpt=a[i]; } } sumdiff=sumr-sumi; printf("%d",rpt+sumdiff); getch(); return 0; } Anirudh Govil on February 11, 2011 Suppose the given array is 1 2 3 3 5. 1. Compute sum of n numbers= n*(n+1)/2=15 2. Sum of this array=14 3. Sum of square of n numbers= n*(n+1)*(2n+1)/6=55 4. Sum of square for this array=48 5. Let a be the number repeated Let b be the actual number a-b=15-14=1

a (raised to power 2)- b (raised to power 2)=7 (a-b) * (a+b) = 7 a+b=7 a=4 b=3 Please comment if there is any flaw in this method. Anirudh Govil on February 11, 2011 Typo a be the actual number b be the number repeated Reply to Comment pansophism on February 16, 2011 xor would be the answer. a xor a == 0; for(numbers in array first to second last){ i xor i + 1 } Reply to Comment Anonymous on February 16, 2011 int flag =0; int count =1; int missing_num; int a[n]; //the array with n numbers int main() { while(flag =0) { for(int i=1;i<=n;i++) { if(count==a[i]) { count++; flag=0; break; } else { missing_num = count; flag=1; }

} } printf("The missing number is: %d",missing_num); return 0; } Does this solution seem good? Reply to Comment dexter on February 19, 2011

public static void repeatCheck(int[] a) { int pos = 1, temp=0; while(pos < a.length) { if(a[pos] >= 0) { if(a[a[pos]] < 0) { System.out.println("Repeated value: "+a[pos]); break; } temp = a[a[pos]]; a[a[pos]] = -1; a[pos] = temp; System.out.println(Arrays.toString(a)); } else pos++; } }

round 2> 6. Quadrant contains N points and all are + ve points ( I mean both (X,Y) are +ve values). sub questions: 1. How you will store( or Data structure) N points to make look up( or search) easy. 2. Find out closest point (Pj) for a entered point (Pi). Note: He asked me time efficient solution. User can add extra M points later point of time. So your solution should be Scalable. 14 [Full Interview Report] Tags: Amazon Data Structures Software Engineer / Developer Question #7689665 (Report Dup) | Edit | History

Anonymous on February 08, 2011 Not sure if this is best soln: 1. Store x co-ordinates in a BST (Say X BST) 2. For y co-ordinates , Design a Hash table where key will be corresponding x value . Here many y can have same x, so store all such y in a BST, and slot for x key in Hash table will point to the root of this BST Using these Data Structures, All x will be in one BST and All y will be in corresponding x key BSTs in Hash Table. Searching a given (x,y): 1st look of x in X BST (log n), if not found, return -1, else look for y in Hash table, in x key BST(log n). Seach Time: log n Finding Closest Point for a given (x,y): 1. Look for x JUST smaller then given x, look for y JUST smaller than given y, calculate the distance (say d1) 2. Look for x JUST smaller then given x, look for y JUST greater than given y, calculate the distance (say d2) 3. Look for x JUST greater then given x, look for y JUST smaller than given y, calculate the distance (say d3) 4. Look for x JUST greater then given x, look for y JUST greater than given y, calculate the distance (say d4) 5. point of MIN(d1,d2,d3,d4) is the closest point. Time: log n This design looks scalable, Any number of new points can be added anytime. Anurag Singh on February 08, 2011 A little addition: Finding Closest Point for a given (x,y): 1. Look for x JUST smaller then given x, look for y JUST smaller than given y, calculate the distance (say d1) 2. Look for x JUST smaller then given x, look for y JUST greater than given y, calculate the distance (say d2) 3. Look for x JUST greater then given x, look for y JUST smaller than given y, calculate the distance (say d3) 4. Look for x JUST greater then given x, look for y JUST greater than given y, calculate the distance (say d4) 5. Look for same x, look for y JUST greater than given y, calculate the distance (say d5) 6. Look for same x, look for y JUST smaller than given y, calculate the distance (say d6)

7. Look for same y, look for x JUST greater than given x, calculate the distance (say d7) 8. Look for same y, look for x JUST smaller than given x, calculate the distance (say d8) 9. point of MIN(d1,d2,d3,d4,d5,d6,d7,d8) is the closest point. Anonymous on February 09, 2011 I am afraid it is not that simple. Consider the following points (1,3), (2,100), (3,3). Now the point closest to (3,3) is (1,3) which your logic doesn't consider at all. Reply to Comment asetech on February 08, 2011 you can use a HASH Table for it.. like a array of pointers(structure pointer)and then from every index(use it as x coordinate) and store the y coordinate in the array[index]..and like wise for all those numbers whose x coordinate are same..just cr8 a link list from that index which will point to all points of same x coordinate.. struct *number[]. store only the y coordinate let say point (0,1) . cr8 a node .store 1 and store the address of the node in number[0]..and so on go on storing all those number having coordinates after the node which stored 1..as a single link list.. in this way we can store all points.. and then for searching first check X coordinate and then go to that number[x coordinate) to move to the starting node of that point and search for y coordinate in that link list...( u can get nearest point to it in this easily..) Reply to Comment GekkoGordan on February 08, 2011 How about k-d tree Building a k-d tree: O(n log 2 n) Insertion; O(logn) Searching closest point: O(sqrt(n)) Anurag Singh on February 08, 2011 Yes. Look like k-d tree is the right answer. siva.sai.2020 on February 09, 2011 I spent 30 min to understand k-d tree but I couldn't. chennavarri on February 09, 2011 Look at Animation of NN searching with a KD Tree in 2D on wiki that might help visualize. thanks

Reply to Comment sg .. on February 09, 2011 please someone put some gud tutorial like on K-d tree ... Anonymous on February 09, 2011 if k == 1, a kd-tree is nothing but a binary search tree (BST). A node has a single key (x) and for each node all the keys in the left-subtree of the node are less-than this key and all the keys in the rightsubtree are greater-than or equal to this key. if k == 2, a kd-tree is almost the same as BST except for a minor change. Note that each node now has two keys (x, y). Instead of using only one key we will try to use both of them. Let 'l' be the level/height/depth of a node 'n' in the tree. Assume that the root is at level 0. If ('l' mod 2 == 0), all the (x-keys) in the left sub-tree are less-than the x-key of 'n' and all the (x-keys) in the right-subtree are greater-than are equal to the x-key of 'n'. On the other hand if ('l' mod 2 == 1) the rule will be applied to thr y-keys. It is just a modified-BST with the comparison rule applied to the k-keys depending on the level of the node. This may sound confusing, but it helps to visualize the structure as follows. For the root (rx, ry), all the points in the left sub-tree are to the left of the vertical line X = rx and those in the right sub-tree are to its right. Let the root of the left sub-tree be (lx, ly). For this node all the points in the left sub-tree are to the bottom of the horizontal line (Y = ly) and those in the right sub-tree are to its top. The same horizontal line logic goes for the root of the right sub-tree (rx, ry). NOTE: Even though I said horizontal line (Y = ly), it is infact a line-segment (Y = ly && (X < rx)). See the article on wikipedia for a visual example. The above logic can be extended to k-dimensions easily. rahul on February 10, 2011 thanks Neha on February 10, 2011 For calculating shortest distance we can use formula (squareroot of (x-x1)^2+(y-y1)^2). here x,y are the given points and x1,y1 can be iterated from hash map Reply to Comment Rh on February 15, 2011 2. Divide and Conquer Solution. See cormen chapter 33 Computational Geometry. Complexity O (n log n). Reply to Comment swathi on July 05, 2011 you have to store the (x,y) in a structure and maintain the array of this structure for storing all the points...

a) We have to sort all the element based on x cooridinate b) then we have to use divide and conquer to get the smallest distance.. For more info refer cormen or mark alen weiss

Given an array having integers with just one integer repeated thrice, how will you find out which integer is that? 12 [Full Interview Report]

Tags: Amazon Data Structures Fresh graduate interview Question #7635661 (Report Dup) | Edit | History SB on February 08, 2011 sorting is the best I could think of. Reply to Comment Anonymous on February 08, 2011 hash table with value=count Reply to Comment Anonymous on February 08, 2011 can do it by hashing each element and if found the same element then return that number Reply to Comment SG ... on February 08, 2011 Did he mentioned any other condition or restrictions for entries in array ? Reply to Comment yours.ramesh on February 08, 2011 what about other elements in the array, how may times they are repeated...are there any restrictions on that? Reply to Comment Anonymous on February 09, 2011 How about XORing the array. Evey number will nullify when it sees itself again. After completion of the process we will be left with the required odd number Time Complexity ---> O(n) Anon on February 09, 2011 It doesn't say that the rest are repeated an even number of times - could be 1 or 5 Anonymous on February 10, 2011 @anonymous : please read the Q carefully before answering. Reply to Comment satyah920 on March 02, 2011 Instead of using hashing techniques,we can do simply using logical operators.ex-or all the elements in the array if a number occurs twice or repeated even number of times then the sum will be zero if not it is repeated odd number of times then the remaining element the element which has occurred odd number of times. eg:::

a[8]={1,3,3,2,4,4,2,1,1} ex-or all elements------>> the output will be 1 d on March 04, 2011 what abt a[9]={1,3,3,2,4,4,2,1,1,2} ??? it fails .. Reply to Comment akash.kotadiya2000@gmail.com on June 26, 2011 public int RepeatedThrice(int[] array){ QuickSort sortAlgo=new QuickSort(); sortAlgo.sort(array,0, array.length-1); int count=0; for(int i=0;i<array.length-3;i++){ count=0; for(int j=i+1;j<array.length;j++){ if(array[i]==array[j]){ count++; continue; } else break; } if(count==2) return array[i]; else i=i+count; } return -1; } Simple solution would be : sort and count for exact 3 matches. Complexity would be around O(nlogn+n). Reply to Comment Praveen on July 01, 2011 Assuming the problem is "only one number is repeated trice all others are unique and numbers are from 1 to N". We need to find 3 relations between repeated number and 2 missing numbers. We will get 3 relations from Find the sum of N numbers - given N numbers, Find the sum of squares of all N numbers - squares of given N numbers Find the sum of cubes of all N numbers - cubes of given N numbers Solve above 3 eqns to find the 3 numbers. How to store a sequence of numbers according to frequency. The most frequent number stores at the beginning 12 [Full Interview Report]

Tags: Bloomberg LP Data Structures Financial Software Developer

Question #7582661 (Report Dup) | Edit | History Anonymous on January 19, 2011 Max Priority Queue Reply to Comment Anonymous on January 19, 2011 Max Priority Queue Reply to Comment siva.sai.2020 on January 19, 2011 1. We have to use TWO hash tables and ONE Double linked list . 2. Time complexity O(1) to add a number and delete a number. Approach: 1. Store numbers in double linked list. Highest frequency number first node and least frequency number last node . number frequency 5 2 4 3 3 1 2 10 2) linked list looks : I don't know how to represent double linked list diagrammatically, so in below example i am using single linked list .

2->4->5->3 3) now THREE times you added 3 , then linked list becomes 2->3->4->5 4) to make above node swapping in O(1) time complexity you can use hashing technique. Hash table1: number | Frequency ------------------| | Hash table 2: Frequency | First node | Last node ------------------------------------| | | |

5) From First hash table you can get number frequemncy and by using frequency on second Hash table you can get Linked list location where you to insert node. 6) I know above explanation bit confusing. I could not showed my solution properly in diagrammetic way . 7) My solution works O(1) time complexity. 8) Space complexity: O(n) + Hash tables space O(1) gekko gordan on January 19, 2011 A modification to your code, you dont need two hash tables. only one which contains the following for every number key=Number, value=(Frequency, PrevNode,NextNode) The frequency of a number changes by only 1 at a point of time (assuming numbers are input 1 by 1). so all you need is to check the Frequency(prevNode->value) i.e. hash.find(prevNode>value).frequency and if it is greater than swap. anonymous on January 19, 2011 Sorry, I couldn't understand how to access a particular number if we don't keep a pointer to its associated node. What I understand is that, we intend to keep a sorted (based on frequency) linked list of number. To access a number in O(1) complexity, we use a hash table key=number, value=<frequency,nodePointer>. As it's a doubly linked list, we can access Prev or Next node in O(1) time. Thanks. siva.sai.2020 on January 20, 2011 @ gekko gordan, Yes correct, We can do it with one hash table . Thansk for correction . Anonymous on January 21, 2011 Time complexity isn't O(1) unless you have a perfect hash table, which you don't. Usually good hashtable implementations have a redblack tree behind them, so your insert is logn. Stil a good algorithm though. Reply to Comment Aman on January 20, 2011 Why not store the entire data as in a huffman coded tree ? I suppose that would have the number with the highest frequency at the top and the one with the lowest at the bottom. Reply to Comment Anonymous on January 25, 2011 @gekko and siva In a hash table, the order of the tuples is not guaranteed. You'll need to use a TreeMap. Reply to Comment yogesh on January 28, 2011 Answer is close to Aman answer, its a sort of tree called optimal binary search tree which is comparable to Huffman tree. Applications, spellcheckers or frequently used items, Requirement, Need to know the frequency and number of items in advance, Else Max heap is the only option i believe Reply to Comment Ab on March 05, 2011 Why not use a Splay tee?? &troller on March 14, 2011 why not LGBT tree? Given a dictionary find out if given word can be made by two words in dictionary. For eg. given "newspaper" you have to find if it can be made by two words. (news and paper in this case)

15

Tags: Google Data Structures Software Engineer / Developer Question #7400667 (Report Dup) | Edit | History Myth on January 11, 2011

for(c=0;c<str.length();c++) { String p1= str.subString(0,c+1); //First index inclusive second exclusive String p2=str.subString(c+1,str.length()); boolean b1=binarySearch(p1); //The dictionary file is sorted by alphabet boolean b2=binarySearch(p2); if(b1==true && b2==true) print p1 and p2 }

For the String, going character by character dividing string into two parts and checking both the occurences with the dictionary using binary search. Complexity looks in the order of o(m logn) beyondfalcon on January 12, 2011 to binary search, you have to sort the dictionary as a preliminary step. It costs a lot... Myth on January 12, 2011 Wont the dictionary be in sorted order? They always are :| kmadhu3042008 on January 12, 2011 I think binary search solution could be better if modified to avoid the search for both first and second part simultaneously and by checking one part and if found, then it would be approved to search for the second part. And for searching if suffix tree is used, then it would be better that way considering time complexity. Myth on January 12, 2011 yup. we could always omit the 2nd second search if the first boolean returns a false. Skipped off my mind. :) Divij on January 18, 2011 When you search for a string in the binary search, you haven't taken into count the time that would be taken to compare the string (which would linear to the length of the string). So the time complexity would not be O(mlogn). Do read about Suffix arrays for efficient string comparison.

Reply to Comment Anonymous on January 11, 2011 Use TRIE data structure Reply to Comment ketz on January 11, 2011 the better data structure required here is suffix tree trie and the earlier solution would not be a good option if there is also a possibility of excluding some letters in the original word to get the new word. beyondfalcon on January 12, 2011 yep. this is a typical question designed for suffix tree. anonymous on January 13, 2011 Could anyone pls explain how to use suffix tree to solve this problem? Reply to Comment qbird on January 12, 2011 How bout this? import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class FindWordCombos { Map<String,String> dictionary = null; FindWordCombos() { dictionary = new HashMap<String,String>(); dictionary.put("news", "information visible to public"); dictionary.put("paper", "write stuff on it"); dictionary.put("foo","fooz"); dictionary.put("bar","barz"); } // assume word has to be two chars List<String> madeOfWhat(String str) { List<String> pair = new ArrayList<String>(); int len = str.length(); for ( int i = 1; i < len-2; i++ ) { int w1end = i; int w2start = i+1; String word1 = str.substring(0,w1end+1); String word2 = str.substring(w2start,len); // System.out.println(word1); // System.out.println(word2); if ( dictionary.containsKey(word1) && dictionary.containsKey(word2) ) { pair.add(word1); pair.add(word2); return pair;

} } return pair; } /** * Given a dictionary find out if given word can be made by two words in * dictionary. For eg. given "newspaper" you have to find if it can be * made by two words. (news and paper in this case) * * @param args */ public static void main(String[] args) { FindWordCombos fwc = new FindWordCombos(); List<String> res = fwc.madeOfWhat("newspaper"); if ( res.size() != 0 ) { System.out.println("Match!"); for ( String s : res ) { System.out.println(s); } } else { System.out.println("Nope"); } } } Reply to Comment Anshul on January 16, 2011 Not a suffix tree, but a Prefix tree or TRIE. Dictionaries are typically stored as a TRIE, and NOT a suffix tree. It also follows from that fact that we are essentially looking up a prefix to the given word (as the first sub-word). rmd on January 21, 2011 I agree. Reply to Comment Anonymous on January 17, 2011 #include <iostream> #include <dictionary> #include <string> using namespace std; int main() { Dictionay dic = new Dictionary("C:\\dictionaryTextWords"); bool found=false; string str; cin >> str;

int len = str.length(); Trie * t = dic->getRoot(); for(int i=0;i<len;i++) { t = dic->move(str[i]); if(t->end == true) { if(dic->hasWord(str.subStr(i+1,len-1))) { found = true; break; } } } cout << found ; return; } Reply to Comment akash.kotadiya2000@gmail.com on June 24, 2011 package com.DataStructures; public class Trie { Trie[] nodes; boolean isEnd; public Trie(){ nodes=new Trie[26]; isEnd=false; } public void insert(String word){ Trie current=this; for(int i=0;i<word.length();i++){ int index=word.charAt(i)-'A'; if(current.nodes[index]==null){ current.nodes[index]=new Trie(); } current=current.nodes[index]; } current.isEnd=true; } public boolean isMatched(String word){ Trie current=this; int index=0;

for(int i=0;i<word.length();i++){ index=word.charAt(i)-'A'; if(current.nodes[index]!=null){ current=current.nodes[index]; } else{ return false; } } if(!current.isEnd){ return false; } } return true;

public boolean isMadeOfTwoWords(String word){ int begin=0; int count=0; for(int i=0;i<word.length();i++){ if(isMatched(word.substring(begin,i+1))){ count++; begin=i+1; } if(count==2){ if(i==word.length()-1) return true; else return false; } } return false; } public static void main(String args[]){ Trie trie=new Trie(); trie.insert("NEWSPAPER"); trie.insert("NEWS"); trie.insert("PAPER"); trie.insert("GOOGLE"); trie.insert("HELLLO"); System.out.println(trie.isMadeOfTwoWords("NEWSPAPERS")); } } Its Complete implementation with TRIE. Basic assumption is Dictionary stored as TRIE. Find the minimum depth of a binary tree 13

Tags: Facebook Data Structures Software Engineer / Developer Question #6913773 (Report Dup) | Edit | History Dmitry on December 12, 2010 int min_depth(struct Node* root, int depth) { if (root->left == NULL && root->right == NULL) return depth; int x = (root->left != NULL) ? min_depth(root->left, depth+1) : depth; int y = (root->right != NULL) ? min_depth(root->right, depth+1) : depth; return (x < y) ? x : y; } Reply to Comment riderchap on December 12, 2010 int MinDepth(TreeNode *node) { if( node == 0 ) { return 0; } int hL = MinDepth(node->left); int hR = MinDepth(node->right); if( (hL == 0) || (hR == 0) ) { return max( hL, hR ) + 1; } return min( hL, hR ) + 1; } Reply to Comment NJ on December 13, 2010 None of the two approaches seem good since they end up searching the entire tree. Reply to Comment testing comments on December 13, 2010 no moderation or manual moderation ? Reply to Comment Anonymous on December 13, 2010

static int mindep=0; void Min(NODE* node, int dep) { if(!node) { return; } int curDep = dep+1; if(!node->l && !node->r) { mindep=curDep<mindep?curDep:mindep; return; } if(curDep<mindep) { if(node->l) Min(node->l, curDep); if(node->r) Min(node->r, curDep); } } main() { Min(root,0); } Anonymous on December 14, 2010 I do not think this function is updating the min depth.. What if root node has, lets say two children. In this case, the curDep =1 but mindep =0 and so the second if condition will never be entered I think.May be I am not getting what you are trying to put in the function, but I think by your logic the value for this case will come out to be 0 which I don't think is correct Reply to Comment gg on December 14, 2010 int min_depth(node_type *root) { if(root==NULL) { return 0; } else { return (1 + min(min_depth(root->left) , min_depth(root->right))); } }

please mind that in the called function we have to deduct 1 h=min_depth(root); depth=h-1; so depth is the minimum depth of the tree. Anurag Singh on January 23, 2011 This is a working solution but it does complete tree traversal. Level order traversal would be more efficient which is below after few other posts. Reply to Comment Big-O on December 15, 2010 Sorry I don't have a working code, but using BFS should tell you the min depth of a tree. Just check for a node with no children. This would not require full tree scan. Reply to Comment r.ramkumar on December 16, 2010 int MinDepth(Node *root) { Queue <q> ; if (root== NULL) { return 0; } q.push_back(root); int currLevelChildCount = 1; int nextLevelChildCount = 0; int minDepthLevel = 1; while (!q.empty()) { Node *root = q.pop(); currLevelChildCount--; if (root->children.size() == 0) { return minDepthLevel; } for (int i=0; i < root->children.size(); i++) { q.push_back(root->children[i]); nextLevelChildCount += 1; } if (currLevelChildCount == 0) { minDepthLevel += 1; currLevelChildCount = nextLevelChildCount; nextLevelChildCount = 0; }

} }

Reply to Comment ss on January 23, 2011 int compute_min_depth (struct node *root, int depth) {

int tmp; if (root == NULL) return MAX_INT; if (root->left == NULL && root->right == NULL) { return depth; } tmp = compute_min_depth(root->left, depth + 1); if (tmp < min_depth) { min_depth = tmp; } tmp = compute_min_depth(root->right, depth + 1); if (tmp < min_depth) { min_depth = tmp; } return min_depth; } Reply to Comment Anurag Singh on January 23, 2011 Using Level Order Traversal (using Queue) Added null after all nodes in one level are added in queue, as an indicator of one level traversal int min_depth(BT t) { int depth=0; Queue q; if(!t || (!t->left && !t->right)) return 0; Enqueue(Q,t); Enqueue(q,null); while(!IsEmptyQ(q)) { node=Dequeue(q); if(q==null) { depth++; if(!IsEmptyQ(q)) Enqueue(q,null); } else { if(!t->left && !t->right) return depth; else { if(t->left) Enqueue(q,t->left); if(t->right) Enqueue(q,t->right); } }

} } Lokesh on March 31, 2011 Good Solution :) Implement Stack using Queues? 10

Tags: Microsoft Data Structures Software Engineer / Developer Question #6234846 (Report Dup) | Edit | History sekhar740 on November 29, 2010 use 2 queues for stack pop operation.. jiangok on November 30, 2010 one queue is enough. Reply to Comment Anonymous on November 29, 2010 #include <iostream> #include <stdio.h> #define max 5 using namespace std; class queue { int front; int rear; int data[max]; public: queue() { front = 0; rear = 0; } void enQueue(int i) { if( rear == max ) return ; data[rear++] = i; } int deQueue() { if( front == rear ) { return -1;

} return data[front++]; } void disp() { cout<<"Front ="<<front<<" Rear = "<<rear<<endl; } int size() { return rear; } int reSet() { front = 0; rear = 0; } }; class stack { queue q; public: void push( int i) { if( q.size() == max ) { cout<<"Stack is full"<<endl; return ; } q.enQueue(i); } int pop() { int ret = 0; int result = 0; queue temp; int c = 0; while( ( ret = q.deQueue() ) != -1) { temp.enQueue(ret); result = ret; } q.reSet(); int size = temp.size(); if( size == 0 ) { cout<<"stack is empty " <<endl; return -1; }

else { size--; } while(size--) q.enQueue(temp.deQueue()); temp.reSet(); return result; } void disp() { q.disp() ; } }; Reply to Comment Ankit Garg on December 04, 2010 1. Declare 2 Queues 2. Start inserting in Q1 till a pop is required 3. Transfer the contents of Q1 into Q2 except the last entry and pop it out 4. If another insertion in required insert in Q2 itself. 5. When another pop operation is required transfer the contents in Q1 back. Nutshell: Whenever a pop is required transfer is required else keep inserting in the same queue. Reply to Comment Dan on January 02, 2011 I feel it can be done using 1 queue in the following way: 1. Push elements in queue Q and keep a count of total no of elements(n). 2. If element has to be popped, pop n-1 elements and push them again into the Q. 3. Now the element popped is the required element. 4. Update no of elements n and repeat the same steps to pop another element. Any suggestions ? pankaj4u4m on January 12, 2011 I think it will be 2 queue. where will you keep n-1 element? SH on February 07, 2011 Good one !! U r pushing them back in the same queue.. Anonymous on June 26, 2011 Here you are assuming queue is implemented using array. What if its implemented by linkedList. Reply to Comment SH on February 07, 2011 Can we just use a double ended queue ? Reply to Comment akash.kotadiya2000@gmail.com on June 26, 2011 package com.DataStructures; public class StackUsingQueue { Queue enQueue=new Queue();

Queue deQueue=new Queue(); public void push(int item){ enQueue.insert(item); } public int pop(){ int item = 0; while(!enQueue.isEmpty()){ item=enQueue.remove(); if(!enQueue.isEmpty()){ deQueue.insert(item); } } // Swapping References Queue tmp=enQueue; enQueue=deQueue; deQueue=tmp; return item; } public static void main(String[] args) { StackUsingQueue obj=new StackUsingQueue(); obj.push(10); obj.push(30); obj.push(50); obj.push(70); obj.push(100); System.out.println(obj.pop()); System.out.println(obj.pop()); System.out.println(obj.pop()); } } Implemented as mentioned by Ankit Garg above. esign a linked list.. Add nodes to both front and rear , also other operations possible with linked list... Display, Delete....Disadv of linked list 4 [Full Interview Report]

Tags: Amazon Data Structures Software Engineer / Developer Question #6100711 (Report Dup) | Edit | History blueskin.neo on November 18, 2010 are you looking for a deque? double ended queue? or an array list? Reply to Comment Anonymous on November 22, 2010 queue always has 2 ends !!! GP on November 23, 2010 one of the questions was to insert to the front, the other was to insert at rear... they are two diff questions Reply to Comment Piyush on February 23, 2011 Keep 2 pointer front,rear. 1) INSERTION if insertion of new node say "newNode" at rear then rear->next=newNode; rear=newNode; else if insertion is at front then newNode->next=front; front=newNode; 2) DISPLAY/DELETE similar as display/delete of linklist Reply to Comment
Ask for Help Email me w hen new comments are posted

Add a Text Comment | Add Runnable Code Name: Comment:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.
Submit

Chat window too small? Open in new window. Connect via gchat. Access history. How to Get Better Chat Responses - READ THIS FIRST | Disable Chat.

Follow CareerCup on Twitter Follow CareerCup on Twitter More from Glassdoor.com

Software Engineering Jobs Software Engineering Salaries

Which one is better? HashTable or Binary balanced trees? List scenarios when you will prefer HashTable. 3 [Full Interview Report]

Tags: F5 Networks Data Structures Software Engineer / Developer Question #5465881 (Report Dup) | Edit | History chennavarri on November 11, 2010 Hash tables have high insertion complexity but other operations are constant time depending on the hash function. hashmaps or unordered are implemented using this. RBTrees is the widely used balanced binary tree which has logn for all operations. and not so easy to implement. Maps are implemented using this structure So it depends on the application, if you know approx. what the size of your data would be then hashmaps are the best if not you need to choose. An easier alternative to RBTrees are skip lists which are much easier to implement but same performance. anyways, please reply your perspective on this problem. Thanks Gabriel on November 18, 2010 Depending on the hash function hash tables can have a constant time complexity for insertion. Reply to Comment adhi on March 16, 2011 Algorithm :The buckets array may have to be resized dynamically when a certain load factor is reached.the tree need to be balanced. C++ STL Implementations:std::unordered_map,std::unordered_set for hashes and std::map for trees Sorting:No in hashes Yes in Tree Range Search :" Runtime Complexity :Inserting: O(1) (normal case), O(N) (worst case, only with bad hash algorithm) Searching: O(1) (normal case), O(N) (worst case, only with bad hash algorithm). Inserting: O(log(n)) (when balanced) Searching: O(log(n)) (when balanced) How will you delete duplicate odd numbers from a linked list? (delete only duplicates, keep one copy, list is not sorted) Interviewer was expecting O(n) answer. He didn't say anything clear about the extra space. 14

Tags: Microsoft Algorithm C Coding, Data Structures, Algorithms Data Structures Software Engineer / Developer Question #4716817 (Report Dup) | Edit | History bogdan.cebere on October 27, 2010 you could do it with a hashtable. Reply to Comment gao on October 27, 2010 i think if extra space is acceptable. use hashset. O(n) Reply to Comment Anonymous on October 31, 2010 use a xor process on all the data sachin323 on October 31, 2010 How does XOR solution fit to this , can explain ? Reply to Comment Anonymous on November 01, 2010 he cannot explain, because he doesnt know either Anonymous on November 17, 2010 if you xor the same numbers you will get a zero. Anonymous on December 01, 2010 seriously? thats your answer? Reply to Comment Anonymous on December 03, 2010 only even number of times if a number is repeated then xoring will return zero , if it is odd number of times then it wont be zero , using hash table would be fine Reply to Comment aggarwal.richa on January 08, 2011 Do it with hash table. Reply to Comment kk on March 28, 2011 public static List<Node> getDupNodes(Node n) { HashSet<Node> h = new HashSet<Node>(); while (n.next != null) { if ((n.data % 2 != 0) && (h.Contains(n))) { //do nothing/// } else { h.Add(n); }

n = n.next; } return h.ToList<Node>(); } Reply to Comment kamleshlu2009 on June 15, 2011 @to the people suggesting for hash table range is not given how much big table will u take foe eg list conatains 1 2 3 4 2 5 6 5 7 8 10000 u will need an array of 1000 size kamleshlu2009 on June 15, 2011 sorry 10000 size Reply to Comment Ashish Kaila on June 20, 2011 You could ask the interviewer about the range of numbers. If range of numbers are given then you can use a bitmap to record occurrences. Usually if range is small then there is a constant memory space required which is not the case with hash tables. Hence you can have a solution that is technically O(n) in both space and time complexity. Reply to Comment akash.kotadiya2000@gmail.com on June 26, 2011 package com.DataStructures; import java.util.HashMap; public class RemoveDuplicateFromLinkedList { HashMap<Integer, Character > map=new HashMap<Integer, Character>(); public void removeDuplicates(LinkedListNodeInt current){ LinkedListNodeInt previous=null; while(current!=null){ if(map.containsKey(current.value)){ if(current.value%2!=0) previous.link=current.link; else previous=current; } else{ map.put(current.value,' '); previous=current; } current=current.link; } } public static void main(String args[]){ RemoveDuplicateFromLinkedList obj=new RemoveDuplicateFromLinkedList(); LinkedListNodeInt node=new LinkedListNodeInt(); node.insert(1);

} } Reply to Comment Find the width of a tree pointed by head 35

node.insert(2); node.insert(5); node.insert(60); node.insert(3); node.insert(5); node.insert(60); node.insert(5); obj.removeDuplicates(node.link); node.traverse();

Tags: Amazon Algorithm C Data Structures Software Engineer / Developer Question #4529943 (Report Dup) | Edit | History Anonymous on October 25, 2010 bfs level-wise traverse Anonymous on October 25, 2010 not necessarily... it maybe possible that A is root node with B as left and C as right child. B has only left child while c has both left and right child. In this case the width will be 4 where as if you traverse using BFS it will give you three nodes We need to find width of tree not the number of leaf nodes..... Noname on October 25, 2010 I agree with this. width is only affected by the left and right most leaf nodes. so, if we know the height of two leaf nodes and the parents type(left or right). I think we can calculate the width of the tree. For example, A BC EGH We will get info on E and H and store info like E(left,left) as the path has left and left nodes. Then based on these nodes on the path it is possible to get the width. Reply to Comment KS on October 25, 2010 void get_min_max_offset( const Node * root, int offset, int & min, int & max ) { if( root == 0 ) {

return;

if( min > offset ) { min = offset; } if( max < offset ) { max = offset; } get_min_max_offset( root->left, offset - 1, min, max ); get_min_max_offset( root->right, offset + 1, min, max ); } int get_tree_width( const Node * root ) { if( root == 0 ) { return 0; } int min = INT_MAX; int max = INT_MIN; get_min_max_offset( root, 0, min, max ); return 1 + max - min; } Reply to Comment Anonymous on October 26, 2010 A tree is not necessarily a binary tree. It could be any type of tree. The width of a tree is supposed to be the maximal number of nodes in one level of the tree. Anonymous on October 26, 2010 Not necessarily on one level. Reply to Comment Anonymous on October 26, 2010 int left, right;

int f(NODE* r, int i) { if(i>right) { right=i; } if(i<left) { left=i; } if(r->l) { f(r->l, i-1); } if(r->r) { f(r->r, i+1); } } void main() { left=right=0; f(r, 0); width=right-left+1; } Anonymous on November 16, 2010 wat is the return value?????/ Reply to Comment No name on October 26, 2010 what would be the initial value for i Anonymous on November 16, 2010 what is the return value???????? Reply to Comment andy on October 26, 2010 findWidth(Node root){ if(numChild(root) <= 1) /*numChild(root) returns # of children*/ return 1; width = 0; for each child of root{

width += findWidth(child); } return width; } In above function I have assumed that width does not have to be max number of nodes on same level. Can somebody clarify whether width is max number of nodes on same level or levels can be at different levels? [If nodes have to be on same level then BFS should work] andy on October 26, 2010 Is this correct? Reply to Comment Anonymous on October 26, 2010 Can we proceed with finding the height of a tree. PLZ let me know. Reply to Comment VladimirMee on October 26, 2010 No, width hasn`t been found yet and nobody can tell the exact definition of a width of a tree, neither do I, but I`d like to get to know. Reply to Comment vinaysachdeva23 on October 26, 2010 The width of the trees number of columns you can find in the tree... for example: A BC DEF has width = 5 where first column has D second has B third has A and E, forth has C and fifth has F Hope someone can solve this question Reply to Comment VladimirMee on October 26, 2010 vinaysachdeva23, please, can you give the source (book or prooflink or article) of definition of width you gave? I couldn`t find Reply to Comment Anonymous on October 26, 2010

// Assuming the definition of tree width is the max number of nodes in any level of the tree: // Perform Level Order Traversal, with additional variable called level_number being pushed into the queue int findWidth(struct node *head) { int prevlevel=-1; int currlevel=-1; int maxwidth=0; int width=0; q.queue(head);

q.queue(1); while(!q.empty()) { struct node n=q.dequeue(); currlevel=q.dequeue(); if(currlevel!=prevlevel) { if(width>maxwidth) maxwidth=width; width=0; } width++; // Queue all children and their levels if(n.left!=NULL) { q.queue(n.left); q.queue(currlevel+1); } if(n.right!=NULL) { q.queue(n.right); q.queue(currlevel+1); } prevlevel=currlevel; } if(width>maxwidth) maxwidth=width; return maxwidth; } Reply to Comment xenon on October 27, 2010 the definition is sort of flawed. imagine a tree with 10 levels. root has left and right child. but left child ahs only left child, which has only left child, and so on for remaining 8 levels. same for right child (only right childs) at lowermost level tree has 2 nodes, but as far apart as possible. arguably this tree is wide than a 2 level tree with a root having left and right child, both being leaf nodes. either tree has 2 nodes in leaf level. i think the point of the question is to see how candidate can try to zero in on a definition of a vague concept like tree width. ideally they would want to see elimination of simple and inaccurate definitions while working through scenarios. Otherwise just counting leaf nodes is trivial. Reply to Comment vinaysachdeva23 on October 27, 2010 The question is about the width of a tree not the maximum number of nodes on a particular level... The width of a tree means how wide it is. Like as explained above by xenon, the width of tree is not equal to 2 but will be much more than 2 as it extends too wide in 10 levels. So its clear that the width means the extension of tree not the max number of nodes on a particular level. If that would have been the case, then a tree with 3 levels would have had same width as a tree with 10 levels(above tree) which contradictorily proves wrong. Hence the width of a tree actually means how wide it is. Reply to Comment VladimirMee on October 27, 2010

Still dont get it(( For example, tree described above with only left childs in the left subtree and right childs in the right one and depth = 8 would be very wide and its width won`t be be 2^8 = 256? What is the formala to calculate width for each tree? For example, the height is the longest path from root to leaves, but what about width? How it`s gonna be found? vinaysachdeva23 on October 27, 2010 yes its width would be 256 if the leftmost and the rightmost elements are present. The width is the distance between leftmost and the rightmost node. Like for example a tree with root node and its left node has a width of 2 while the width of a tree with a root node and one left node and one right node will be 3 Important point: The width of a tree with root node A, a left node B and a right node to B , say C, will be 2.Since A and B will be on the same column. Hence the leftmost node is B while the right most node will be A (or C). Hence their difference is 2 and hence the width. I hope you get it now.... vinaysachdeva23 on October 27, 2010 yes its width would be 256 if the leftmost and the rightmost elements are present. The width is the distance between leftmost and the rightmost node. Like for example a tree with root node and its left node has a width of 2 while the width of a tree with a root node and one left node and one right node will be 3 Important point: The width of a tree with root node A, a left node B and a right node to B , say C, will be 2.Since A and B will be on the same column. Hence the leftmost node is B while the right most node will be A (or C). Hence their difference is 2 and hence the width. I hope you get it now.... vinaysachdeva23 on October 27, 2010 yes its width would be 256 if the leftmost and the rightmost elements are present. The width is the distance between leftmost and the rightmost node. Like for example a tree with root node and its left node has a width of 2 while the width of a tree with a root node and one left node and one right node will be 3 Important point: The width of a tree with root node A, a left node B and a right node to B , say C, will be 2.Since A and B will be on the same column. Hence the leftmost node is B while the right most node will be A (or C). Hence their difference is 2 and hence the width. I hope you get it now.... vinaysachdeva23 on October 27, 2010 sorry the width would be 15 for the above question pointed by vladmirmee. 7 nodes to the left of root, 7 to the right and one root.... Hence the width would be 15 Anonymous on October 28, 2010 What if the nodes are in middle of the tree for ex: A B C D E F GHIJ

and A

D Reply to Comment VladimirMee on October 27, 2010 , your examples made it all clear to me, now i get it) appreciate your help, thanks) Reply to Comment Anonymous on October 30, 2010 http: en.wikipedia.org wiki Tree_decomposition Reply to Comment PKT on November 17, 2010 A BC D EF GHIJ i think the max width is '4' b/w g and c Reply to Comment Ketz on November 20, 2010 public Integer width() { LinkedList<Node1> queue = new LinkedList<Node1>();//for level operations ArrayList<Integer> level = new ArrayList<Integer>();//list of counts at each level int levelCount = 0;//count at each level if(root!=null) { queue.add(root); levelCount = 1; } while(queue.size()>0)//to check if we reach leaf nodes { level.add(levelCount); while(levelCount>0) { Node1 node = queue.removeFirst(); if(node.left!=null)queue.add(node.left); if(node.right!=null)queue.add(node.right); --levelCount; } levelCount = queue.size();//at this level we get the total nodes at one level } //naive approach for finding Max. Can be replaced by a priority queue Iterator<Integer> levelItr = level.iterator(); int Max = 0; while(levelItr.hasNext())

{int temp = levelItr.next().intValue(); Max = Max>temp?Max:temp; } return Max; }

Reply to Comment hi on January 09, 2011 i think width can be found out by MAX(going left of each node until leftchild is NULL + same for right + 1) which can be solved recursively as: int width(node *sr,node *k) { if(k == NULL) return 0; static int max; int l = width(k,k->leftchild); int r = width(k,k->rightchild); if(l+r+1 > max) max = l+r+1; if(sr == NULL) return max; else if(k == sr -> leftchild) return l+1; else return r+1; } Reply to Comment HI on January 09, 2011 sry it wont work for some cases pls go forward using my code..... Reply to Comment Newbie on January 10, 2011 width(node* N) { int count++; count=leftwidth(N->left,count); count=rightwidth(N->right,count); print(count); } leftwidth(Node N,count) { if(n!=null) { count++; n=n->left; } return count; } rightwidth(Node N,count)

{ if(n!=null) { count++; n=n->right; } } Reply to Comment Newbie on January 10, 2011 let me know if anything is wrong.. Reply to Comment Nifty on January 16, 2011 Considering that the width is maximum number of nodes at any one level, the code below should work. No?? public void maxWidthBST(NodeType rootNode) { int level=depthBST(rootNode); int maxWidth=0; int intNodeCount=0; for(int counter=1; counter<=level;counter++) { intNodeCount = NodeCount(rootNode, counter); if(intNodeCount>maxWidth) { maxWidth = intNodeCount; } } Console.WriteLine("The maximum width is: " + maxWidth); } public int NodeCount(NodeType root, int level) { int LWidth=0; int RWidth=0; int totalNodesAtLevel=0; if(level<=0) return 0; if(level==1)return 1; if(level>1) { if(root.Left !=null) LWidth=NodeCount(root.Left, level-1); if(root.Right !=null) RWidth= NodeCount(root.Right, level1); totalNodesAtLevel = LWidth+RWidth; } return totalNodesAtLevel; } Reply to Comment

SH on February 05, 2011 www cs duke edu/courses/spring00/cps100/assign/trees/diameter html replace " " by "." Implement a stack that can have push, pop and find_minimum operations in o(1) time. 6 [Full Interview Report]

Tags: Amazon Data Structures Software Engineer / Developer Question #4504663 (Report Dup) | Edit | History TheRunner on October 20, 2010 import java.util.*; public class Stack { private ArrayList<Comparable> _list; private ArrayList<Comparable> _subListMin; public Stack() { _list = new ArrayList<Comparable>(); _subListMin = new ArrayList<Comparable>();

public void push(Comparable item) { _list.add(item); if(_subListMin.size()==0) { _subListMin.add(item); return; } Comparable lastMin = _subListMin.get(_subListMin.size()-1); if(lastMin.compareTo(item) < 0) { _subListMin.add(lastMin); } else {

} }

_subListMin.add(item);

public Comparable pop() { _subListMin.remove(_subListMin.size()-1); return _list.remove(_list.size()-1); } public Comparable findMinimum() { return _subListMin.get(_subListMin.size()-1); } private String listToString(ArrayList<Comparable> list) { String res = ""; for(Comparable c:list) { res += c.toString() + ","; } if(res.length()>0) { res = res.substring(0,res.length()-1); } return res; } public void print() { System.out.println("Stack content = " + listToString(_list)); System.out.println("Min = " + findMinimum());

public static void main(String[] args) { Stack s = new Stack(); s.push(2); s.push(8); s.push(1); s.print(); s.pop(); s.print(); } } Anonymous on October 21, 2010 Great!! Reply to Comment

andy on October 26, 2010 Can you explain your code to store minimum value in subListMin? Comparable lastMin = _subListMin.get(_subListMin.size()-1); if(lastMin.compareTo(item) < 0) { _subListMin.add(lastMin); } else { _subListMin.add(item); } It appears to me that it is not correct. How will subListMin change if I do, push(1) push(2) push(3) push(4) push(5) push(6) push(7) push(8) push(10) push(9) Reply to Comment Adi on November 15, 2010 Can you please give the Corresponding C or C++ code for this ? Reply to Comment Anonymous on November 26, 2010 hi Reply to Comment adhi on March 16, 2011 struct stack{ int minvalue; int array[MAX_SIZE]; int top; }mystack; whenever u push an element just update the value of minvalue.Rest all works like normal stack. Push,Pop,find_minimum in O(1). mplement Queue using stacks. What's the time complexity of various queue operations for this implementation? 5 [Full Interview Report]

Tags: Facebook Data Structures Software Engineer / Developer

Question #4399683 (Report Dup) | Edit | History Aditya on October 20, 2010 I think we will need two stacks to implement queue :stack has operations top(),empty(),pop(),add() lets take two stacks s1 and s2 keep a variable FRONT nOw :1) Create queue :- create s1 and s2 and FRONT = NULL and REAR = NULL; 2) Enqueue (e) :- -----------O(1) if( s1.empty() ) then FRONT = e REAR = e; s1.add(e) 3) Dequeue() :---------------------------------O (Num. elements) if ( s1.empty() then UNDERFLOW else { while( !s1.empty() ) s2.add( s1.pop()); s2.pop(); if( !s2.empty() ) FRONT = s2.top(); Else REAR = NULL; while( !s2.empty() ) s1.add( s2.pop() ); } 4) Front() :- return FRONT ---- O(1) 5) Rear() :- return REAR --------O(1)

Anon on May 17, 2011 Dequeue can be optimized further. There is no need to pop the s2 back to s1. Just check s2 for elements first before accessing s1. Dequeue() { if (s2.empty()) { while (!s1.empty()) { s2.push_back(s1) } } if (s2.empty()) UNDERFLOW; return s2.pop() } Reply to Comment anonymous on November 07, 2010 we can do it using a single stack. supported operations - top(), empty(), pop(), add() for top() and pop() we recursively top or pop the elements until we get the last element. we will still be using two stacks.. one- the given stack and the other recursion stack.. but explicitly its just one stack!

wat say?? Anonymous on March 03, 2011 recursion means you have used another stack Reply to Comment Anonymous on November 27, 2010 just one stack is fine. insert - O(1) dequeue - O(n) Convert a doubly linked list to BST in place 16

Tags: Google Data Structures Software Engineer / Developer Question #4344046 (Report Dup) | Edit | History sushant on October 17, 2010 Sort the doubly link list... u will get BST... Anonymous on October 18, 2010 That wont be in-place. rath.swaroop on October 18, 2010 There are inplace sorting algorithms rath.swaroop on October 18, 2010 There are inplace sorting algorithms Reply to Comment Anonymous on October 17, 2010 You mean when you have a list like 1<->2<->3<->4 you can also consider it as a BST, where the root is one and each node only has a right child? Aditya on November 15, 2010 After sorting, make previous pointer of every node=NULL. and next point to next node(right child). Left child is NULL. But this is not a proper BST since the searching time will be O(n), so not a very effective solution. However, better to take the middle element and make it node and recursively take the middle element from the left and right part of link list ... Reply to Comment sushantmax88 on October 18, 2010 nope.. i mean, when you have list of 1,2,3,4,5,6,7,8,9 your root wil be at middle element. which is 5 now, left side again make it half n make it left child of 5 . same with right side. select middle element n make it right child of 5. every time you are making it half. Reply to Comment Anonymous on October 18, 2010 but first elements in the list need to be sorted Reply to Comment Anonymous on October 18, 2010 sort the list will make it a BST.

Reply to Comment czpete on October 21, 2010 What does it mean to turn DL List into a BST in place? What is the data structure to be used? That will make a difference in what you can/cannot do! Should I asssume that each element has 5 pointers (next, previous, parent, left, right) or should I reuse next as right, previous as left with no parent? In any case, sorting first and then somehow asembling the tree would work. You can use merge sort to sort the list--O(n log n) time. Sorted list is a BST, though a linear one. The above mentioned trick with finding the middle for each half and creating the tree this way would also work. A possibly simpler solution is to build the tree one node at a time. Start with empty tree. Grab the first element from the DL list, that's your root. At each step, you'll have a root of the tree you're building, and the remaining DL list. Remove the first element from the (partial) list, insert it (recursively) in the tree. Repeat until no elements left in the DL list. Running time should be O(n*h) where h is the tree height (log n if random or RB tree). Anonymous on October 22, 2010 @czpete You are good. If you are new grad, I should afraid of the interviews Anonymous on November 03, 2010 @czpete Will the tree that will be constructed by ur algo will be same as of middle element algo described above ? Can u explain ur method in more detail ? Reply to Comment Anonymous on November 11, 2010 Example: 7,6,8,4,2,9,5 Considering BST, the left child tree items should be less than the root, and the root should be larger than the right child tree items. Sounds like a partition operation in quick sort. 1. 7,6,8,4,2,9,5 Choose 7 as root ,and as pivot 2. 6,4,2,5,7,8,9 Then 6,4,2,5 are the left child, and 8,9 are the right child. 3. 6,4,2,5 Choose 6 as root, and as pivot 4. 4,2,5,6 Then 6 is the root and 4,2,5 are the left, no right child 5. 4,2,5 Choose 4 as the root, and as pivot 6. 2,4,5 Then 4 is root, 2's left and 5's right child. 7. 8,9 Choose 8 as the root, and as pivot 8. 8,9 Then 8 is the root and 9's the right child. Now, we got a BST tree. In fact, it is a quick sort, O(n*lgn). vvvvv on December 24, 2010 how can you apply quick sort on a DL list? it is not an array.. Reply to Comment Anonymous on January 16, 2011 cur_tree=null cur_node=list next_node=list->next while(next_node) { cur_node->previous-=null cur_node->next=null insert_tree(root,cur_node) cur_node=nextnode next_node=nextnode->next }

Reply to Comment Jin on January 26, 2011 struct node { int v; node *prev, *next; }; node *DdlToBst(node*head) { node *root = null; node *cur = head; while (cur) { node *next = cur->next; if (!root) { root = cur; } else { insert(root, cur); } cur->prev = cur->next = null; cur = next; } return root;

void insert(node *root, node *p) { if (p->v < root->v) { if (!root->prev) { root->prev = p; } else { insert(root->prev, p); } } else { if(!root->next) { root->next = p; } else { insert(root->next, p); } } } Convert a min heap to BST without changing its structure and of course no extra space . 14

Tags: Google Data Structures Software Engineer / Developer Question #4280049 (Report Dup) | Edit | History ibnipun10 on October 17, 2010 Take 3 nodes at a time in the tree (parent and its 2 children) Now rearrange the values such that left is the min , parent is the middle element and right is the highest of the three. Do it for every node in the tree Tulley on October 17, 2010 Single traversal wont work Reply to Comment Tulley on October 17, 2010 We can do it by traversing the tree and swaping the values as many times as the hight of tree. Tree traversal will always take extra space (stack for recursive calls). Below is the psudo code: MinHeapToBst (Root){ if (Root){ TempRoot = Root; LeftChild = Root->LeftChild; RightChild = Root->RightChild; MinHeaptoBst (LeftChild); MinHeaptoBst (RightChild); if (RightChild && LeftChild){ if (LeftChild->Key > RightChild->Key){ SWAP (LeftChild->Key, RightChild->Key); } SWAP (LeftChild->Key, Root->Key); } else if (LeftChild){ SWAP (LeftChild->Key, Root->Key) } } } 1. N<-Number of node in tree, H<-log(N), hight of tree, R<-Root of tree; 2. While (H > 0){ MinHeapToBst (R); } Running time is Nlog(N) Anybody, please let me know if it can be done witout using stack (extra space). Tulley on October 17, 2010 Sorry for the mistake, the psudo code is as below: MinHeapToBst (Root){ . if (Root){ . TempRoot = Root; . LeftChild = TempRoot->LeftChild; . RightChild = TempRoot->RightChild; . MinHeaptoBst (LeftChild); . MinHeaptoBst (RightChild); . if (RightChild && LeftChild){ . if (LeftChild->Key > RightChild->Key){ . SWAP (LeftChild->Key, RightChild->Key); .}

. SWAP (LeftChild->Key, TempRoot->Key); .} . else if (LeftChild){ . SWAP (LeftChild->Key, TempRoot->Key) .} .} } 1. N<-Number of node in tree, H<-log(N), hight of tree, R<-Root of tree; 2. While (H > 0){ . MinHeapToBst (R); . H <- H-1; .} anonymous... on October 18, 2010 it is wrong.... Asfdf on November 14, 2010 Excellent !! Asfdf on November 14, 2010 Excellent !! Reply to Comment annonD on October 21, 2010 How do you convert following head to BST w/o changing structure? 1 11 Reply to Comment swk on October 22, 2010 lyle.smu.edu/~saad/courses/cse3358/ps7/problemset7sol.pdf problem 4 (b) Reply to Comment jhr on November 13, 2010 at the top of the heap, take the largest element A from the left subtree, swap it with the smallest element B from the right subtree if A>B. If A<B, stop, and if root < A, swap A and the root. do this recursively, on the left subtree and on the right subtree. Reply to Comment Anonymous on December 04, 2010 @tulley the code is not working as expected for the following minheap 1 | 2 3 | 4 5 6 11 | 12 21 Reply to Comment vvvvv on December 24, 2010 Convert( Node) { if(Node!=null) { Convert(Node->left) Convert(Node->right) Fix(Node) } }

Fix(Node) { if(Node!=null) { if(Node->left!=null && Node->right!=null) if(Node->left->value < Node->right->value) {swap(Node->left, Node); Fix(Node->left); else { Node->left to Node->right, Node->right to Node, Node to Node->left Fix(Node->left);Fix(Node->right) } } } T(N) = 2T(N/2) + O(logN) (Fix(Node) is O(logN) ),by Master theoremT(N) = O(N) Anonymous on April 20, 2011 Algo is correct, but complexity is nlogn Reply to Comment amshali on January 10, 2011 We just need to sort the array representing the heap using say quicksort. It is O(nlgn). Question does not have any constraint on the order. Reply to Comment Convert a BST to max heap without using extra memory and in as optimum time as possible 6

Tags: Google Data Structures Software Engineer / Developer Question #4281027 (Report Dup) | Edit | History Tulley on October 17, 2010 Do it same as Menaheap to BST. Will that not work? Please comment. Reply to Comment gradStudent on October 17, 2010 Pseudo Code: /* Bottom Up recursive code. * Basic Idea: Swap the right child to its parent bottom up to make it a Max Heap. */ NODE* BSTMaxHeapify(NODE* Tree) { if(Tree==NULL) return Tree; BSTMaxHeapify(Tree->left); BSTMaxHeapify(Tree->right); return(BSTMaxHeapSwap(Tree,Tree->right)); }

NODE* BSTMaxHeapSwap(NODE* Root, NODE* RootRight) { if(RootRight==NULL) return Root; else Swap the Root and RootRight Node; return RootRight; } Plz comment if I have made any mistake dumdum on January 24, 2011 you dont have to swap the nodes, swap the data. That would be neat. Reply to Comment Anonymous on October 18, 2010 How about this approach? O(n) to convert BST to sorted LL, and O(n) to convert sorted LL to heap node* previous; BST2LL(node* n) { ..if(n==null) return; ..BST2LL(n->rightChild); ..if(previous!=null) ....previous->rightChild = n; // in the linked list, the rightChild is like "next" ..else ....root=n; ..previous=n; ..BST2LL(n->leftChild); } //step 1. BST to Linked List BST2LL(root); //step 2. LL to heap node* i1=root; node* i2=root->rightChild; node* i3; if(i2!=null) i3=i2->rightChild; while(i1!=null) { ..node* next = i1->right; ..i1->left = i2; ..i1->right = i3; ..i1 = next; ..if(i2!=null) i2 = i2->right; if(i2!=null) i2=i2->right; ..if(i3!=null) i3 = i3->right; if(i3!=null) i3=i3->right; } Please comment if i have made any mistake Reply to Comment amshali on January 10, 2011 How about just doing a simple in-order traversal of the BST. It would produce a sorted array which is indeed a max-heap! amshali on January 10, 2011 We also need to inverse the array at the end! O(n)

This was only technical question my interviewer was asking to every candidate he interviewed What kind of questions u will ask to me if u have to design a Queue for me ? i answered as 1) for data type u want it he said int 2) It is going to contain very large numbers of objects he said no 3)do u want to dynamically expanding he said no , lets keep it simple 4)do want functionality of accessing any element in queue like At() function interviewer : yes 5)Do u want min and max element functions interviewer : yes After this he kept saying what else what else and i was blank he mentioned asking about environment would have been a good question like do want this queue for kernel for application or for Database then he asked me to write a class which will implement this but he was rushing a lot kept saying we have very less time left so i end up writing queue full , queue empty , insert and pop conditions only i must say i was bit disappointed by this interview as from CareerCup i have prepared for alot of coding question and from these kind of questions will everybody answer easily , how will they screen candidates 5

mplement three stacks in single array 7

Tags: Google Data Structures Question #4240706 (Report Dup) | Edit | History Metta on October 09, 2010 Each element of the array can contain a value and a previous pointer. Maintain 3 pointers one for each stack, which points to the last pushed element. And maintain a separate list of free indices. Now, - Push Find the free index from free list , add the element and mark previous pointer to last index of the stack. Add free index to free list. - Pop Go to element at last index of the stack, make last index point to element->previous and null out the element. Add the nulled index to free list. This incurs extra space to maintain free pointers though. vkr_coder on December 07, 2010

without needing to have a separate free list, we can use XOR linked list to fill the pointer field in each node. In this case, we can traverse the same list to get the first free node i.e., a node whose prev pointer will be NULL. Reply to Comment S on October 10, 2010 Classic implementation on stack using an array on indexes 3*k, 3*k+1, 3*k+2. This can be generalized for N stacks in a single array. Metta on October 10, 2010 What happens if stack1 gets full while stack2 and stack3 are still empty? You still need to use the other stacks' free space to grow stack1 to make it an efficient implementation. czpete on October 10, 2010 Let's see, we have 2 algorithms. A: Array elements contain 2 pointers plus one extra array (or list?) for free indices. B: Array elements contain 1 pointer, no additional storage needed. (I am ignoring the constant storage that is about the same for each algorithm). Space considerations (Initial array size is 3*N) -----------------------------------------------(1) All stacks are balanced (say n elements each) and array is almost full (3n is almost equal to 3N). A: We need at least 6*N units of space for the array and additional space for the free elements. Assuming that empty elements are stored in a linked list, this would be close to 0. (If it's array, it would another 3*N). B: We need 3*N units of space. [Here one unit can hold one address, i.e. 32 or 64 bits] (2) All stacks are roughly balanced and array is half full (each stack has about n elements with 2*n~N). A: We need at least 6*N units of space + 6*n = 3*N for linked list (or array) implementation of the list of available elements. 9*N units total. B: We need 3*N units of space. (3) One stack has just overflown, i.e. it has N+1 elements. The others are empty. A: 6*N for the arrays, 4*N for the list of empty cells (or 3*N if array is used). Total: 10*N B: Double the size of the array--6*N. This is not a comlete analysis but no matter what case you consider, the simple, easy to implement solution is more space efficient than the complicated one. You could probably make some of the constants slightly smaller by making the implementation even more tricky but I doubt that you could do better than the simple solution suggested by S. Very often, simple is better :-) Now, there might be a solution that somehow is more efficient than S's solution but I don't see it (and Mehta's solution is not it either). This of course brings the question--what would be the point of implementing 3 stacks in one array? Reply to Comment Sam on October 15, 2010 @Nani Thanks for sharing this but could you tell us little more? Did you do code for this problem or just discuss through phone about space efficiency? Thanks Reply to Comment pankaj4u4m on November 20, 2010 we can create any number of stack in array for each we maintain two index push index and pop index create array with following field: just a sudo code

struct arr{ data // value which we want to store in stack link to previous //index of previous }; g //1 global index p1, p2, p3 // index of last push // initialize -1 r1, r2, r3 // index of last pop // initialize all 0 ///---------push--------------///////////////////// push( n ) // n is stack number in which i want to insert data v1 , v2, v3 = &sort(r1, r2, r3); //reference of sorted indexes assign the data value = data assign previous link = push index of n; push index of n = v1; if(v1 == g)g++; if(v1 != v2)v1 = v2; else if(v1 != v3)v1 = v2 = v3; else v1 = v2 = v3 = g; } ///-----------------pop------------------// pop( n ) int data = data at push index of n pop index of n = push index of n push index of n = link to previous at push index of n return data;

Implement two stacks in a single array. Please note that you should not report stack full until all the elements are full. 5

Tags: Microsoft Data Structures

Question #4180708 (Report Dup) | Edit | History

Mahesh on October 09, 2010 Start from the two ends of the array and move towards the center of the array as elements are being added to the stacks. When the stacks meet, report full. czpete on October 11, 2010

Nice :-) Reply to Comment sachin323 on October 10, 2010 class Stack { private: int arr[200]; int size; int top1; int top2; Stack(int sz) : size(sz),top1(0),top2(size -1) { } bool isfull(){ if(top1 ==0 && top1 == top2) return true; else if(top1 + 1 == top2) return true; return false; } public:

void push_back_1(int elem){ if(!isfull()){ arr[top1++] = elem; } }

void push_back_2(int elem){ if(!isfull()){ arr[top2--] = elem; }

} int pop_1(){ if(top1 == 0) return -1;

return arr[top1--]; } int pop_2(){ if(top2 == size - 1) return -1; return arr[top1++]; } };

czpete on October 11, 2010 Dude, I wonder how the formatting got so messed up ... It seems that your stack would be reported full with some space still left. For example, top1=top2=0 ==> there's still one slot available at 0 or top1=1, top2=top1+1=2 ==> there are slots available at 1 and 2! It would be easier to start at -1 and size and then first increment/decrement and then insert (for Push()) and first read and then decrement/increment for Pop()). Reply to Comment CodeTillYouFaint on October 17, 2010 I guess top1 must be initialised to -1 and top2 to size. And Stack will be full when top1+1 == top2 or top2-1 == top1 Given a binary tree with nodes with integer values write down the code for calculating the average of the numbers. 2 [Full Interview Report]

Tags: National Instruments Data Structures Intern Question #3955901 (Report Dup) | Edit | History veb on October 17, 2010 We can use a recursive function along with static storage for the summation such that value is retained between successive call to the function. This method first computer over left subtree and then on right subtree of the Root of the binary tree.. static specifier maintain the value between recursive calls.. void average(node* start) { static int average = 0; if(start!= NULL) {

Add(node->left); Add(node->right); result += node->value; } } Given a circular link list. struct llsit{ int data; struct llist *nextnode; }; Node contains alternate +ve and -ve value . Now return the node from where if we keep on adding the values of next node we will always have a +ve sum untill we come to same node again. 7

Tags: Data Structures Question #3871417 (Report Dup) | Edit | History Anonymous on September 23, 2010 /* Is implemented as an array but no random accesses and the conversion to linked list is trivial */ #include<stdlib.h> #include<stdio.h> #define SIZE 10 bool verify(int start, int array[]) { int sum = 0; for(int i=start, j=0;j<SIZE;j++, i = (i+1)%SIZE) { sum += array[i]; printf("%d %d\n", sum, array[i]); } } void FindPositiveSubArray(int array[]) { int sum = 0; int current = 0; while(array[current]<=0 && current<SIZE) current++; if(current==SIZE) printf("-1\n"); sum = array[current]; int start = current, diff = 1; current++; while(start<SIZE) {

sum += array[current]; while(sum<=0 && start<SIZE && start<current) { sum-=array[start]; diff--; start++; } if(start == current) { while(array[current]<=0) { current = current+1; if(current == SIZE) { printf("-1\n"); return; } current = current%SIZE; } start = current; sum = array[current]; } current++; diff++; if(diff == SIZE) break; } if(start!=SIZE) printf("%d\n", start); else{ printf("-1\n"); }

} int main() { int i; int array[SIZE] = {2, -3, 4, -5, 6, -7, 10, -6, 7, -7}, pows[2] = {1, -1}; int sign = pows[rand()%2]; /*for(i=0;i<SIZE;i++) { array[i] = sign * rand()%1000; printf("%d %d\n", i, array[i]); sign*=-1; }*/ FindPositiveSubArray(array); } ibnipun10 on September 23, 2010 Can you please explain the logic and the time complexity your algorithm takes?

Reply to Comment Anonymous on September 24, 2010 If any such node is sufficient, then the node with the largest positive value should be the one (if any such node exists). Mahesh on September 24, 2010 Not necessary. Reply to Comment xyz on September 25, 2010 The sum of the complete linked list shall be the same. No matter in which order u add. If we start n finish at the same node then is it not like adding all the positive and negative numbers which shall always give the same answer?? Reply to Comment Raj on September 27, 2010 I agree with xyz, the sum remains the same no matter where you start and sum up all the node values. Can we have some clarification of the question. Reply to Comment billa on October 10, 2010 i think we need to exclude the current node data.. tht will differentiate the answer.. Reply to Comment
Ask for Help Email me w hen new comments are posted

Add a Text Comment | Add Runnable Code Name: Comment:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.
Submit

Chat window too small? Open in new window. Connect via gchat. Access history. How to Get Better Chat Responses - READ THIS FIRST | Disable Chat.

Follow CareerCup on Twitter Follow CareerCup on Twitter More from Glassdoor.com Software Engineering Jobs Software Engineering Salaries Tell me how these DS stored in memory? Hashtables, Dictionary, Trees, Arrays, LinkLists

Tags: Microsoft Data Structures Software Engineer in Test Question #3787052 (Report Dup) | Edit | History SB on September 09, 2010 I think Hashtables : array of objects Dictionary : array of keys and array of values(both at same indexes) Trees : array of nodes with pointers to left and right children. Arrays : array :-) Linklists : array of addresses to objects. Anonymous on September 15, 2010 I think... In memory data is stored only in two ways. Array or link list. Depends on you whether you want for eg a stack to be array or linked list. Dictionary is any DS on which certain operations can be done. So it can be array or list. Reply to Comment ramu kumar on Septembe ou have single linkedlist.Swap every consecutive two elements without using value stored in the node of linkedlist. for eg. 1->2->3->4->5 then output should be 2->1->4->3->5 23 [Full Interview Report]

Tags: Microsoft Data Structures Question #3537658 (Report Dup) | Edit | History anton1172 on August 24, 2010 public class ListNode<T> { private T data; public T Data { get { return data; } } private ListNode<T> nextNode; public ListNode<T> NextNode { get { return nextNode; }

set { nextNode = value; } } public ListNode(T data) { this.data = data; } public override string ToString() { return data.ToString(); } } public class LinkedList<T> where T : class { ListNode<T> head = null; public void Add(T data) { ListNode<T> newHead = new ListNode<T>(data); newHead.NextNode = head; head = newHead; } public void Show() { ListNode<T> current = head; while (current != null) { Console.Write(current.Data.ToString() + "; "); current = current.NextNode; } Console.Write(Environment.NewLine); } private ListNode<T> PrivateSwapTwo(ListNode<T> current) { if ((current != null) && (current.NextNode != null)) { var tmp1 = current.NextNode.NextNode; var tmp2 = current.NextNode; current.NextNode.NextNode = current; current.NextNode = PrivateSwapTwo(tmp1); return tmp2; } else { return current; } } public void SwapTwo() { head = PrivateSwapTwo(head); } }

Reply to Comment SachinGuptaMNNIT on August 24, 2010 /* Program of reverse linked list*/ # include <stdio.h> # include <malloc.h> struct node { int info; struct node *link; }*start; struct node * rev( struct node * head) { struct node * temp = NULL; if ( head == NULL) return NULL; if ( head->link == NULL ) return head; temp = rev ( head->link ); head->link -> link = head; head->link = NULL; return temp; } create_list(int num) { struct node *q,*tmp; tmp= malloc(sizeof(struct node)); tmp->info=num; tmp->link=NULL; if(start==NULL) start=tmp; else { q=start; while(q->link!=NULL) q=q->link; q->link=tmp; } }/*End of create_list() */ display() { struct node *q; if(start == NULL) { printf("List is empty\n"); return; } q=start; while(q!=NULL) { printf("%d ", q->info);

q=q->link; } printf("\n"); }/*End of display()*/ reverse() { struct node *p1,*p2,*p3; if(start->link==NULL) /*only one element*/ return; p1=start; p2=p1->link; p3=p2->link; p1->link=NULL; p2->link=p1; while(p3!=NULL) { p1=p2; p2=p3; p3=p3->link; p2->link=p1; } start=p2; }/*End of reverse() */ struct node *swaptwo(struct node *head) { if((head!=NULL)&&(head->link !=NULL)) { struct node *tmp1=head->link->link; struct node *tmp2=head->link; head->link->link=head; head->link=swaptwo(tmp1); return tmp2; } else return head; } main() { int i,n,item; start=NULL; printf("How many nodes you want : "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the item %d : ",i+1); scanf("%d",&item); create_list(item); } printf("Initially the linked list is :\n"); display(); start=swaptwo(start);

printf("Linked list after reversing is :\n"); display(); }/*End of main()*/ Reply to Comment SachinGuptaMNNIT on August 24, 2010 /*Sachin Gupta MNNIT_ALD above code is for 1>reverse a linklist 2.revese a linklist using one pointer 3.Swap every consecutive two elements without using value stored in the node of linkedlist Reply to Comment SachinGuptaMNNIT on August 24, 2010 /*Swap every consecutive two elements without using value stored in the node of linkedlist use*/ struct node *swaptwo(struct node *head) { if((head!=NULL)&&(head->link !=NULL)) { struct node *tmp1=head->link->link; struct node *tmp2=head->link; head->link->link=head; head->link=swaptwo(tmp1); return tmp2; } else return head; } stag on September 11, 2010 I ran this code ..It works perfectly Reply to Comment Just A guy on August 24, 2010 @Sachin Have u even tried running ur code on ur machine ? It will not do what it is supposed to do and u will even lose data from the list. and ur first code is not using single pointer to reverse list you are taking O(n) space too bcoz of the stack overhead of the RECURSIVE call. Have u written the code urself or ... ? :P SachinGuptaMNNIT on August 25, 2010 //in gcc it is working # include <stdio.h> # include <malloc.h> struct node { int info; struct node *link; }*start; struct node * rev( struct node * head) { struct node * temp = NULL;

if ( head == NULL) return NULL; if ( head->link == NULL ) return head; temp = rev ( head->link ); head->link -> link = head; head->link = NULL; return temp; } create_list(int num) { struct node *q,*tmp; tmp= malloc(sizeof(struct node)); tmp->info=num; tmp->link=NULL; if(start==NULL) start=tmp; else { q=start; while(q->link!=NULL) q=q->link; q->link=tmp; } }/*End of create_list() */ display() { struct node *q; if(start == NULL) { printf("List is empty\n"); return; } q=start; while(q!=NULL) { printf("%d ", q->info); q=q->link; } printf("\n"); }/*End of display()*/ struct node *swaptwo(struct node *head) { if((head!=NULL)&&(head->link !=NULL)) { struct node *tmp1=head->link->link; struct node *tmp2=head->link; head->link->link=head; head->link=swaptwo(tmp1); return tmp2;

} else return head; } main() { int i,n,item; start=NULL; printf("How many nodes you want : "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the item %d : ",i+1); scanf("%d",&item); create_list(item); } printf("Initially the linked list is :\n"); display(); start=swaptwo(start); printf("Linked list after reversing is :\n"); display(); }/*End of main()*/ Reply to Comment another guy on August 24, 2010 if you post pseudo code it will be a lot more helpful to understand btw nice code Anonymous on August 24, 2010 I agree 100%.. Reply to Comment Anonymous on August 25, 2010 p=head,q=head->next while(p->next){ temp=q->next q->next=p p->next=temp if(p->next)p=p->next if(p->next)q=q->next } Reply to Comment Anonymous on August 25, 2010 sorry little mistake in abpve code p=head,q=head->next while(p->next){ temp=q->next q->next=p p->next=temp if(p->next)p=p->next if(p->next)q=p->next } coder on August 26, 2010

i dont think we need three pointers two will suffice code p1 = head; p2=p1->next; while(p1!=NULL&&p2!=NULL) { p1->next = p2->next; p2->next = p1; p1 = p1->next; if(p1!=NULL) p2 = p2->next; } coder on August 26, 2010 sorry a small mistake in the last line p2 = p1->next Happy on August 26, 2010 u are not keeping track of the head in your code. one line could be added inside the while loop,

if(p1 == head) head = p1->next;

Reply to Comment Girish on August 25, 2010

/* keep 4 pointers - prev, first, second and third. */ #include <stdio.h> struct NODE { int val; NODE* next; }; NODE* CreateLinkedList(int* array, int nElems); void PrintLinkedList(NODE* node); void ReverseLinkedList(NODE** node); int main() { //int array[] = {1,2,3,4,5,6,7};

int array[] = {1,2,3,4,5,6,7,8}; NODE* head; head = CreateLinkedList(array, sizeof(array)/sizeof(array[0])); PrintLinkedList(head); ReverseLinkedList(&head); PrintLinkedList(head); return 0;

NODE* CreateLinkedList(int* array, int nElems) { NODE* head = NULL; NODE* curr = NULL; NODE* prev = NULL; for( int i = 0; i < nElems; i++ ) { curr = new NODE; curr->val = array[i]; curr->next = NULL; if( prev == NULL ) { } else { } } return head; } void PrintLinkedList(NODE* head) { printf("Linked List is -->\n"); while(head) { printf("[%d] ", head->val); head = head->next; } printf("\n"); } head = curr; prev = curr;

prev->next = curr; prev = curr;

void ReverseLinkedList(NODE** head) { NODE* prev = NULL; NODE* first = *head; NODE* second = NULL; NODE* third = NULL; if( first )

second = first->next;

while( first && second ) { third = second->next; first->next = third; second->next = first; if( prev == NULL ) else

*head = second; prev->next = second;

prev = first; first = third; if( first ) } } second = first->next;

Reply to Comment SachinGuptaMNNIT on August 25, 2010 /*Reverse a single linked list using single pointer iteratively and recursively (Recursive)for iterative code visit sachingupta.tk */ struct list * reverse_ll( struct list * head) { struct list * temp = NULL; if ( head == NULL) return NULL; if ( head->next == NULL ) return head; temp = reverse_ll ( head->next ); head->next -> next = head; head->next = NULL;

return temp; } Reply to Comment mandeepg on August 25, 2010 Here's my 2 cents: void pairReverse() { struct List *a, *b, *c, *prev=NULL; a = b = c = head; while(c != NULL && c->next != NULL) { if(prev == NULL) head = head->next; a = c; a = a->next; c = a->next; a->next = b; prev = b; b = c; if(c != NULL && c->next != NULL) prev->next = c->next; else prev->next = c; } } Anonymous on September 02, 2010 Good One, Thanks Reply to Comment Ankush Bindlish on September 03, 2010 Please comment on the recursive and iterative version of the problem.

Node RecursiveSwap(Node head){ if((head == null) || (head->next == null)) return head; Node result = head->next; head->next = RecursiveSwap(result->next); result->next = head; return result; } Node IterativeSwap(Node head){ if((head == null) || (head->next == null)) return head; Node p,q; p = head; head = p->next; while((p != null)&&(p->next != null)){

} return head; } Reply to Comment ramu kumar on September 07, 2010 p=head; q=head->next; while(q!=NULL) { swap(p,q); p=q->next; q=q->next->next; } swap(node*p,node*q) { node*temp=p; p=q; q=temp; } Reply to Comment Aseem on October 01, 2010 // We can have a recursive function swap(node *p) { if(p->next==null) return p; else { q=p->next; if(q->next!=null) { pos=swap(q->next); q->next=pos; } p->next=q->next; q->next=p; return q; } Reply to Comment Anonymous on November 27, 2010 swap(Node node){ if(node == null) return prev = null; while(node != null){ next = node.next.next node.next.next = node node.next = next

q = p->next; p->next = q->next; p = p->next;

prev = node node = next } if(prev != null){ temp = node node = node.next node.next = temp } } Reply to Comment Anonymous on November 27, 2010 swap(Node node){ if(node == null) return prev = null; while(node != null){ next = node.next.next node.next.next = node node.next = next prev = node node = next } if(prev.next != null){ temp = node node = node.next node.next = temp } } you have given a node of a tree. that node is defined as below: node( int value, node left; node right; node grandparent) at the starting the grand parent node is null in the tree. you have to assign the grandparent node for all the nodes in the tree. 34 [Full Interview Report]

Tags: Microsoft Data Structures Software Engineer in Test Question #3491945 (Report Dup) | Edit | History S on August 12, 2010 My first idea: 1. complete the rest of the tree with dummy nodes until it's a complete binary tree.

2. do a level order and save it to an array. 3. use the idea from binary heap to get the grand parent. MaYanK on August 12, 2010 My second Idea :) postorder(root,gparent,count){ if(root==null) return; if(count==0){ root.granparent = gparent; count=2; } postorder(root.left,root,count-1); postorder(root.right,root,count-1); } call postorder(root,null,2); MaYanK on August 13, 2010 :( above code is wrong see Frodo's code below. Reply to Comment Frodo Baggins on August 13, 2010 @MaYanK , I think you are assigning parent instead of grand parent here . Every time you are calling postorder(root,gparent,count) -> 1. either gparent is null 2. or gparent->left=root or gparent->right=root so , gparent is not the grand parent here , its parent . One more thing , it will only set the gparent for the nodes where cout = 0 . so , suppose we are at node current_node , then postorder(current_node->left,..) and postorder(current_node->right,..) will be called with count = 1 , and so the gparent for those nodes will not be assigned . MaYanK on August 13, 2010 @Frodo Baggins You are right. :) Sravan on August 21, 2010 We can do level order traversal keeping track of lastnode traversed and parentOfLastNodeTravesed. before dequeuing the next level element enqueue NULL as indication of next level and parentOfLastNodeTravesed traversed. Anonymous on August 23, 2010 Frodo, great solution. spgokul on August 25, 2010 thank you for your solution frodo :) Reply to Comment Frodo Baggins on August 13, 2010 // My code postorder(root,gparent,parent){ if(root==null)return; root->granparent=gparent; postorder(root->left,parent,root); postorder(root->right,parent,root);

} call postorder(root,null,null) ibnipun10 on August 13, 2010 Parent will always be null here ibnipun10 on August 13, 2010 I am sorry, you are right....:) santhosh on August 17, 2010 gud work coder on September 18, 2010 awesome!! Ricardo Neto on November 12, 2010 Good and clean solution! Anonymous on November 20, 2010 superb!!! Reply to Comment harsh1690 on August 13, 2010 void assign_gp(node * root, node * parent) { if(root) { if(root->left) { root->left->gparent=parent; assign_gp(root->left,root); } if(root->right) { root->right->gparent=parent; assign_gp(root->right,root); } } } Fuckass on August 25, 2010 Nice one !! Reply to Comment harsh1690 on August 13, 2010 void assign_gp(node * root, node * parent) { if(root) { if(root->left) { root->left->gparent=parent; assign_gp(root->left,root); } if(root->right) { root->right->gparent=parent; assign_gp(root->right,root); } } } . . . main()

{ root->gpearent=NULL; assign_gp(root, NULL); } Reply to Comment try on August 21, 2010 void SetGrandParent(Node root) { SetGrandParent(null, null, root); } void SetGrandParent(Node grandParent, Node parent, Node root) { node.grandparent = grandparent; if (root.left != null) { SetGrandParent(parent, root, root.left); } if (root.right !=null) { SetGrandParent(parent, root, root.right); } } Reply to Comment Venky on August 27, 2010 public static void AssignGrandParent(TreeNode root) { if (root == null) return; if (root.Parent != null) root.GrandParent = root.Parent.Parent; AssignGrandParent(root.LeftNode); AssignGrandParent(root.RightNode); } AA on September 01, 2010 Node structure does not have Parent field. Reply to Comment O(?) on September 07, 2010 I think if we have both parent and grandparent in the node implementation then it will quite easy implementation. Reply to Comment Sameh.S.Hegazy on September 11, 2010 Here is my C# implementation static void SetGrandParent(Node n, Node parent, Node GrandParent) { if (GrandParent != null) n.GrandParent = GrandParent; if (parent != null) { if (n.Left != null) SetGrandParent(n.Left, n, parent); if (n.Right != null) SetGrandParent(n.Right, n, parent);

} else { if (n.Left != null) SetGrandParent(n.Left, n, null); if (n.Right != null) SetGrandParent(n.Right, n, null); } } and first Call Will be SetGrandParent(tree, null, null); OPTIMIZE DUDE on September 21, 2010 I am sure next five lines could have been enough. n.GrandParent = GrandParent; if (n.Left != null) SetGrandParent(n.Left, n, parent); if (n.Right != null) SetGrandParent(n.Right, n, parent); Sameh.S.Hegazy on September 21, 2010 Yes , right no need for the extra code , thanks for updating me :) Paul on October 03, 2010 how to make initial call with only those five lines. Sameh.S.Hegazy on October 03, 2010 i think OPTIMIZE DUDE means that the code with the method has to be minimized , so the function and the first call will still be the same , i traced it and the same output was generated Reply to Comment Anonymous on September 12, 2010 main(){ assigngrandparent(root->left,root); assigngrandparent(root->right,root); } assigngrandparent(node n,node gpn) { if(gpn!=null) {node->left->gp=gpn; // if there is a left child for node node->right->gp=gpn; // if there is a right child for node } assigngrandparent(node->left,node);// if there is a left child for node assigngrandparent(node->right,node);// if there is a right child for node } CHECK FOR NULL on September 21, 2010 No checks whether n->left or n->right is null. BIG MISTAKE Check for gpn is useless. Reply to Comment Prashant on September 15, 2010 Hi, Simplest approach...

Push(root) while(isempty() == FALSE) { node = pop(); if(node != NULL) { if (node->left != NULL) { node->left->garandparent = node; push(node->left) } else push (NULL); if (node->right != NULL) { node->right->garandparent = node; push(node->right); } else push (NULL); } } And there u go dude... Where to go dude on September 21, 2010 U are only assigning the parents to the nodes. At least check your solutions before putting here. Reply to Comment i.shahin on September 28, 2010 void set_grand(node* n, node *p) { if(!n) return; if(n->left) { n->left->gp = p; set_grand(n->left, n); } if(n->right) { n->right->gp = p; set_grand(n->right, n); } } set_grand(root, 0); Reply to Comment Vinay on October 31, 2010

Simplest Solution: void assignGrandParent(Node* curr, Node* parent, Node* gparent) { if(curr == NULL) return; curr->grandparent = gparent; assignGrandParent(curr->left, curr, parent); assignGrandParent(curr->right, curr, parent); } Is there anything wrong with this approach: Reply to Comment Mi Jalgaonkar on June 18, 2011 class TreeNode { public int Data { get; set; } public TreeNode Left { get; set; } public TreeNode Right { get; set; } public TreeNode GrandParent { get; set; } public TreeNode(int data) { this.Data = data; this.Left = null; this.Right = null; this.GrandParent = null; } public void SetGrandParent(TreeNode root) { Queue<TreeNode> q = new Queue<TreeNode>(); q.Enqueue(root); TreeNode current = null; while (q.Count > 0) { current = q.Dequeue(); if (current.Left != null) { q.Enqueue(current.Left); CheckChildren(current.Left, current); } if (current.Right != null) { q.Enqueue(current.Right); CheckChildren(current.Right, current); } } }

private void CheckChildren(TreeNode parent, TreeNode grandParent) { if (parent.Left != null) { parent.Left.GrandParent = grandParent; } if (parent.Right != null) { parent.Right.GrandParent = grandParent; } } public void DisplayFamily(TreeNode node) { if (node == null) { return; } DispayFamily(node.Left); Console.WriteLine(" Grand father of {0} is : {1}", node.Data, (node.GrandParent == null) ? "Null" : node.GrandParent.Data.ToString()); DispayFamily(node.Right); } }

Вам также может понравиться