Top Banner
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.
177

Quiz

Nov 01, 2014

Download

Documents

rajeevpathak

Numerical Computer Science Quiz
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Quiz

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 testQuestion #9708961 (Report Dup) | Edit | History

AL on July 06, 2011External sort. Also k-select may handle this.Anonymous on July 06, 2011but what about the products, i mean overflow??If_else on July 06, 2011How about min-heap?Reply to CommentDan on July 06, 2011Depending 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 CommentAnonymous on July 06, 2011Create 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 facingafter 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, 2011Good one if numbers are int32 or less.Wouldn't work if longs or floats.Reply to CommentWgpShashank on July 07, 2011we 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/32Algorithm1.create min-heap of size K2. 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 heapify3. repeat whole algo until EOFour heap will contain the k largest elements , return product of all the elemnmts in heap will give us answerTime Complexity (O(k)+O(n-k)logk)Do Notify me if i am wrong or any other algo ??Shashankswathi on July 10, 2011

Page 2: Quiz

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 / DeveloperQuestion #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){

pA[k]=pB[j];

Page 3: Quiz

j--;}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--;

}}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, 2011Just 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, 2011I 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

Page 4: Quiz

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, 2011more readable and beautiful than mine.O(1) on June 29, 2011nice solutionReply to Commentleeym 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, 2011your 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 Commentsomeone on June 26, 2011

Page 5: Quiz

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>=03) 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 Commentlol on June 27, 2011Using 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, 2011a correction: a queue is sufficient here. deque would be overkill.lol on June 27, 2011Ignore this stupid post. It's too obvious to find O(1) space solution. If interested, look here : ideone.com/dITsAReply to CommentiCoder on June 28, 2011IMO, the solutions above are O(n+m) time.Reply to CommentAnonymous 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++]; } }

Page 6: Quiz

}

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 CommentAnonymous 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++;

Page 7: Quiz

} else { a[x] = b[j]; x++; j++; } } while (j < sizeOfb) { a[x] = b[j]; x++; j++; } }Read a file of this format:

japanusajapanrussiausajapanjapanaustralia

Print the output in the following format:<country> : <count>So for above file output would be:

japan : 4usa : 2australia : 1russia : 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 / DeveloperQuestion #9538861 (Report Dup) | Edit | History

Vikas on June 19, 2011import java.util.*;public class hash {public static void main(String[] args) {String str[] = {"russia","japan","russia","india"};int len = 4;Hashtable ht = new Hashtable();

Page 8: Quiz

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));elseht.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, 2011Solution is incomplete. You are not sorting the same value members.Anonymous on June 20, 2011why we need to sort ..?...same value members are getting hashed together...@vikas on June 20, 2011the 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, 2011What if you had japan and jamaica ? Both will be hased togatherAnonymous on June 22, 2011What if you had japan and jamaica ? Both will be hased togatherReply to CommentUpt on June 19, 2011After inserting all of them in the hashMap we can make tree sets of the same value types.Reply to CommentAnonymous on June 20, 2011Correct algorithm is TRIE treeReply to Commentmemo on June 20, 2011Most efficient doesn't mean anything. Most efficient in space, time, what?Reply to Commentscot on June 21, 2011This 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

Page 9: Quiz

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, 2011the 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 test19   [Full Interview Report]

Tags: Amazon » Data Structures  » Software Engineer / DeveloperQuestion #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, 2011niceReply to Commentwhataheck on June 12, 2011

Page 10: Quiz

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, 2011classicReply to CommentAnonymous on June 12, 2011@whataheck - Your would not handle case like '((()))'...it is good for case '()()()' onlyRakesh Kumar on June 13, 2011he just needs to check at the end whether stack is empty or not and not before every pushReply to CommentUT on June 13, 2011Assumption: 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, 2011Hey, what about a string "()))((" .Above string is not wellformed. I prefer to go for using stack data structureUT on June 13, 2011my solution will return false with your case you mentioned. what is wrong with that?Reply to CommentWhataheck on June 13, 2011I 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 / DeveloperQuestion #9289896 (Report Dup) | Edit | History

Anonymous on June 11, 2011

Page 11: Quiz

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 CommentAnonymous on June 12, 2011array has cache invalidation problems if you're trying to update...i would have said linked list for sort and array for search...Reply to Commentsomeone on June 13, 2011for 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, 2011Searching an unsorted array takes linear time, but you can do binary search on a sorted array.Reply to CommentAnonymous on July 02, 2011for 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 listas 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 toWhat is Hashtable, using which data structure hash table is implemented4   [Full Interview Report]

Tags: Amazon » Data Structures  » Software Engineer / DeveloperQuestion #9114360 (Report Dup) | Edit | History

unknown on June 11, 2011i feel that it will be implemented using an array..Reply to CommentAlgorithmist on June 13, 2011Depends 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 treesAnonymous on June 21, 2011hey 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 CommentAnonymous on June 22, 2011hashtables are also built using self balancing binary trees

Page 12: Quiz

Given a binary matrix of N X N of integers , you need to return only unique rows of binary arrayseg:0 1 0 0 11 0 1 1 00 1 0 0 11 1 1 0 0ans:0 1 0 0 11 0 1 1 01 1 1 0 028 

Tags: Google » Algorithm Coding, Data Structures, Algorithms Data Structures Matrix  » Software Engineer

Question #9478119 (Report Dup) | Edit | History

Ishan on June 09, 2011Find 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 valuesnee.agl on June 09, 2011basically 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, 2011Sorting n items of n length string would be O(n*nlogn). so better use hashing...Anonymous on June 13, 2011Wouldnt it overflow if n is greater than bits in word of the platform.mnit.rohit on June 15, 2011TO 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 advancerahul 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 advanceReply to CommentRakesh Kushwaha on June 09, 2011

Page 13: Quiz

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 CommentAnonymous on June 09, 2011TRIE data structure can work fine for this problem!!!asdf on June 09, 2011how to implement it?Anonymous on June 09, 2011ukkonen could do that in O(n)!google the algorithm (Ukkonen suffix tree online).the only change to do = count leaf nodes during tree building processReply to CommentAnonymous on June 09, 2011xor each row with every other.nee.agl on June 09, 2011O(N^2)!Rakesh Kushwaha on June 09, 2011Please note that problem is talking about 0 to N number , not binary numbernee.agl on June 10, 2011Ya.. so wud be O(n^3)...Reply to CommentAnonymous on June 10, 2011We 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 CommentKVF on June 10, 2011We 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, 2011can 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 occurOrr on June 13, 2011How 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 CommentSupraja on June 12, 2011Hi

Page 14: Quiz

The return should be inplace ?And Java has Arrays.equals(arr1, arr2);ThanksSReply to CommentSupraja on June 12, 2011Also constructing a trie if N is not very big is not so optimal I guess ?How much is optimization important in interviews ? Anyone ?ThanksSAbhi on June 14, 2011Constructing 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 caseAbhi on June 14, 2011My 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, 2011Space requirement for TRIE will be O(n^2) whereas will be lesser for hashingSo, hashing seems to be a more viable option.Correct me i I am wrongReply to CommentAbhi on June 14, 2011Here is my code for this..taking N=5 here for example

