Question: How could you determine if a linked list contains a cycle in it, and, at what
node the cycle starts?
Answer: There are a number of approaches. The approach I shared is in time N (where N is the number of nodes in your linked list). Assume that the node definition contains a boolean fla, bVisited. struct Node { ... bool bVisited; }; Then, to determine whether a node has a loop, you could first set this fla to false for all of the nodes! // Detect cycle // Note: pHead points to the head of the list (assume already exists Node !p"urrent # pHead; $hile (p"urrent { p"urrent%&bVisited # false; p"urrent # p"urrent%&pNext; } Then, to determine whether or not a cycle e"isted, loop throuh each node. After #isitin a node, set bVisited to true. $hen you first #isit a node, check to see if the node has already been #isited (i.e., test bVisited ## true). If it has, you%#e hit the start of the cycle& bool b"ycle # false; p"urrent # pHead; $hile (p"urrent '' (p"ycle { if (p"urrent%&bVisited ## true // cycle( p"ycle # true; else { p"urrent%&bVisited # true; p"urrent # p"urrent%&pNext; } } A much better approach was submitted by '(uys #isitor (eore )., a *icrosoft inter#iewer+employee. He recommended usin the followin techni,ue, which is in time -(N) and space -(.). /se two pointers. // error checking and checking for NULL at end of list omitted p) # p* # head; do { p) # p)%&next; p* # p*%&next%&next; } $hile (p) (# p*; p* is mo#in throuh the list twice as fast as p). If the list is circular, (i.e. a cycle e"ists) it will e#entually et around to that sluard, p). Thanks (eore& Question: How would you re#erse a doubly0linked list? Answer: This problem isn%t too hard. 1ou 2ust need to start at the head of the list, and iterate to the end. At each node, swap the #alues of pNext and p+re,. 3inally, set pHead to the last node in the list. Node ! p"urrent # pHead- !p.emp; $hile (p"urrent { p.emp # p"urrent%&pNext; p"urrent%&pNext # p"urrent%&p+re,; p"urrent%&p+re, # temp;
pHead # p"urrent; p"urrent # temp; } Question: Assume you ha#e an array that contains a number of strins (perhaps char ! a/)001). 4ach strin is a word from the dictionary. 1our task, described in hih0le#el terms, is to de#ise a way to determine and display all of the anarams within the array (two words are anarams if they contain the same characters5 for e"ample, tales and slate are anarams.) Answer: 6ein by sortin each element in the array in alphabetical order. 7o, if one element of your array was slate, it would be rearraned to form aelst (use some mechanism to know that the particular instance of aelst maps to slate). At this point, you slate and tales would be identical! aelst. Ne"t, sort the entire array of these modified dictionary words. Now, all of the anarams are rouped toether. 3inally, step throuh the array and display duplicate terms, mappin the sorted letters (aelst) back to the word (slate or tales). Question: (i#en the followin prototype! int compact(int ! p- int si2e; write a function that will take a sorted array, possibly with duplicates, and compact the array, returnin the new lenth of the array. That is, if p points to an array containin! )- 3- 4- 4- 5- 6- 6- 6- )0, when the function returns, the contents of p should be! )- 3- 4- 5- 6- )0, with a lenth of 8 returned. Answer: A sinle loop will accomplish this. int compact(int ! p- int si2e { int current- insert # ); for (current#); current 7 si2e; current88 if (p/current1 (# p/insert%)1 { p/insert1 # p/current1; current88; insert88; } else current88; } Question:I was asked to write a piece of code to take a 9 diit phone number, and enerate all possible combinations of the letters in their 9 places. Imaine a slots machine with 9 spinners. The problem is to write out all the possible slots combinations you could arri#e at by pullin the le#el and spinnin each diit. (Aside! I was tempted to write this as a random problem, and draw a random set of diits until I had e"hausted the set space. I resisted.) Here:s simple code to sol#e this *icrosoft problem! ). public ,oid my"utie+ie(char[] in- int le,el){ *. if(le,el ## in.len9th){ 3. System.out.println(in); :. return; ;. } <. for(int i # 0; i7 in.len9th; i88){ 4. for(int = # 0; = 7 3; =88){ 5. char temp # in[i]; 6. in[i] # 9etNext>etter(temp- =); )0. my"utie+ie(in- le,el88); )). in[i] # temp; )*. } )3. } !" } .. Given a rectangular (cuboidal for the puritans) cake with a rectangular piece removed (any size or orientation), how would you cut the remainder of the cake into two equal halves with one straight cut of a knife ? . !ou"re given an array containing both positive and negative integers and required to find the sub#array with the largest sum ($(%) a la &'(). )rite a routine in * for the above. +. Given an array of size % in which every number is between , and %, determine if there are any duplicates in it. !ou are allowed to destroy the array if you like. - . ended up giving about / or 0 different solutions for this, each supposedly better than the others 1. /. )rite a routine to draw a circle (2 33 4 y 33 5 r 33 ) without making use of any floating point computations at all. - 6his one had me stuck for quite some time and . first gave a solution that did have floating point computations 1. 0. Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal. - . gave the obvious solution of taking 7 ,8 and 9 ,8, which gives us the decimal value in reverse order. 6his requires an array since we need to print it out in the correct order. 6he interviewer wasn"t too pleased and asked me to give a solution which didn"t need the array 1. :. Give a one#line * e2pression to test whether a number is a power of . -%o loops allowed # it"s a simple test.1 ;. Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it. <. =ow many points are there on the globe where by walking one mile south, one mile east and one mile north you reach the place where you started. >. Give a very good method to count the number of ones in a ?n? (e.g. +) bit number. @%A. Given below are simple solutions, find a solution that does it in log (n) steps. .terative function iterativecount (unsigned int n) begin int count58B while (n) begin count 45 n C 82, B n DD5 ,B end return countB end Aparse *ount function sparsecount (unsigned int n) begin int count58B while (n) begin count44B n C5 (n#,)B end return count B end ,8. )hat are the different ways to implement a condition where the value of 2 can be either a 8 or a ,. @pparently the if then else solution has a Eump when written out in assembly. if (2 55 8) y5a else y5b 6here is a logical, arithmetic and a data structure solution to the above problem. ,,. Feverse a linked list. ,. .nsert in a sorted list ,+. .n a G"s and 8"s game (i.e. 6.* 6@* 6$H) if you write a program for this give a fast way to generate the moves by the computer. . mean this should be the fastest way possible. 6he answer is that you need to store all possible configurations of the board and the move that is associated with that. 6hen it boils down to Eust accessing the right element and getting the corresponding move for it. Io some analysis and do some more optimization in storage since otherwise it becomes infeasible to get the required storage in a I$A machine. ,/. . was given two lines of assembly code which found the absolute value of a number stored in two"s complement form. . had to recognize what the code was doing. Jretty simple if you know some assembly and some fundaes on number representation. ,0. Give a fast way to multiply a number by ;. ,:. =ow would go about finding out where to find a book in a library. (!ou don"t know how e2actly the books are organized beforehand). ,;. (inked list manipulation. ,<. 6radeoff between time spent in testing a product and getting into the market first. ,>. )hat to test for given that there isn"t enough time to test everything you want to. 8. Kirst some definitions for this problemL a) @n @A*.. character is one byte long and the most significant bit in the byte is always "8". b) @ &anEi character is two bytes long. 6he only characteristic of a &anEi character is that in its first byte the most significant bit is ",". %ow you are given an array of a characters (both @A*.. and &anEi) and, an inde2 into the array. 6he inde2 points to the start of some character. %ow you need to write a function to do a backspace (i.e. delete the character before the given inde2). ,. Ielete an element from a doubly linked list. . )rite a function to find the depth of a binary tree. +. Given two strings A, and A. Ielete from A all those characters which occur in A, also and finally create a clean A with the relevant characters deleted. /. @ssuming that locks are the only reason due to which deadlocks can occur in a system. )hat would be a foolproof method of avoiding deadlocks in the system. 0. Feverse a linked list. @nsL Jossible answers # iterative loop curr#Dne2t 5 prevB prev 5 currB curr 5 ne2tB ne2t 5 curr#Dne2t endloop recursive reverse(ptr) if (ptr#Dne2t 55 %M(() return ptrB temp 5 reverse(ptr#Dne2t)B temp#Dne2t 5 ptrB return ptrB end :. )rite a small le2ical analyzer # interviewer gave tokens. e2pressions like ?a3b? etc. ;. 'esides communication cost, what is the other source of inefficiency in FJ*? (answer L conte2t switches, e2cessive buffer copying). =ow can you optimize the communication? (ans L communicate through shared memory on same machine, bypassing the kernel N @ Mniv. of )ash. thesis) <. )rite a routine that prints out a #I array in spiral orderO >. =ow is the readers#writers problem solved? # using semaphores9ada .. etc. +8. )ays of optimizing symbol table storage in compilers. +,. @ walk#through through the symbol table functions, lookup() implementation etc. # 6he interviewer was on the Picrosoft * team. +. @ version of the ?6here are three persons G ! Q, one of which always lies?.. etc.. ++. 6here are + ants at + corners of a triangle, they randomly start moving towards another corner.. what is the probability that they don"t collide. +/. )rite an efficient algorithm and * code to shuffle a pack of cards.. this one was a feedback process until we came up with one with no e2tra storage. +0. 6he if (2 55 8) y 5 8 etc.. +:. Aome more bitwise optimization at assembly level +;. Aome general questions on (e2, !acc etc. +<. Given an array t-,881 which contains numbers between ,..>>. Feturn the duplicated value. 6ry both $(n) and $(n#square). +>. Given an array of characters. =ow would you reverse it. ? =ow would you reverse it without using inde2ing in the array. /8. Given a sequence of characters. =ow will you convert the lower case characters to upper case characters. ( 6ry using bit vector # solutions given in the * lib #typec.h) /,. Kundamentals of FJ*. /. Given a linked list which is sorted. =ow will u insert in sorted way. /+. Given a linked list =ow will you reverse it. //. Give a good data structure for having n queues ( n not fi2ed) in a finite memory segment. !ou can have some data#structure separate for each queue. 6ry to use at least >87 of the memory space. /0. Io a breadth first traversal of a tree. /:. )rite code for reversing a linked list. /;. )rite, efficient code for e2tracting unique elements from a sorted list of array. e.g. (,, ,, +, +, +, 0, 0, 0, >, >, >, >) #D (,, +, 0, >). /<. Given an array of integers, find the contiguous sub#array with the largest sum. @%A. *an be done in $(n) time and $(,) e2tra space. Acan array from , to n. Femember the best sub#array seen so far and the best sub# array ending in i. />. Given an array of length % containing integers between , and %, determine if it contains any duplicates. @%A. -.s there an $(n) time solution that uses only $(,) e2tra space and does not destroy the original array?1 08. Aort an array of size n containing integers between , and &, given a temporary scratch integer array of size &. @%A. *ompute cumulative counts of integers in the au2iliary array. %ow scan the original array, rotating cyclesO -*an someone word this more nicely?1 3 0,. @n array of size k contains integers between , and n. !ou are given an additional scratch array of size n. *ompress the original array by removing duplicates in it. )hat if k RR n? @%A. *an be done in $(k) time i.e. without initializing the au2iliary arrayO 0. @n array of integers. 6he sum of the array is known not to overflow an integer. *ompute the sum. )hat if we know that integers are in "s complement form? @%A. .f numbers are in "s complement, an ordinary looking loop like for(i5total58BiR nBtotal45array-i441)B will do. %o need to check for overflowsO 0+. @n array of characters. Feverse the order of words in it. @%A. )rite a routine to reverse a character array. %ow call it for the given array and for each word in it. 3 0/. @n array of integers of size n. Generate a random permutation of the array, given a function randNn() that returns an integer between , and n, both inclusive, with equal probability. )hat is the e2pected time of your algorithm? @%A. ?H2pected time? should ring a bell. 6o compute a random permutation, use the standard algorithm of scanning array from n downto ,, swapping i#th element with a uniformly random element R5 i#th. 6o compute a uniformly random integer between , and k (k R n), call randNn() repeatedly until it returns a value in the desired range. 00. @n array of pointers to (very long) strings. Kind pointers to the (le2icographically) smallest and largest strings. @%A. Acan array in pairs. Femember largest#so#far and smallest#so#far. *ompare the larger of the two strings in the current pair with largest# so#far to update it. @nd the smaller of the current pair with the smallest#so#far to update it. Kor a total of R5 +n9 strcmp() calls. 6hat"s also the lower bound. 0:. )rite a program to remove duplicates from a sorted array. @%A. int removeNduplicates(int 3 p, int size) S int current, insert 5 ,B for (current5,B current R sizeB current44) if (p-current1 O5 p-insert#,1) S p-insert1 5 p-current1B current44B insert44B T else current44B return insertB T 0;. *44 ( what is virtual function ? what happens if an error occurs in constructor or destructor. Iiscussion on error handling, templates, unique features of *44. )hat is different in *44, ( compare with uni2). 0<. Given a list of numbers ( fi2ed list) %ow given any other list, how can you efficiently find out if there is any element in the second list that is an element of the first list (fi2ed list). 0>. Given + lines of assembly code L find it is doing. .6 was to find absolute value. :8. .f you are on a boat and you throw out a suitcase, )ill the level of water increase. :,. Jrint an integer using only putchar. 6ry doing it without using e2tra storage. :. )rite * code for (a) deleting an element from a linked list (b) traversing a linked list :+. )hat are various problems unique to distributed databases :/. Ieclare a void pointer @%A. void 3ptrB :0. Pake the pointer aligned to a / byte boundary in a efficient manner @%A. @ssign the pointer to a long number and the number with ,,...,,88 add / to the number ::. )hat is a far pointer (in I$A) :;. )hat is a balanced tree :<. Given a linked list with the following property node is left child of node,, if node R node, else, it is the right child. $ J U U $ @ U U $ ' U U $ * =ow do you convert the above linked list to the form without disturbing the property. )rite * code for that. $ J U U $ ' 9 V 9 V 9 V $ ? $ ? determine where do @ and * go :>. Iescribe the file system layout in the M%.G $A @%A. describe boot block, super block, inodes and data layout ;8. .n M%.G, are the files allocated contiguous blocks of data @%A. no, they might be fragmented =ow is the fragmented data kept track of @%A. Iescribe the direct blocks and indirect blocks in M%.G file system ;,. )rite an efficient * code for "tr" program. "tr" has two command line arguments. 6hey both are strings of same length. tr reads an input file, replaces each character in the first string with the corresponding character in the second string. eg. "tr abc 2yz" replaces all "a"s by "2"s, "b"s by "y"s and so on. @%A. a) have an array of length :. put "2" in array element corr to "a" put "y" in array element corr to "b" put "z" in array element corr to "c" put "d" in array element corr to "d" put "e" in array element corr to "e" and so on. the code while (Oeof) S c 5 getc()B putc(array-c # "a"1)B T ;. what is disk interleaving ;+. why is disk interleaving adopted ;/. given a new disk, how do you determine which interleaving is the best a) give ,888 read operations with each kind of interleaving determine the best interleaving from the statistics ;0. draw the graph with performance on one a2is and "n" on another, where "n" in the "n" in n#way disk interleaving. (a tricky question, should be answered carefully) ;:. . was a c44 code and was asked to find out the bug in that. 6he bug was that he declared an obEect locally in a function and tried to return the pointer to that obEect. Aince the obEect is local to the function, it no more e2ists after returning from the function. 6he pointer, therefore, is invalid outside. ;;. @ real life problem # @ square picture is cut into ,: squares and they are shuffled. )rite a program to rearrange the ,: squares to get the original big square. ;<. int 3aB char 3cB 3(a) 5 8B 3c 5 3aB printf(?7c?,3c)B what is the output? ;>. )rite a program to find whether a given m9c is big#endian or little# endianO <8. )hat is a volatile variable? <,. )hat is the scope of a static function in * ? <. )hat is the difference between ?malloc? and ?calloc?? <+. struct n S int dataB struct n3 ne2tTnodeB node 3c,3tB c#Ddata 5 ,8B t#Dne2t 5 nullB 3c 5 3tB what is the effect of the last statement? </. .f you"re familiar with the ? operator 2 ? y L z you want to implement that in a functionL int cond(int 2, int y, int z)B using only W, O, X, C, 4, U, RR, DD no if statements, or loops or anything else, Eust those operators, and the function should correctly return y or z based on the value of 2. !ou may use constants, but only < bit constants. !ou can cast all you want. !ou"re not supposed to use e2tra variables, but in the end, it won"t really matter, using vars Eust makes things cleaner. !ou should be able to reduce your solution to a single line in the end though that requires no e2tra vars. <0. !ou have an abstract computer, so Eust forget everything you know about computers, this one only does what ."m about to tell you it does. !ou can use as many variables as you need, there are no negative numbers, all numbers are integers. !ou do not know the size of the integers, they could be infinitely large, so you can"t count on truncating at any point. 6here are %$ comparisons allowed, no if statements or anything like that. 6here are only four operations you can do on a variable. ,) !ou can set a variable to 8. ) !ou can set a variable 5 another variable. +) !ou can increment a variable (only by ,), and it"s a post increment. /) !ou can loop. Ao, if you were to say loop(v,) and v, 5 ,8, your loop would e2ecute ,8 times, but the value in v, wouldn"t change so the first line in the loop can change value of v, without changing the number of times you loop. !ou need to do + things. ,) )rite a function that decrements by ,. ) )rite a function that subtracts one variable from another. +) )rite a function that divides one variable by another. /) Aee if you can implement all + using at most / variables. Peaning, you"re not making function calls now, you"re making macros. @nd at most you can have / variables. 6he restriction really only applies to divide, the other are easy to do with / vars or less. Iivision on the other hand is dependent on the other functions, so, if subtract requires + variables, then divide only has , variable left unchanged after a call to subtract. 'asically, Eust make your function calls to decrement and subtract so you pass your vars in by reference, and you can"t declare any new variables in a function, what you pass in is all it gets. (inked lists 3 <:. Mnder what circumstances can one delete an element from a singly linked list in constant time? @%A. .f the list is circular and there are no references to the nodes in the list from anywhere elseO Yust copy the contents of the ne2t node and delete the ne2t node. .f the list is not circular, we can delete any but the last node using this idea. .n that case, mark the last node as dummyO 3 <;. Given a singly linked list, determine whether it contains a loop or not. @%A. (a) Atart reversing the list. .f you reach the head, gotchaO there is a loopO 'ut this changes the list. Ao, reverse the list again. (b) Paintain two pointers, initially pointing to the head. @dvance one of them one node at a time. @nd the other one, two nodes at a time. .f the latter overtakes the former at any time, there is a loopO p, 5 p 5 headB do S p, 5 p,#Dne2tB p 5 p#Dne2t#Dne2tB T while (p, O5 p)B <<. Given a singly linked list, print out its contents in reverse order. *an you do it without using any e2tra space? @%A. Atart reversing the list. Io this again, printing the contents. <>. Given a binary tree with nodes, print out the values in pre# order9in#order9post#order without using any e2tra space. >8. Feverse a singly linked list recursively. 6he function prototype is node 3 reverse (node 3) B @%A. node 3 reverse (node 3 n) S node 3 m B if (O (n CC n #D ne2t)) return n B
m 5 reverse (n #D ne2t) B n #D ne2t #D ne2t 5 n B n #D ne2t 5 %M(( B return m B T >,. Given a singly linked list, find the middle of the list. =.%6. Mse the single and double pointer Eumping. Paintain two pointers, initially pointing to the head. @dvance one of them one node at a time. @nd the other one, two nodes at a time. )hen the double reaches the end, the single is in the middle. 6his is not asymptotically faster but seems to take less steps than going through the list twice. Bit-manipulation >. Feverse the bits of an unsigned integer. @%A. Zdefine reverse(2) V (252DD,:U(828888ffffC2)RR,:, V 25(82ff88ff88C2)DD<U(8288ff88ffC2)RR<, V 25(82f8f8f8f8C2)DD/U(828f8f8f8fC2)RR/, V 25(82ccccccccC2)DDU(82++++++++C2)RR, V 25(82aaaaaaaaC2)DD,U(8200000000C2)RR,) 3 >+. *ompute the number of ones in an unsigned integer. @%A. Zdefine countNones(2) V (25(82aaaaaaaaC2)DD,4(8200000000C2), V 25(82ccccccccC2)DD4(82++++++++C2), V 25(82f8f8f8f8C2)DD/4(828f8f8f8fC2), V 25(82ff88ff88C2)DD<4(8288ff88ffC2), V 252DD,:4(828888ffffC2)) >/. *ompute the discrete log of an unsigned integer. @%A. Zdefine discreteNlog(h) V (h5(hDD,)U(hDD), V hU5(hDD), V hU5(hDD/), V hU5(hDD<), V hU5(hDD,:), V h5(82aaaaaaaaCh)DD,4(8200000000Ch), V h5(82ccccccccCh)DD4(82++++++++Ch), V h5(82f8f8f8f8Ch)DD/4(828f8f8f8fCh), V h5(82ff88ff88Ch)DD<4(8288ff88ffCh), V h5(hDD,:)4(828888ffffCh)) .f . understand it right, log() 5,, log(+)5,, log(/)5..... 'ut this macro does not work out log(8) which does not e2istO =ow do you think it should be handled? 3 >0. =ow do we test most simply if an unsigned integer is a power of two? @%A. Zdefine powerNofNtwo(2) V ((2)CC(W(2C(2#,)))) >:. Aet the highest significant bit of an unsigned integer to zero. @%A. (from Ienis Qabavchik) Aet the highest significant bit of an unsigned integer to zero Zdefine zeroNmostNsignificant(h) V (hC5(hDD,)U(hDD), V hU5(hDD), V hU5(hDD/), V hU5(hDD<), V hU5(hDD,:)) >;. (et f(k) 5 y where k is the y#th number in the increasing sequence of non#negative integers with the same number of ones in its binary representation as y, e.g. f(8) 5 ,, f(,) 5 ,, f() 5 , f(+) 5 ,, f(/) 5 +, f(0) 5 , f(:) 5 + and so on. Given k D5 8, compute f(k). Others ><. @ character set has , and byte characters. $ne byte characters have 8 as the first bit. !ou Eust keep accumulating the characters in a buffer. Auppose at some point the user types a backspace, how can you remove the character efficiently. (%oteL !ou cant store the last character typed because the user can type in arbitrarily many backspaces) >>. )hat is the simples way to check if the sum of two unsigned integers has resulted in an overflow. ,88. =ow do you represent an n#ary tree? )rite a program to print the nodes of such a tree in breadth first order. ,8,. )rite the "tr" program of M%.G. .nvoked as tr #str, #str. .t reads stdin and prints it out to stdout, replacing every occurance of str,-i1 with str-i1. e.g. tr #abc #2yz to be and not to be R# input to ye 2nd not to ye R# output