Algorithms and Programming
1. 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 ?
2. You’re given an array containing both positive and negative integers and required to find the sub-array with the largest sum (O(N) a la KBL). Write a routine in C for the above.
3. Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like. [ I ended up giving about 4 or 5 different solutions for this, each supposedly better than the others ].
4. Write a routine to draw a circle (x ** 2 + y ** 2 = r ** 2) without making use of any floating point computations at all. [ This one had me stuck for quite some time and I first gave a solution that did have floating point computations ].
5. Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal. [ I gave the obvious solution of taking % 10 and / 10, which gives us the decimal value in reverse order. This requires an array since we need to print it out in the correct order. The interviewer wasn’t too pleased and asked me to give a solution which didn’t need the array ].
6. Give a one-line C expression to test whether a number is a power of 2. [No loops allowed – it’s a simple test.]
7. 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.
8. How 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.
9. Give a very good method to count the number of ones in a “n” (e.g. 32) bit number.
ANS. Given below are simple solutions, find a solution that does it in log (n) steps.
Some sample Questions-Previously asked
In a X’s and 0′s game (i.e. TIC TAC TOE) if you write a program for this give a fast way to generate the moves by the computer. I mean this should be the fastest way possible.
ANS:- The answer is that you need to store all possible configurations of the board and the move that is associated with that. Then it boils down to just accessing the right element and getting the corresponding move for it. Do some analysis and do some more optimization in storage since otherwise it becomes infeasible to get the required storage in a DOS machine.
I was given two lines of assembly code which found the absolute value of a number stored in two’s complement form. I had to recognize what the code was doing. Pretty simple if you know some assembly and some fundas on number representation.
3 Give a fast way to multiply a number by 7.
4. How would go about finding out where to find a book in a library. (You don’t know how exactly the books are organized beforehand).
5. Linked list manipulation.
6. Tradeoff between time spent in testing a product and getting into the market first.
7. What to test for given that there isn’t enough time to test everything you want to.
8. First some definitions for this problem: a) An ASCII character is one byte long and the most significant bit in the byte is always ’0′. b) A Kanji character is two bytes long. The only characteristic of a Kanji character is that in its first byte the most significant bit is ’1′. Now you are given an array of a characters (both ASCII and Kanji) and, an index into the array. The index points to the start of some character. Now you need to write a function to do a backspace (i.e. delete the character before the given index).
9. Give a one-line C expression to test whether a number is a power of 2. [No loops allowed – it’s a simple test.
10. 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.
11. Given an array of integers, find the contiguous sub-array with the largest sum.
ANS. Can be done in O(n) time and O(1) extra space. Scan array from 1 to n. Remember the best sub-array seen so far and the best sub-array ending in i.
12. Given an array of length N containing integers between 1 and N, determine if it contains any duplicates.
ANS. [Is there an O(n) time solution that uses only O(1) extra space and does not destroy the original array?]
13. Sort an array of size n containing integers between 1 and K, given a temporary scratch integer array of size K.
ANS. Compute cumulative counts of integers in the auxiliary array. Now scan the original array, rotating cycles! [Can someone word this more nicely?]
14. C++ ( what is virtual function ? what happens if an error occurs in constructor or destructor. Discussion on error handling, templates, unique features of C++. What is different in C++, ( compare with Unix).
15. Given a list of numbers ( fixed list) Now 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 (fixed list).
16. I was a c++ code and was asked to find out the bug in that. The bug was that he declared an object locally in a function and tried to return the pointer to that object. Since the object is local to the function, it no more exists after returning from the function. The pointer, therefore, is invalid outside.
17. A real life problem – A square picture is cut into 16 squares and they are shuffled. Write a program to rearrange the 16 squares to get the original big square.
.
int *a;
char *c;
*(a) = 20;
*c = *a;
printf(“%c”,*c);
18what is the output?
19 Write a program to find whether a given m/c is big-endian or little-endian!
20 What is a volatile variable?
21 What is the scope of a static function in C ?
22. What is the difference between “malloc” and “calloc”?
23. struct n { int data; struct n* next}node;
node *c,*t;
c->data = 10;
t->next = null;
*c = *t;
what is the effect of the last statement?
24. If you’re familiar with the ? operator x ? y : z
you want to implement that in a function: int cond(int x, int y, int z); using only ~, !, ^, &, +, |, <<, >> no if statements, or loops or anything else, just those operators, and the function should correctly return y or z based on the value of x. You may use constants, but only 8 bit constants. You can cast all you want. You’re not supposed to use extra variables, but in the end, it won’t really matter, using variables just makes things cleaner. You should be able to reduce your solution to a single line in the end though that requires no extra vars.
25 You have an abstract computer, so just forget everything you know about computers, this one only does what I’m about to tell you it does. You can use as many variables as you need, there are no negative numbers, all numbers are integers. You do not know the size of the integers, they could be infinitely large, so you can’t count on truncating at any point. There are NO comparisons allowed, no if statements or anything like that. There are only four operations you can do on a variable.
1) You can set a variable to 0.
2) You can set a variable = another variable.
3) You can increment a variable (only by 1), and it’s a post increment.
26) You can loop. So, if you were to say loop(v1) and v1 = 10, your loop would execute 10 times, but the value in v1 wouldn’t change so the first line in the loop can change value of v1 without changing the number of times you loop.
You need to do 3 things.
1) Write a function that decrements by 1.
2) Write a function that subtracts one variable from another.
3) Write a function that divides one variable by another.
4) See if you can implement all 3 using at most 4 variables. Meaning, you’re not making function calls now, you’re making macros. And at most you can have 4 variables. The restriction really only applies to divide, the other 2 are easy to do with 4 vars or less. Division on the other hand is dependent on the other 2 functions, so, if subtract requires 3 variables, then divide only has 1 variable left unchanged after a call to subtract. Basically, just 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.
Linked lists
27. Under what circumstances can one delete an element from a singly linked list in constant time?
ANS. If the list is circular and there are no references to the nodes in the list from anywhere else! Just copy the contents of the next node and delete the next node. If the list is not circular, we can delete any but the last node using this idea. In that case, mark the last node as dummy!
28. Given a singly linked list, determine whether it contains a loop or not.
ANS. (a) Start reversing the list. If you reach the head, gotcha! there is a loop! But this changes the list. So, reverse the list again.
(b) Maintain two pointers, initially pointing to the head. Advance one of them one node at a time. And the other one, two nodes at a time. If the latter overtakes the former at any time, there is a loop!
p1 = p2 = head;
do {
p1 = p1->next;
p2 = p2->next->next;
} while (p1 != p2);
29. Given a singly linked list, print out its contents in reverse order. Can you do it without using any extra space?
ANS. Start reversing the list. Do this again, printing the contents.
30 Given a binary tree with nodes, print out the values in pre-order/in-order/post-order without using any extra space.
31 Reverse a singly linked list recursively. The function prototype is node * reverse (node *) ;
node * reverse (node * n)
{
node * m ;
if (! (n && n -> next))
return n ;
m = reverse (n -> next) ;
n -> next -> next = n ;
n -> next = NULL ;
return m ;
}
32. Given a singly linked list, find the middle of the list.
HINT. Use the single and double pointer jumping. Maintain two pointers, initially pointing to the head. Advance one of them one node at a time. And the other one, two nodes at a time. When the double reaches the end, the single is in the middle. This is not asymptotically faster but seems to take less steps than going through the list twice.
33. Reverse the bits of an unsigned integer.
#define reverse(x) \
(x=x>>16|(0x0000ffff&x)<<16, \
x=(0xff00ff00&x)>>8|(0x00ff00ff&x)<<8, \
x=(0xf0f0f0f0&x)>>4|(0x0f0f0f0f&x)<<4, \
x=(0xcccccccc&x)>>2|(0×33333333&x)<<2, \
x=(0xaaaaaaaa&x)>>1|(0×55555555&x)<<1)
34. Compute the number of ones in an unsigned integer.
#define count_ones(x) \
(x=(0xaaaaaaaa&x)>>1+(0×55555555&x), \
x=(0xcccccccc&x)>>2+(0×33333333&x), \
x=(0xf0f0f0f0&x)>>4+(0x0f0f0f0f&x), \
x=(0xff00ff00&x)>>8+(0x00ff00ff&x), \
x=x>>16+(0x0000ffff&x))
35. Compute the discrete log of an unsigned integer.
ANS.
#define discrete_log(h) \
(h=(h>>1)|(h>>2), \
h|=(h>>2), \
h|=(h>>4), \
h|=(h>>8), \
h|=(h>>16), \
h=(0xaaaaaaaa&h)>>1+(0×55555555&h), \
h=(0xcccccccc&h)>>2+(0×33333333&h), \
h=(0xf0f0f0f0&h)>>4+(0x0f0f0f0f&h), \
h=(0xff00ff00&h)>>8+(0x00ff00ff&h), \
h=(h>>16)+(0x0000ffff&h))
If I understand it right, log2(2) =1, log2(3)=1, log2(4)=2….. But this macro does not work out log2(0) which does not exist! How do you think it should be handled?
36. How do we test most simply if an unsigned integer is a power of two?
ANS. #define power_of_two(x) \ ((x)&&(~(x&(x-1))))
37. Set the highest significant bit of an unsigned integer to zero.
ANS. (from Denis Zabavchik) Set the highest significant bit of an unsigned integer to zero
#define zero_most_significant(h) \
(h&=(h>>1)|(h>>2), \
h|=(h>>2), \
h|=(h>>4), \
h|=(h>>8), \
h|=(h>>16))
38. Let f(k) = 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(0) = 1, f(1) = 1, f(2) = 2, f(3) = 1, f(4) = 3, f(5) = 2, f(6) = 3 and so on. Given k >= 0, compute f(k).
39. A character set has 1 and 2 byte characters. One byte characters have 0 as the first bit. You just keep accumulating the characters in a buffer. Suppose at some point the user types a backspace, how can you remove the character efficiently. (Note: You cant store the last character typed because the user can type in arbitrarily many backspaces)
40. What is the simples way to check if the sum of two unsigned integers has resulted in an overflow.
24. How do you represent an n-ary tree? Write a program to print the nodes of such a tree in breadth first order.
41. Write the ‘tr’ program of UNIX. Invoked as tr -str1 -str2. It reads stdin and prints it out to stdout, replacing every occurance of str1 with str2.
e.g. tr -abc -xyz
to be and not to be <- input
to ye xnd not to ye <- outpu