#include<stdio.h>#define N 5int 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++)

Page 15: Quiz

{ 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 rahulhe 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 CommentAnonymous on June 15, 2011since 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 

Page 16: Quiz

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 tree19 

Tags: Google » Algorithm Data Structures Trees and Graphs  » Software EngineerQuestion #9249473 (Report Dup) | Edit | History

Vipul on June 09, 2011I 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 nodesnodes 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, 2011Sorry 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 nodesnodes 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

Page 17: Quiz

@vipul can write the code for it..i need to aware for Time Complexity ..???Reply to CommentRahul on June 09, 2011@vipul can write the code for it..i need to aware for Time Complexity ..???Vipul on June 09, 2011Time complexity will be O(nlog n)Rohit on June 09, 2011But the requirement is of a recursive solutionVipul on June 09, 2011Here 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); }

Page 18: Quiz

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, 2011Your time complexity will be O(n * n) in the worse case.

Page 19: Quiz

rahul on June 21, 2011@vipul Awesome work Man Keep it up...:)Reply to CommentJuvN on June 11, 2011This 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, 2011Maybe 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 youReply to CommentMobile Lover on June 13, 2011If 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 Commentchina.taoqin on June 14, 20111. 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 Commentchina.taoqin on June 14, 2011Using the array2, construct BST O(nlogn + nlogn). Sorry:)Reply to CommentSolution Part 1 on June 17, 2011package org.nrec.probs;import java.util.Comparator;public class MNodeI implements Comparator<MNode>{@Overridepublic int compare(MNode arg0, MNode arg1) {if(arg0.i > arg1.i){return 1;}else if(arg0.i < arg1.i){

Page 20: Quiz

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>{

@Overridepublic 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 CommentSolution Part 2 on June 17, 2011

package org.nrec.probs;

import java.util.Comparator;

public class MNodeJ implements Comparator<MNode>{

@Overridepublic int compare(MNode arg0, MNode arg1) {

if(arg0.j > arg1.j){return -1;

}else if(arg0.j < arg1.j){

Page 21: Quiz

return 1;} return 0;

}

}

Reply to CommentSolution 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){

Page 22: Quiz

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,

numbers.size());}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;

if(rightSubTree != null)root.right = createBSTHeap(rightSubTree);

elseroot.right = null;

System.out.println("Returning back \n node :: "+ root);System.out.println("Left :: "+root.left);System.out.println("Right :: "+root.right);return root;

Page 23: Quiz

}

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 CommentEdit on June 17, 2011The traversal is inorder .... although by mistake I have named it as preorder !!!

Page 24: Quiz

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 EngineerQuestion #9464167 (Report Dup) | Edit | History

Rakesh Kushwaha on June 08, 2011struct linkInfo {char *link;uint refcount;};struct Historydata {uint linkInfoVecIndx; // uint let unsingned uinttime_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 indxh->linkInfoVecIndx = LinkInfovec.size() -1;h->timestamp =h->timestamp; } }anonymous on June 08, 2011When 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.

Page 25: Quiz

Anonymous on June 09, 2011You have to sort the vector based on ref count to give the most visited pages per dayReply to Commentkrishna on June 09, 2011I 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 Commentkrishna on June 09, 2011I 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 CommentAshish Kaila on June 09, 2011Heaps 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 CommentSupraja on June 12, 2011HiWont 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.ThanksSReply to Commentsudo on June 12, 2011A 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 Commentkkishore on June 15, 2011Splay trees???Write a data structure to count number of connections on web server in last 1 minute.6 

Page 26: Quiz

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

bylike on June 04, 2011red-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 CommentAshish Kaila on June 05, 2011I 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, 2011seems to fine to me.Reply to CommentHarshit on June 05, 2011Ill 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 Commentrsl on June 05, 2011circular array + sum integer.On new entry (x = number of connections in last second):add entry to array (index 0)sum = sum+xsum = sum - array(current index - 60);remove last entry from array.Reply to Commentkrishna on June 09, 2011a hash vector of size 60 will do i guess . ie int count[60].Reply to CommentHow 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

Page 27: Quiz

Question #9406138 (Report Dup) | Edit | History

loser on June 04, 2011median of medians recursively?pansophism on June 06, 2011smart choiceReply to CommentAnonymous on June 04, 2011selection algorithm?Reply to CommentDarkLord on June 04, 2011It can be done by modifying the partition algo of quicksort...Reply to Commentswathi on June 05, 2011it should be an external sortReply to Commentmolla on June 05, 2011it should be an AVL tree,then root is always the median.Reply to CommentAnonymous on June 06, 2011Select Algorithm...no need to sort the array..linear timeReply to CommentAshish Kaila on June 09, 2011Modify 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 min5. Return (index + index1) / 2;Reply to CommentAnonymous on June 14, 2011Use 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());

Page 28: Quiz

} 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 EngineerQuestion #9382096 (Report Dup) | Edit | History

Anonymous on June 02, 20111) Merge sort2) Hadoop + HiveReply to CommentS on June 02, 20111. 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 CommentYashwanth Redd y on June 02, 2011have 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 CommentAshutosh on June 02, 2011Divide the file in chunks. Use Map reduce methodologyAnd 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, 2011There 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.eA,B,C,D,C,A ===> B,D

Page 29: Quiz

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, 2011As 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 filek = # of computersstep 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) timeso, total complexity O(n log k)Reply to CommentAnonymous on June 04, 2011why 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, 2011Probably you overlooked the thing of "huge" file. You can have a 5GB file which won't be fitted into your memory.Reply to Commentbothell on June 05, 2011using 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 EngineerQuestion #9286473 (Report Dup) | Edit | History

lol on May 23, 2011Are you sure? I think there exists NO algorithm to solve it < O (logn) time.sanjeevsince90 on May 23, 2011

Page 30: Quiz

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 cannotReply to CommentAnonymous on May 23, 2011it can be done in only one binary search pass.let start =0, end = n-1look 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, 2011Can you post some sample code to achieve this?Reply to CommentKishore on May 24, 2011When 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 arrayarr[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 arrayif(value > arr[pivot])search(arr, pivot+1, end, value);elsesearch(arr, start, pivot-1, value);case 2: //DESC array if(value < arr[pivot])search(arr, pivot+1, end, value);elsesearch(arr, start, pivot-1, value);case 3: if(value > arr[pivot]) //arr[pivot] is smallest element in array

Page 31: Quiz

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, 2011that's not a rotated array..original array: 2,3,4,5,6rotated array: 4,5,6,2,3Anonymous on June 09, 2011Very nice... good job..Reply to CommentAnonymous on May 24, 2011Sorry forgot to remove the last lineif(pivot){Reply to CommentAnonymous on May 24, 2011first 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 arraysso total time complexity is logn+logn1+logn2=logn where n1,n2 are less than n.correct me if i am wrongReply to Commentkumarasvn 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;

}

Page 32: Quiz

return -1; }

Reply to Commentsid 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 Commenttoajay.iitd on May 30, 2011You need to search the max element rank. That will partition the array into 2 parts. First part higher values. Second part lower values. Its likea1<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 CommentAnonymous on June 02, 2011int 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;

Page 33: Quiz

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 Commentneh on June 02, 2011Check 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 CommentAmm 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;}

Page 34: Quiz

return -1;}

//FIND X IN SORTED ROTATED ARRAYint 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 sortedif (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);

elsereturn 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 EngineerQuestion #9303687 (Report Dup) | Edit | History

ankit on May 23, 2011this can be done without recursionsanjeevsince90 on May 23, 2011They asked me to try using recursion when I was trying without...Reply to CommentAnonymous on May 23, 2011LinkedListNode* toLinkedList (Node *curr_node) { if (curr_node == NULL) return NULL;

Page 35: Quiz

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, 2011A very good attempt. But does your solution return the head node of the linked list?wfchiang on May 24, 2011oh.... 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 valHow to serialize/de-serialize a binary tree?8   [Full Interview Report]

Tags: Google » Data Structures  » Software EngineerQuestion #9253182 (Report Dup) | Edit | History

Orr on May 20, 2011Binary 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 CommentGoogler on May 20, 2011When 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,

Page 36: Quiz

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, 2011Correct, we can use Inorder & Preorder traversal also to store the data can construct same tree again.Reply to Commentwfchiang on May 20, 2011I 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 NULLIf there is a unbalanced tree such as a -> b and cb -> d (only one child)Then it will be recorded as a b d NULL NULL c NULLIn this case, we can de-serialize the tree properly....Reply to Commentrusl 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 {

Page 37: Quiz

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 CommentRoxanne on May 25, 2011Why 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 CommentAnonymous on May 26, 2011Sorry 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, 2011Use a preorder traversal.Emit (key, child1index, child2index,...) for each nodewhere 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 TestQuestion #9106620 (Report Dup) | Edit | History

Anonymous on May 15, 2011i don think there's any sorting technique in O(n) timeAdi on June 12, 2011Given 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, 2011sorted dictionary uses binary tree internally which would cost O(nlogn).Reply to CommentAnonymous on May 15, 2011i don think there's any sorting technique in O(n) timeReply to CommentAnonymous on May 15, 2011

Page 38: Quiz

i don think there's any sorting technique in O(n) timeReply to Commentcelicom on May 15, 2011Use any "Non-comparison sorts" (see wiki)Reply to CommentAnonymous on May 15, 2011counting sortAnonymous on May 17, 2011see the range of values and assumption made in counting sort........... counting sort fails on large rangeAshish Kaila on June 16, 2011Radix sort does not suffer from large range of numbers and its O(n)Reply to CommentHere is the solution with o(2n) ~ O(n) on May 15, 2011static 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, 2011That'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 Commentazgirlcoder on May 15, 2011Bucket sort should workanonymous on May 16, 2011

Page 39: Quiz

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, 2011O(n) is a deception. Cos k is not a constant its arbitraryAnonymous on May 16, 2011O(n) is a deception. Cos k is not a constant its arbitraryianam on May 17, 2011Nonsense, 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, 2011To 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 CommentAnonymous on May 16, 2011counting sort ,Reply to CommentAnonymous on May 16, 2011what about using hashing technique ?Reply to CommentAnonymous on May 16, 2011Hash 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 CommentAnonymous on May 16, 2011But, 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 Commentguru on May 16, 20111. set the appropiate bits in a bit array2. print the array index whoes bit is set.Anonymous on May 16, 2011Though 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, 2011isnt it O(max-min) in time too?ianam on May 16, 2011Fails 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 CommentInfinity on May 17, 2011

Page 40: Quiz

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, 2011You must believe in magic. An O(1) map is not sorted, and a sorted map is not O(1).Infinity on May 18, 2011The 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 Commentjay on May 17, 2011Following are the steps to solve it in O(n):1) Create a BST for the array2) do inorder traversalPlease correct me if I am wrongfoobar on June 14, 2011you cant build a BST in O(n). any kinda comparison sort algorithm have the lower bound of O(nlogn).Reply to CommentAnonymous 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 CommentAnonymous on May 18, 2011In my opinion, Radix sort is good enough for this question...Reply to CommentVIP on May 18, 2011Radix sort will do it in O(kn) where k = max possible no. of digits in an element.for the example case-1 1 1 2 2 4 444 44 5 5 45 45 61 1 1 2 2 4 4 5 5 6 444 44 45 451 1 1 2 2 4 4 5 5 6 44 45 45 444Each 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, 2011This approach will fail if all are dupilicate. Then result will be O(nXn).Orr on May 27, 2011Radix 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 Commentappscan on May 23, 2011I guess it is radix sort, which in this case is O(3n).Reply to CommentAshish Kaila on June 09, 2011Counting 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 Commentfoobar on June 14, 2011

Page 41: Quiz

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 CommentSathish on June 15, 2011The 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 / DeveloperQuestion #8875952 (Report Dup) | Edit | History

jobsearch99 on May 01, 2011threaded 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 Commentabcd on May 01, 2011Morris TraversalReply to Commentmersulo on May 02, 2011Thanks to abcd, found Morris traversal on StackOverflow. Didn't expect the structure can be modified. Elegant solution.Reply to CommentRV on May 04, 2011How 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, 2011Its mentioned no extra space....Reply to CommentAnonymous on June 24, 2011

public void morisTravel(Node localRoot){

Node current=localRoot;

Page 42: Quiz

while(current!=null){

if(current.leftChild==null){System.out.print(current.key+ " ");current=current.rightChild;

}else{

// Find Inorder predecessorNode pre=current.leftChild;while(pre.rightChild!=null && pre.rightChild!=current)

pre=pre.rightChild;

// Set Linksif(pre.rightChild==null){

pre.rightChild=current;//

current=current.leftChild;// Make current to predecessor of current

}// Restoreelse{

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 exampleif you have /.../ then remove the letters before and itselfwww.bing.com/abc/asd/asdffg/../../2 

Tags: Microsoft » Data Structures  » Software Engineer / DeveloperQuestion #8344017 (Report Dup) | Edit | History

Page 43: Quiz

Anonymous on May 12, 2011As 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 CommentAnonymous on July 11, 2011Split 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 itthen pop everything and prepend itWhen would you use a hash table? Specific situations were asked1   [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, 2011Hash 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 functio2nd phone screen)reverse pair of elements in a linked list.eg. abcdef shouldbecome badcfe17   [Full Interview Report]

Tags: Amazon » Data Structures  » Software Engineer in TestQuestion #7920663 (Report Dup) | Edit | History

woohoo on February 28, 2011In C

Page 44: Quiz

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, 2011nice solution !Reply to CommentPKT on March 01, 2011divide linklist into two parts:a->c->e->g...andb->d->f->h....now change the order subLinkListsecondListNode->firstListNodeb->a->d->c->f->e->....Reply to CommentWgpShashank 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);

Page 45: Quiz

}}Reply to Commentrj 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 CommentAnonymous 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;

}while(prev!=null);}return head;

} Anonymous on March 03, 2011Using double pointers will be more efficientReply to CommentAnonymous 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; }

}

Page 46: Quiz

Anonymous on March 08, 2011forgot to add return revso 

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 CommentSomdip 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));

Page 47: Quiz

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;

Page 48: Quiz

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 timeto execute or its not what was asked for.Thanks in advance...Dhawal on March 26, 2011Nice!!Reply to CommentSachin on March 31, 2011Simple 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 CommentAnonymous on March 31, 2011ignore extra braces at start and endReply to [email protected] on June 26, 2011

public void reversePair(){LinkedListNode previous=head.link; // First ElementLinkedListNode current=head.link.link; // Second ElementLinkedListNode 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;

}

Page 49: Quiz

if(previous.link!=null){previous.link=current.link;current.link=previous;

}else{

tmp2.link=previous;}

}Reply to CommentAnonymous on July 12, 2011// 1-2-3-4-5-6-7// 2-1-4-3-6-5-7ListNode* 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 CommentAnonymous on July 12, 2011

// 1-2-3-4-5-6-7// 2-1-4-3-6-5-7ListNode* 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;

}

Page 50: Quiz

return nodeToReturn;}Anonymous on July 12, 2011One minor correction and recursive function too.

// 1-2-3-4-5-6-7// 2-1-4-3-6-5-7ListNode* 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-7ListNode* 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);

Page 51: Quiz

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, 2011You 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, 2011A 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 s13. 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, 2011Ah good call. Thank you for that!

PKT on February 26, 2011Awesome approch...!

sidhartha.mahapatro on February 26, 2011WOW.. Appreciated. Good logic.

If anybody publish some code then that will really help.

sidhartha.mahapatro on February 26, 2011

Page 52: Quiz

WOW.. Appreciated. Good logic.

If anybody publish some code then that will really help.

Lavanya on March 13, 2011Can you tell me what's the optimization in anurag singh's answer over nugarp's.

nugarp on March 13, 2011I had additional popping when not necessary

Searching on April 20, 2011@Anurag Singh, good approach!!!!

Reply to CommentAnonymous 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, 2011Awesome! Thanks for the elegant code snippet.

Reply to CommentAnonymous on March 13, 2011#include <iostream>using namespace std;

Page 53: Quiz

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()

Page 54: Quiz

{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);

Page 55: Quiz

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--)

Page 56: Quiz

{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];

}}

Page 57: Quiz

}

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

Tags: JP Morgan » Data Structures  » Software Engineer / DeveloperQuestion #7801682 (Report Dup) | Edit | History

Anonymous on February 23, 2011collision, and quality of hash functionReply to CommentAnonymous on February 27, 2011load factorReply to CommentAnonymous on March 05, 2011When 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 Imdb6 

Tags: Amazon » Data Structures  » Software Engineer / DeveloperQuestion #7801675 (Report Dup) | Edit | History

Hamed on February 25, 2011may 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, 2011dont we need to store a 'movie_id' field as well to handle duplicate movie names?Reply to Commentamm on February 25, 2011something 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.

Page 58: Quiz

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, 2011Maintain 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 CommentAnonymous on February 17, 2011it 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;

Page 59: Quiz

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 Commentshreyas.behera on February 17, 20111. 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){

Page 60: Quiz

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 LLTRight->Right = Root->Left;

DeleteNode = Root;Root = Root->Right;Free(DeleteNode)

}}

Reply to CommentSathya 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, 2011Nice Solution :)

Page 61: Quiz

Reply to Commentswap1712 on February 18, 2011Correct 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, 2011I didn't read the "memory must be handled manually" requirement at first, ignore the previous comment.

Reply to Commentaragorn on February 20, 2011I 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, 2011Will 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, 2011Read the question.It says recursion is not allowed

Reply to CommentRip on February 24, 2011Can't it be solved just by a postorder tree walk?

ashish on February 26, 2011I 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

Page 62: Quiz

if you want to do postorder without recursion then we can do it by using stack and flag.

Anonymous on March 03, 2011Post-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, 2011The above does not work because there is a repeated number.

koundi on February 08, 20111 2 3 4 5 6 7 sum 281 2 3 4 5 7 7 sum 29difference = 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 101 2 2 3 sum 8difference = 2 repeated num = 2 abs(difference) + repeated nmber = 4 i think we can check abs(difference) - repeated number

Reply to CommentAnonymous on February 08, 2011There is nothing said like numbers will be from 1 to n in sorted order. It can be in any order

Reply to CommentSathya on February 08, 2011

int sum=0,sqsum=0;

Page 63: Quiz

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) spaceSathya on February 08, 2011sorry typo should be sqsum+=a[i]*a[i]; not sqsum+=sqsum+a[i]*a[i];

siva.sai.2020 on February 09, 2011Great answer

S on February 09, 2011Yes, indeed a great answer but you should be careful with the final formula.

Let dif = [n*(n+1)/2] - sumLet DIF = [n*(n+1)*(2n+1)/6]-sqsumIf dif = 0, no number is missing.Elsem-r = dif => r = m - difm^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 CommentCode Saviour on February 08, 2011The 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)/2b) 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.

Page 64: Quiz

Substitute in original equation to get the value of y.

GekkoGordan on February 08, 2011ya.. 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, 2011ya, 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 CommentAnurag Singh on February 08, 2011If 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, 2011without using extra space, we have to find missing number.

Anonymous on February 09, 2011who said than we can`t use extra space?

Reply to CommentAnonymous on February 09, 2011compute sum, y-x = sum - n*(n+1)/2compute 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

Page 65: Quiz

2009radha9 on March 13, 2011I 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 CommentAnonymous on February 09, 2011Let 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+yIf you add all the numbers in the array and subtract if from n(n+1)/2 you will get x-yThen solve the 2 simultaneous equations.

Let n=3A[1,2,1]1 is repeated twice and 3 is missing.n(n+1)/2 = 6XOR A =2x+y=4Solving we get both missing number and repeated number.Add A = 4x-y=2

Guest on February 10, 2011I think Xor solution does not work.Let's sayx is missing number and y is repeated numberand n = 5Array is {1,2,3,4,4}. Here x = 5, y = 4 Sum you have mentioned is = n(n+1)/2 = 15Xor of all the numbers is (1^2^3^4^4) = 0Difference 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 CommentAnonymous on February 09, 2011We can use xor for this problem..For eg:let n be 3 and the given numbers be 1 2 2Let 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

Page 66: Quiz

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, 2011This 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.= 1Last 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 Commentchennavarri on February 09, 2011Here'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{

Page 67: Quiz

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, 2011Good answer..

Anonymous on February 09, 2011ya... I think this is the best one for this problem

PKT on February 20, 2011awesome chennavarri...!

Reply to CommentGuess who?? on February 09, 2011Since 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];

Page 68: Quiz

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, 2011This is probably the most efficient solution.

souravghosh.btbg on February 13, 2011Simply amazing! The simplicity!

kk on March 26, 2011Simply amazing, I love it

Reply to Commentgodblessme 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);}

Page 69: Quiz

for(int i=0;i<a.length;i++){if(m.containsKey(a[i]+"")){m.remove(a[i]+"");}}

//only one item leftSystem.out.println( m.values().iterator().next() );

}

Anonymous on February 11, 2011This is O(n) time and O(n) space solution

Reply to CommentAnonymous on February 11, 2011#include <stdio.h>#include <conio.h>#define N 10int 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

Page 70: Quiz

2. Sum of this array=143. Sum of square of n numbers= n*(n+1)*(2n+1)/6=554. Sum of square for this array=485. 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, 2011Typoa be the actual numberb be the number repeated

Reply to Commentpansophism on February 16, 2011xor would be the answer.a xor a == 0;for(numbers in array first to second last){i xor i + 1 }

Reply to CommentAnonymous on February 16, 2011int flag =0;int count =1;int missing_num;int a[n]; //the array with n numbersint main(){while(flag =0){for(int i=1;i<=n;i++){if(count==a[i]){count++;flag=0;break;

Page 71: Quiz

}else{missing_num = count;flag=1;}}}printf("The missing number is: %d",missing_num);return 0;}

Does this solution seem good?

Reply to Commentdexter 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.

Page 72: Quiz

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, 2011Not 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 BSTUsing 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, 2011A 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)

Page 73: Quiz

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, 2011I 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 Commentasetech on February 08, 2011you 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 CommentGekkoGordan on February 08, 2011How about k-d treeBuilding a k-d tree: O(n log 2 n) Insertion; O(logn)Searching closest point: O(sqrt(n))

Anurag Singh on February 08, 2011Yes. Look like k-d tree is the right answer.

Page 74: Quiz

siva.sai.2020 on February 09, 2011I spent 30 min to understand k-d tree but I couldn't.

chennavarri on February 09, 2011Look at Animation of NN searching with a KD Tree in 2D on wikithat might help visualize. thanks

Reply to Commentsg .. on February 09, 2011please someone put some gud tutorial like on K-d tree ...

Anonymous on February 09, 2011if 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 right-subtree 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, 2011thanks

Neha on February 10, 2011For 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 CommentRh on February 15, 20112. Divide and Conquer Solution.See cormen chapter 33 Computational Geometry.

Page 75: Quiz

Complexity O (n log n).

Reply to Commentswathi on July 05, 2011you 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 cooridinateb) 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 interviewQuestion #7635661 (Report Dup) | Edit | History

SB on February 08, 2011sorting is the best I could think of.Reply to CommentAnonymous on February 08, 2011hash table with value=countReply to CommentAnonymous on February 08, 2011can do it by hashing each element and if found the same element then return that numberReply to CommentSG ... on February 08, 2011Did he mentioned any other condition or restrictions for entries in array ?Reply to Commentyours.ramesh on February 08, 2011what about other elements in the array, how may times they are repeated...are there any restrictions on that?Reply to CommentAnonymous on February 09, 2011How 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 numberTime Complexity ---> O(n)Anon on February 09, 2011It doesn't say that the rest are repeated an even number of times - could be 1 or 5Anonymous on February 10, 2011@anonymous : please read the Q carefully before answering.

Page 76: Quiz

Reply to Commentsatyah920 on March 02, 2011Instead 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 1d on March 04, 2011what abt a[9]={1,3,3,2,4,4,2,1,1,2} ??? it fails ..Reply to [email protected] on June 26, 2011public 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 CommentPraveen on July 01, 2011Assuming 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 numbersFind the sum of cubes of all N numbers - cubes of given N numbersSolve 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 beginning12   [Full Interview Report]

Page 77: Quiz

Tags: Bloomberg LP » Data Structures  » Financial Software DeveloperQuestion #7582661 (Report Dup) | Edit | History

Anonymous on January 19, 2011Max Priority QueueReply to CommentAnonymous on January 19, 2011Max Priority QueueReply to Commentsiva.sai.2020 on January 19, 20111. 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->33) 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 ------------------- | |

Page 78: Quiz

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, 2011A modification to your code, you dont need two hash tables. only one which contains the following for every numberkey=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, 2011Sorry, 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, 2011Time 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 CommentAman on January 20, 2011Why 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 CommentAnonymous on January 25, 2011@gekko and sivaIn a hash table, the order of the tuples is not guaranteed.You'll need to use a TreeMap.Reply to Commentyogesh on January 28, 2011Answer 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,

Page 79: Quiz

Else Max heap is the only option i believeReply to CommentAb on March 05, 2011Why not use a Splay tee??&troller on March 14, 2011why 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 / DeveloperQuestion #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, 2011to binary search, you have to sort the dictionary as a preliminary step. It costs a lot...Myth on January 12, 2011Wont the dictionary be in sorted order? They always are :|kmadhu3042008 on January 12, 2011I 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

Page 80: Quiz

yup. we could always omit the 2nd second search if the first boolean returns a false. Skipped off my mind. :)Divij on January 18, 2011When 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 CommentAnonymous on January 11, 2011Use TRIE data structureReply to Commentketz on January 11, 2011the better data structure required here is suffix treetrie 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, 2011yep. this is a typical question designed for suffix tree.anonymous on January 13, 2011Could anyone pls explain how to use suffix tree to solve this problem?Reply to Commentqbird on January 12, 2011How 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 charsList<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);

Page 81: Quiz

// 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 CommentAnshul on January 16, 2011Not 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, 2011I agree.Reply to CommentAnonymous on January 17, 2011#include <iostream>#include <dictionary>#include <string>

using namespace std;

Page 82: Quiz

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 [email protected] on June 24, 2011package 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){

Page 83: Quiz

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;

elsereturn 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");

Page 84: Quiz

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 tree13 

Tags: Facebook » Data Structures  » Software Engineer / DeveloperQuestion #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 Commentriderchap 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 CommentNJ on December 13, 2010

Page 85: Quiz

None of the two approaches seem good since they end up searching the entire tree.Reply to Commenttesting comments on December 13, 2010no moderation or manual moderation ?Reply to CommentAnonymous 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, 2010I 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 correctReply to Commentgg on December 14, 2010int min_depth(node_type *root){if(root==NULL){return 0;}

Page 86: Quiz

else{return (1 + min(min_depth(root->left) , min_depth(root->right)));}}please mind that in the called function we have to deduct 1h=min_depth(root);depth=h-1;so depth is the minimum depth of the tree.Anurag Singh on January 23, 2011This 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 CommentBig-O on December 15, 2010Sorry 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 Commentr.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; } } }

Page 87: Quiz

Reply to Commentss on January 23, 2011int 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 CommentAnurag Singh on January 23, 2011Using 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{

Page 88: Quiz

if(t->left)Enqueue(q,t->left);if(t->right)Enqueue(q,t->right);}}}}Lokesh on March 31, 2011Good Solution :)Implement Stack using Queues?10 

Tags: Microsoft » Data Structures  » Software Engineer / DeveloperQuestion #6234846 (Report Dup) | Edit | History

sekhar740 on November 29, 2010use 2 queues for stack pop operation..jiangok on November 30, 2010one queue is enough.Reply to CommentAnonymous on November 29, 2010#include <iostream>#include <stdio.h>#define max 5using 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;

Page 89: Quiz

}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();

Page 90: Quiz

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 CommentAnkit Garg on December 04, 20101. Declare 2 Queues2. Start inserting in Q1 till a pop is required3. Transfer the contents of Q1 into Q2 except the last entry and pop it out4. 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 CommentDan on January 02, 2011I 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, 2011I think it will be 2 queue.where will you keep n-1 element?SH on February 07, 2011Good one !! U r pushing them back in the same queue..Anonymous on June 26, 2011Here you are assuming queue is implemented using array. What if its implemented by linkedList.Reply to CommentSH on February 07, 2011Can we just use a double ended queue ?Reply to Comment

Page 91: Quiz

[email protected] on June 26, 2011package 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 list4   

Page 92: Quiz

[Full Interview Report]

Tags: Amazon » Data Structures  » Software Engineer / DeveloperQuestion #6100711 (Report Dup) | Edit | History

blueskin.neo on November 18, 2010are you looking for a deque? double ended queue? or an array list?Reply to CommentAnonymous on November 22, 2010queue always has 2 ends !!!GP on November 23, 2010one of the questions was to insert to the front, the other was to insert at rear... they are two diff questionsReply to CommentPiyush on February 23, 2011Keep 2 pointer front,rear.1) INSERTIONif insertion of new node say "newNode" at rear thenrear->next=newNode;rear=newNode;else if insertion is at front thennewNode->next=front;front=newNode;2) DISPLAY/DELETEsimilar as display/delete of linklistReply to Comment

 Add a Text Comment | Add Runnable CodeName:

Comment:

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

Chat window too small? Open in new window. Connect via gchat. Access history. 

How to Get Better Chat Responses - READ THIS FIRST | Disable Chat.

Ask for Help Email me w hen new comments are posted

Submit

Page 93: Quiz

Follow CareerCup on TwitterFollow 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 / DeveloperQuestion #5465881 (Report Dup) | Edit | History

chennavarri on November 11, 2010Hash 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 structureSo 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. ThanksGabriel on November 18, 2010Depending on the hash function hash tables can have a constant time complexity for insertion.Reply to Commentadhi on March 16, 2011Algorithm :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 treesSorting:No in hashes Yes in TreeRange 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.

Page 94: Quiz

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, 2010you could do it with a hashtable.Reply to Commentgao on October 27, 2010i think if extra space is acceptable. use hashset. O(n)Reply to CommentAnonymous on October 31, 2010use a xor process on all the datasachin323 on October 31, 2010How does XOR solution fit to this , can explain ?Reply to CommentAnonymous on November 01, 2010he cannot explain, because he doesnt know eitherAnonymous on November 17, 2010if you xor the same numbers you will get a zero.Anonymous on December 01, 2010seriously? thats your answer?Reply to CommentAnonymous on December 03, 2010only 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 fineReply to Commentaggarwal.richa on January 08, 2011Do it with hash table.Reply to Commentkk on March 28, 2011public 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);

Page 95: Quiz

}n = n.next;}return h.ToList<Node>();

}Reply to Commentkamleshlu2009 on June 15, 2011@to the people suggesting for hash tablerange is not given how much big table will u take foe eg list conatains1 2 3 4 2 5 6 5 7 8 10000 u will need an array of 1000 sizekamleshlu2009 on June 15, 2011sorry 10000 sizeReply to CommentAshish Kaila on June 20, 2011You 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 [email protected] on June 26, 2011package 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();

Page 96: Quiz

LinkedListNodeInt node=new LinkedListNodeInt();node.insert(1);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();

}}Reply to CommentFind the width of a tree pointed by head35 

Tags: Amazon » Algorithm C Data Structures  » Software Engineer / DeveloperQuestion #4529943 (Report Dup) | Edit | History

Anonymous on October 25, 2010bfs level-wise traverseAnonymous on October 25, 2010not 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 nodesWe need to find width of tree not the number of leaf nodes.....Noname on October 25, 2010I 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,AB CE G HWe 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 CommentKS on October 25, 2010

void get_min_max_offset( const Node * root, int offset, int & min, int & max ){ if( root == 0 )

Page 97: Quiz

{ 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 CommentAnonymous on October 26, 2010A 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, 2010Not necessarily on one level.Reply to CommentAnonymous on October 26, 2010

int left, right;

Page 98: Quiz

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, 2010wat is the return value?????/Reply to CommentNo name on October 26, 2010what would be the initial value for iAnonymous on November 16, 2010what is the return value????????Reply to Commentandy on October 26, 2010

findWidth(Node root){ if(numChild(root) <= 1) /*numChild(root) returns # of children*/ return 1; width = 0;

Page 99: Quiz

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, 2010Is this correct?Reply to CommentAnonymous on October 26, 2010Can we proceed with finding the height of a tree.PLZ let me know.Reply to CommentVladimirMee on October 26, 2010No, 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 Commentvinaysachdeva23 on October 26, 2010The width of the trees number of columns you can find in the tree... for example:AB CD E Fhas width = 5 where first column has D second has B third has A and E, forth has C and fifth has FHope someone can solve this questionReply to CommentVladimirMee on October 26, 2010vinaysachdeva23, please, can you give the source (book or prooflink or article) of definition of width you gave? I couldn`t findReply to CommentAnonymous 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;

Page 100: Quiz

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 Commentxenon on October 27, 2010the 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 Commentvinaysachdeva23 on October 27, 2010The 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 CommentVladimirMee on October 27, 2010

Page 101: Quiz

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, 2010yes 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 3Important 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, 2010yes 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 3Important 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, 2010yes 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 3Important 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, 2010sorry 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 15Anonymous on October 28, 2010What if the nodes are in middle of the tree for ex:

A B C D E F G H I J

Page 102: Quiz

and 

A B C DReply to CommentVladimirMee on October 27, 2010

, your examples made it all clear to me, now i get it) appreciate your help, thanks)окReply to CommentAnonymous on October 30, 2010http: en.wikipedia.org wiki Tree_decompositionReply to CommentPKT on November 17, 2010AB CDE FG H I Ji think the max width is '4' b/w g and cReply to CommentKetz on November 20, 2010

public Integer width(){

LinkedList<Node1> queue = new LinkedList<Node1>();//for level operationsArrayList<Integer> level = new ArrayList<Integer>();//list of counts at each levelint levelCount = 0;//count at each levelif(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())

Page 103: Quiz

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

return Max;}

Reply to Commenthi on January 09, 2011i 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;elsereturn r+1;}Reply to CommentHI on January 09, 2011sry it wont work for some cases pls go forward using my code.....Reply to CommentNewbie on January 10, 2011width(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;}

Page 104: Quiz

rightwidth(Node N,count){if(n!=null){count++;n=n->right;}}Reply to CommentNewbie on January 10, 2011let me know if anything is wrong..Reply to CommentNifty on January 16, 2011Considering 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, level-

1);totalNodesAtLevel = LWidth+RWidth;

}return totalNodesAtLevel;

}

Page 105: Quiz

Reply to CommentSH on February 05, 2011www cs duke edu/courses/spring00/cps100/assign/trees/diameter htmlreplace " " 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 / DeveloperQuestion #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{

Page 106: Quiz

_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, 2010Great!!

Page 107: Quiz

Reply to Commentandy on October 26, 2010Can 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 CommentAdi on November 15, 2010Can you please give the Corresponding C or C++ code for this ?Reply to CommentAnonymous on November 26, 2010hiReply to Commentadhi on March 16, 2011struct 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

Page 108: Quiz

Question #4399683 (Report Dup) | Edit | History

Aditya on October 20, 2010I think we will need two stacks to implement queue :- stack has operations top(),empty(),pop(),add()lets take two stacks s1 and s2keep 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, 2011Dequeue 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 Commentanonymous on November 07, 2010we 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!

Page 109: Quiz

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

Tags: Google » Data Structures  » Software Engineer / DeveloperQuestion #4344046 (Report Dup) | Edit | History

sushant on October 17, 2010Sort the doubly link list... u will get BST...Anonymous on October 18, 2010That wont be in-place.rath.swaroop on October 18, 2010There are inplace sorting algorithmsrath.swaroop on October 18, 2010There are inplace sorting algorithmsReply to CommentAnonymous on October 17, 2010You mean when you have a list like 1<->2<->3<->4you can also consider it as a BST, where the root is one and each node only has a right child?Aditya on November 15, 2010After 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 Commentsushantmax88 on October 18, 2010nope.. i mean, when you have list of 1,2,3,4,5,6,7,8,9your 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 CommentAnonymous on October 18, 2010but first elements in the list need to be sortedReply to CommentAnonymous on October 18, 2010sort the list will make it a BST.

Page 110: Quiz

Reply to Commentczpete on October 21, 2010What 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 interviewsAnonymous 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 CommentAnonymous on November 11, 2010Example: 7,6,8,4,2,9,5Considering 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 pivot2. 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 pivot4. 4,2,5,6 Then 6 is the root and 4,2,5 are the left, no right child5. 4,2,5 Choose 4 as the root, and as pivot6. 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 pivot8. 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, 2010how can you apply quick sort on a DL list? it is not an array..Reply to CommentAnonymous on January 16, 2011cur_tree=nullcur_node=listnext_node=list->nextwhile(next_node){cur_node->previous-=nullcur_node->next=nullinsert_tree(root,cur_node)cur_node=nextnodenext_node=nextnode->next}

Page 111: Quiz

Reply to CommentJin 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

Page 112: Quiz

Question #4280049 (Report Dup) | Edit | History

ibnipun10 on October 17, 2010Take 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 treeTulley on October 17, 2010Single traversal wont workReply to CommentTulley on October 17, 2010We 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, 2010Sorry 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);

Page 113: Quiz

. }

. 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, 2010it is wrong....Asfdf on November 14, 2010Excellent !!Asfdf on November 14, 2010Excellent !!Reply to CommentannonD on October 21, 2010How do you convert following head to BST w/o changing structure?11 1Reply to Commentswk on October 22, 2010lyle.smu.edu/~saad/courses/cse3358/ps7/problemset7sol.pdfproblem 4 (b)Reply to Commentjhr on November 13, 2010at 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 CommentAnonymous on December 04, 2010@tulleythe code is not working as expected for the following minheap

1 | 2 3 | 4 5 6 11 | 12 21Reply to Commentvvvvv on December 24, 2010Convert( Node){if(Node!=null){Convert(Node->left)Convert(Node->right)Fix(Node)}}Fix(Node)

Page 114: Quiz

{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 theorem,T(N) = O(N)Anonymous on April 20, 2011Algo is correct, but complexity is nlognReply to Commentamshali on January 10, 2011We 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 CommentConvert a BST to max heap without using extra memory and in as optimum time as possible6 

Tags: Google » Data Structures  » Software Engineer / DeveloperQuestion #4281027 (Report Dup) | Edit | History

Tulley on October 17, 2010Do it same as Menaheap to BST. Will that not work? Please comment.Reply to CommentgradStudent on October 17, 2010Pseudo 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){

Page 115: Quiz

if(RootRight==NULL)return Root;elseSwap the Root and RootRight Node;return RootRight;}Plz comment if I have made any mistakedumdum on January 24, 2011you dont have to swap the nodes, swap the data. That would be neat.Reply to CommentAnonymous on October 18, 2010How about this approach?O(n) to convert BST to sorted LL, and O(n) to convert sorted LL to heapnode* 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 ListBST2LL(root);//step 2. LL to heapnode* 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 mistakeReply to Commentamshali on January 10, 2011How 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, 2011We also need to inverse the array at the end! O(n)This was only technical question my interviewer was asking to every candidate he interviewedWhat kind of questions u will ask to me if u have to design a Queue for me ?

Page 116: Quiz

i answered as 1) for data type u want it he said int2) It is going to contain very large numbers of objects he said no3)do u want to dynamically expanding he said no , lets keep it simple4)do want functionality of accessing any element in queue like At() function interviewer : yes5)Do u want min and max element functions interviewer : yesAfter 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 Databasethen 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 onlyi 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 candidates5   

mplement three stacks in single array7 

Tags: Google » Data StructuresQuestion #4240706 (Report Dup) | Edit | History

Metta on October 09, 2010Each 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,- PushFind 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.- PopGo 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, 2010without 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.

Page 117: Quiz

Reply to CommentS on October 10, 2010Classic 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, 2010What 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, 2010Let'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*NB: 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 CommentSam 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?ThanksReply to Commentpankaj4u4m on November 20, 2010we can create any number of stack in arrayfor each we maintain two index push index and pop indexcreate array with following field: just a sudo code

struct arr{

Page 118: Quiz

data // value which we want to store in stacklink to previous //index of previous};

g //1 global indexp1, p2, p3 // index of last push // initialize -1r1, r2, r3 // index of last pop // initialize all 0

///---------push--------------/////////////////////push( n ) // n is stack number in which i want to insert datav1 , v2, v3 = &sort(r1, r2, r3); //reference of sorted indexesassign the data value = dataassign 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 npop index of n = push index of npush index of n = link to previous at push index of nreturn 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 StructuresQuestion #4180708 (Report Dup) | Edit | History

Mahesh on October 09, 2010Start 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, 2010Nice :-)Reply to Comment

Page 119: Quiz

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;

Page 120: Quiz

return arr[top1--];}int pop_2(){

if(top2 == size - 1) return -1;

return arr[top1++];}

};

czpete on October 11, 2010Dude, 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 0ortop1=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 CommentCodeTillYouFaint on October 17, 2010I guess top1 must be initialised to -1 and top2 to size. And Stack will be full when top1+1 == top2 or top2-1 == top1Given 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  » InternQuestion #3955901 (Report Dup) | Edit | History

veb on October 17, 2010We 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); 

Page 121: Quiz

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 StructuresQuestion #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 10bool 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];

Page 122: Quiz

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, 2010Can you please explain the logic and the time complexity your algorithm takes?Reply to Comment

Page 123: Quiz

Anonymous on September 24, 2010If 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, 2010Not necessary.Reply to Commentxyz on September 25, 2010The 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 CommentRaj on September 27, 2010I 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 Commentbilla on October 10, 2010i think we need to exclude the current node data.. tht will differentiate the answer..Reply to Comment

 Add a Text Comment | Add Runnable CodeName:

Comment:

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

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 TwitterFollow 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, LinkLists3 

Ask for Help Email me w hen new comments are posted

Submit

Page 124: Quiz

Tags: Microsoft » Data Structures  » Software Engineer in TestQuestion #3787052 (Report Dup) | Edit | History

SB on September 09, 2010I thinkHashtables : array of objectsDictionary : 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, 2010I 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 Commentramu kumar on Septembeou 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->523   [Full Interview Report]

Tags: Microsoft » Data StructuresQuestion #3537658 (Report Dup) | Edit | History

anton1172 on August 24, 2010public 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; }}

Page 125: Quiz

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 CommentSachinGuptaMNNIT on August 24, 2010

Page 126: Quiz

/* 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;}

Page 127: Quiz

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");

Page 128: Quiz

display();}/*End of main()*/Reply to CommentSachinGuptaMNNIT on August 24, 2010/*Sachin Gupta MNNIT_ALDabove code is for1>reverse a linklist2.revese a linklist using one pointer3.Swap every consecutive two elements without using value stored in the node of linkedlistReply to CommentSachinGuptaMNNIT on August 24, 2010/*Swap every consecutive two elements without using value stored in the node of linkedlistuse*/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, 2010I ran this code ..It works perfectlyReply to CommentJust A guy on August 24, 2010@SachinHave u even tried running ur code on ur machine ?It will not do what it is supposed to do and u will evenlose data from the list.and ur first code is not using single pointer to reverse listyou are taking O(n) space too bcoz of the stack overhead of the RECURSIVE call.Have u written the code urself or ... ? :PSachinGuptaMNNIT 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;

Page 129: Quiz

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;

Page 130: Quiz

}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 Commentanother guy on August 24, 2010if you post pseudo code it will be a lot more helpful to understandbtwnice codeAnonymous on August 24, 2010I agree 100%..Reply to CommentAnonymous on August 25, 2010p=head,q=head->nextwhile(p->next){temp=q->nextq->next=pp->next=tempif(p->next)p=p->nextif(p->next)q=q->next}Reply to CommentAnonymous on August 25, 2010sorry little mistake in abpve code p=head,q=head->nextwhile(p->next){temp=q->nextq->next=pp->next=tempif(p->next)p=p->nextif(p->next)q=p->next}coder on August 26, 2010i dont think we need three pointers two will sufficecode

Page 131: Quiz

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, 2010sorry a small mistake in the last line p2 = p1->nextHappy on August 26, 2010u 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 CommentGirish 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;

Page 132: Quiz

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 ){

head = curr; prev = curr;

}else{

prev->next = curr; prev = curr;

}}return head;

}

void PrintLinkedList(NODE* head){

printf("Linked List is -->\n"); while(head){

printf("[%d] ", head->val); head = head->next;

}printf("\n");

}

Page 133: Quiz

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 )*head = second;

elseprev->next = second;

prev = first;

first = third; if( first )

second = first->next; }

}

Reply to CommentSachinGuptaMNNIT 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;

Page 134: Quiz

return temp;}Reply to Commentmandeepg on August 25, 2010Here'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, 2010Good One, ThanksReply to CommentAnkush Bindlish on September 03, 2010Please 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)){

Page 135: Quiz

q = p->next; p->next = q->next; p = p->next; }return head;}Reply to Commentramu kumar on September 07, 2010p=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 CommentAseem on October 01, 2010// We can have a recursive functionswap(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 CommentAnonymous on November 27, 2010swap(Node node){if(node == null) returnprev = null;while(node != null){next = node.next.nextnode.next.next = node

Page 136: Quiz

node.next = nextprev = nodenode = next}if(prev != null){temp = nodenode = node.nextnode.next = temp}}Reply to CommentAnonymous on November 27, 2010swap(Node node){if(node == null) returnprev = null;while(node != null){next = node.next.nextnode.next.next = nodenode.next = nextprev = nodenode = next}if(prev.next != null){temp = nodenode = node.nextnode.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 TestQuestion #3491945 (Report Dup) | Edit | History

S on August 12, 2010My first idea:1. complete the rest of the tree with dummy nodes until it's a complete binary tree.

Page 137: Quiz

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, 2010My 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 CommentFrodo 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 null2. or gparent->left=root or gparent->right=rootso , 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, 2010We 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, 2010Frodo, great solution.spgokul on August 25, 2010thank you for your solution frodo :)Reply to CommentFrodo 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);

Page 138: Quiz

}call postorder(root,null,null)ibnipun10 on August 13, 2010Parent will always be null hereibnipun10 on August 13, 2010I am sorry, you are right....:)santhosh on August 17, 2010gud workcoder on September 18, 2010awesome!!Ricardo Neto on November 12, 2010Good and clean solution!Anonymous on November 20, 2010superb!!!Reply to Commentharsh1690 on August 13, 2010void 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, 2010Nice one !!Reply to Commentharsh1690 on August 13, 2010void 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);}}}...

Page 139: Quiz

main(){ root->gpearent=NULL;assign_gp(root, NULL);}Reply to Commenttry on August 21, 2010void 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 CommentVenky on August 27, 2010public 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, 2010Node structure does not have Parent field.Reply to CommentO(?) on September 07, 2010I think if we have both parent and grandparent in the node implementation then it will quite easy implementation.Reply to CommentSameh.S.Hegazy on September 11, 2010Here 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)

Page 140: Quiz

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, 2010I 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, 2010Yes , right no need for the extra code ,thanks for updating me :)Paul on October 03, 2010how to make initial call with only those five lines.Sameh.S.Hegazy on October 03, 2010i 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 generatedReply to CommentAnonymous on September 12, 2010main(){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 nodeassigngrandparent(node->right,node);// if there is a right child for node}CHECK FOR NULL on September 21, 2010No checks whether n->left or n->right is null. BIG MISTAKECheck for gpn is useless.Reply to CommentPrashant on September 15, 2010

Page 141: Quiz

Hi, Simplest approach...Push(root)while(isempty() == FALSE){node = pop();if(node != NULL){if (node->left != NULL){node->left->garandparent = node;push(node->left)}elsepush (NULL);if (node->right != NULL){node->right->garandparent = node;push(node->right);}elsepush (NULL); }}And there u go dude...Where to go dude on September 21, 2010U are only assigning the parents to the nodes.At least check your solutions before putting here.Reply to Commenti.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

Page 142: Quiz

Vinay on October 31, 2010Simplest 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 CommentMi 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); }

Page 143: Quiz

} }

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); } }