Documente Academic
Documente Profesional
Documente Cultură
Rohit Birla
Rohit Birla
Page 1
Page 2
TABLE OF CONTENTS
KEY TO DESIGN YOUR CODE: ......................................................................................................................................... 2
WRITE AN ALGORITHM TO DETERMINE IF STRING HAS
UNIQUE CHARACTERS ..................................................................................................................................................... 7
WRITE A METHOD TO DECIDE IF TWO STRINGS ARE
ANAGRAMS OR NOT........................................................................................................................................................ 8
WRITE A METHOD TO REPLACE ALL SPACES IN A STRING
WITH %20........................................................................................................................................................................ 9
WRITE AN ALGORITHM SUCH THAT IF AN ELEMENT IN
AN MXN MATRIX IS 0, ITS ENTIRE ROW AND COLUMN
IS SET TO 0 ....................................................................................................................................................................... 10
WRITE CODE TO REMOVE DUPLICATES FROM AN
UNSORTED LINKED LIST ................................................................................................................................................ 11
FIND MINIMUM AND MAXIMUM OF TWO NUMBERS
WITHOUT USING IF-ELSE OR COMPARISON OPERATOR. ....................................................................................... 12
FIND NTH ELEMENT FROM LAST IN SINGLY LINK-LIST ............................................................................................ 13
DELETE A NODE IN SINGLY LINK LIST, WHEN YOU HAVE
ACCESS TO THAT NODE O NLY...................................................................................................................................... 14
SUM OF TWO NUMBERS, WHICH ARE REPRESENTED BY
LINKED LIST ..................................................................................................................................................................... 15
USE SINGLE ARRAY FO R 3 STACKS .............................................................................................................................. 16
GIVEN A CIRCULAR LINKED LIST, IMPLEMENT AN
ALGORITHM WHICH RETURNS NODE AT THE BEGIN
NING OF THE LOOP ........................................................................................................................................................ 17
HOW WOULD YOU DESIGN A STACK WHICH, IN
ADDITION TO PUSH AND POP, ALSO HAS A FUNCTION
MIN WHICH RETURNS THE MINIMUM ELEMENT? PUSH,
POP AND MIN SHOULD ALL OPERATE IN O(1) TIME................................................................................................ 18
IMAGINE A (LITERAL) STACK OF PLATES IF THE STACK
GETS TOO HIGH, IT MIGHT TOPPLE THEREFORE, IN
REAL LIFE, WE WOULD LIKELY START A NEW STACK
WHEN THE PREVIOUS STACK EXCEEDS SOME
THRESHOLD
IMPLEMENT A DATA STRUCTURE
SETOFSTACKS THAT MIMICS THIS
SETOFSTACKS
SHOULD BE COMPOSED OF SEVERAL STACKS, AND
SHOULD CREATE A NEW STACK ONCE THE PREVIOUS
ONE EXCEEDS CAPACITY
SETOFSTACKS PUSH() AND
SETOFSTACKS POP() SHOULD BEHAVE IDENTICALLY TO
A SINGLE STACK (THAT IS, POP() SHOULD RETURN THE
SAME VALUES AS IT WOULD IF THERE WERE JUST A
SINGLE STACK) ................................................................................................................................................................ 19
WRITE A PROGRAM TO SORT A STACK IN ASCENDING
ORDER YOU SHOULD NOT MAKE ANY ASSUMPTIONS
Page 3
Page 4
Page 5
PRINT
23451
Page 6
Page 7
Page 8
Page 9
Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set
to 0
Alternate1:
Page 10
Page 11
Find minimum and maximum of two numbers without using if-else or comparison operator.
Alternate1:
max = ( a + b + abs(a-b)/2 )
min = ( a + b abs (a-b)/2 )
Page 12
Time: O(n)
Time: O(n)
Alternate2:
1. p1=first, p2=first;
2. Increment p2 by n-1 positions, to make it point to nth node from beginning.
3. if ( p2 -> next == null ) return p1;
4. else
while ( p2 -> next <> null )
{
p1 = p1 -> next;
p2 = p2 -> next;
}
5. return p1;
Page 13
Delete a node in singly link list, when you have access to that node only.
Ex: a->b->c->d->e
ptr->c
it means, you cant move backward.
Alternate1:
1. ptr-> info = ptr -> next -> info;
2. ptr1 = ptr -> next;
3. ptr->next = ptr->next->next;
4. delete ptr1;
Page 14
Alternate1:
1. reverse(linklist1);
2. reverse(linklist2);
3. Now while ptr is not null, calculate sum, and reverse your resultant linked list.
result.data = ( node1.data + node2.data + carry ) % 10;
if ( node1.data + node2.data + carry ) > 10 then carry = 1;
Page 15
Page 16
Given a circular linked list, implement an algorithm which returns node at the begin ning of the
loop
Ex:
Input: A -> B -> C -> D -> E -> C [the same C as earlier]
Output: C
Alternate1:
LinkedListNode n1 = head;
LinkedListNode n2 = head;
while (n2.next != null) {
n1 = n1.next;
n2 = n2.next.next;
if (n1 == n2) break;
}
n1 = head;
while (n1 != n2) {
n1 = n1.next;
n2 = n2.next;
}
Page 17
How would you design a stack which, in addition to push and pop, also has a function min which
returns the minimum element? Push, pop and min should all operate in O(1) time .
Alternate1:
while push(), also maintain the next minimum element also. You will need n extra space also.
Page 18
Imagine a (literal) stack of plates If the stack gets too high, it might topple Therefore, in real life,
we would likely start a new stack when the previous stack exceeds some threshold Implement a
data structure SetOfStacks that mimics this SetOfStacks should be composed of several stacks,
and should create a new stack once the previous one exceeds capacity SetOfStacks push() and
SetOfStacks pop() should behave identically to a single stack (that is, pop() should return the same
values as it would if there were just a single stack)
Alternate1:
Use array of pointers, and perform push & pop over last stack.
We are not assuming, removing from sub-stack, else it will add rollover charge.
Page 19
Write a program to sort a stack in ascending order You should not make any assumptions about
how the stack is implemented The following are the only functions that should be used to write
this program: push | pop | peek | isEmpty.
Alternate1:
Sorting can be performed with one more stack. Idea is to pull an item from the original stack and
push it on the other stack. If pushing this item would violate the sort order of the new stack, we
need to remove enough items from it so that its possible to push the new Item. Since the items we
removed are on the original stack, were back where we started.
Time Complexity: O(N 2)
public static Stack<Integer> sort(Stack<Integer> s) {
Stack<Integer> r = new Stack<Integer>();
while(!s.isEmpty()) {
int tmp = s.pop();
while(!r.isEmpty() && r.peek() > tmp) {
s.push(r.pop());
}
r.push(tmp);
}
return r;
}
Page 20
Page 21
Given a directed graph, how will you find out weather there is route b/w nodes.
Alternate1:
Use simple path traversal i.e. DFS, BFS, mark every visited node & check weather desired node is
found or not.
Page 22
Page 23
Alternate1:
Make the tree and try to find the possible cases.
if ( e.parent == null || e.right != null )
return leftMostChild ( e.right );
while ( ( p = e.parent ) != null )
{
if ( p.left == e )
break;
e = p;
}
return p;
Page 24
Page 25
Alternate1:
void del ( struct node *p , int n )
{
while ( p->next->next->info != n )
p = p -> next;
p1 = p -> next;
p -> next = p -> next -> next;
delete ( p1 );
}
ex: del ( first , 5 );
Page 26
Page 27
Page 28
Page 29
Page 30
You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes.
Create an algorithm to decide if T2 is a sub tree of T1.
Alternate1:
boolean subTree(TreeNode r1, TreeNode r2) {
if (r1 == null)
return false; // big tree empty & subtree still not found.
if (r1.data == r2.data)
if (matchTree(r1,r2)) return true;
return (subTree(r1.left, r2) || subTree(r1.right, r2));
}
boolean matchTree(TreeNode r1, TreeNode r2) {
if (r2 == null && r1 == null)
return true; // nothing left in the subtree
if (r1 == null || r2 == null)
return false; // big tree empty & subtree still not found
if (r1.data != r2.data)
return false; // data doesnt match
return (matchTree(r1.left, r2.left) && matchTree(r1.right, r2.right));
}
Page 31
You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set
all bits between i and j in N equal to M (eg, M becomes a substring of N located at i and starting at
j)
ex:
Input: N = 1011010010, M = 10101, i = 2, j = 6
Output: N = 1011010110
Alternate1:
1. Clear the bits of N from i to j => N = N & (k=10000011) => N = 1010000010
2. Now M = M << 2
3. N = N | M
K can be obtained as: k = 1 << (i+j) followed by k = k | 1 followed by k = k | 1<<1 ( i times )
Page 32
Given an integer, print the next smallest and next largest number that has the same number of 1
bits in their binary representation.
Alternate1:
Use brute force approach.
Alternate2:
1. Traverse from right to left, once we have passed a 1, turn on next 0
2. Turn off the one, that is just right side of that (this will give you next largest number)
3. Make the small number as small as possible by rearranging all 1s to be as far right as possible.
Ex:
step1: 101
step2: 110 (next largest)
step3: 011 (next smallest)
Page 33
Page 34
Page 35
Write a function to determine the number of bits required to convert integer A to integer B
Ex:
Input: 31, 14
Output: 2
Alternate1:
Although this seems quite complex, but it is quite easy. All you have to do is simply XOR both
numbers and then count number of 1s.
int count = 0;
c = a ^ b;
while ( c != 0 )
{
count += c & 1;
c = c >> 1;
}
print ( count );
Page 36
Given a sorted array of strings which is interspersed with empty strings, write a method to find the
location of a given string .
Ex:
find ball in *at, , , , ball, , , car, , , dad, , + will return 4.
Alternate1:
Use ordinary binary search, but you need to little bit modify the ordinary binary search.
search ( String string[], String str, int first, int last )
{
while ( first <= last )
{
while ( first <= last && string[last] == "" )
{
last -- ;
}
while ( first <= last && string[first] == "" )
{
first ++;
}
}
if ( last < first ) return -1;
int mid = ( last + first ) / 2;
t = mid;
while ( string[mid] == "" ) mid++;
int r = string[mid].compareTo(str);
if ( r == 0 ) return mid;
if ( r < 0 ) first = mid + 1;
else
last = t - 1;
search ( string , str , first , last );
}
Page 37
1. Queens Problem
2. Print all subsets of a set
Page 38
Alternate1:
Use loop to swap bits
Alternate2:
Instead of going for loops
1. X is that number
2. X & with 1010101010 store it in a
3. Again X & 0101010101 store it in b
4. Answer will be a>>1 | b<<1
Answer: return ( ( ( x & 0xaaaaaaaa) >> 1 ) | ( x & 0x55555555 ) << 1 ) )
Page 39
Permutation of a string.
Alternate1:
Page 40
Given a matrix in which each row and each column is sorted, write a method to find an element in
it.
Example:
123
456
789
Alternate1:
suppose we need to find 7
start with 3, if 7 > 3 , yes, row++, 7 > 6, yes, row ++ , 7>9, no, col --, 7 >8, col --, 7 = 7 yes!!!!
Page 41
A circus is designing a tower routine consisting of people standing atop one anothers shoulders.
For practical and aesthetic reasons, each person must be both shorter and lighter than the person
below him or her. Given the heights and weights of each person in the circus, write a method to
compute the largest possible number of people in such a tower.
Example:
Input (ht, wt): (65, 100) (70, 150) (56, 90) (75, 190) (60, 95) (68, 110)
Output: The longest tower is length 6 and includes from top to bottom: (56, 90) (60,95) (65,100)
(68,110) (70,150) (75,190)
Alternate1:
1. Sort weight
2. Sort height
3. for ( I = 2 to n )
{
if ( wt[i] < wt[i-1] or ht[i] < ht[i-1] ) continue;
else break;
}
Page 42
How would you design a database that can store terabytes of data. It should support efficient
range queries.
Alternate1:
For range queries, you need B+ Tree
Page 43
Page 44
Page 45
Page 46
Page 47
Alternate2:
int i,n,flag=0,temp,sp;
int arr[]={1,1,0,1,1,1,0,1,1,0};
for(i=0;i<arr.length;i++)
{
if(arr[i]==1&&flag==0)
{
sp=i;
flag=1;
}
if(arr[i]==0 && flag==1)
{
arr[i] <--> arr[sp];
i=sp;
flag=0;
}
}
Page 48
Write a program to print NXN matrix where all elements are increasing from diagonal in both
directions as shown in below examples.
Example:
PrintMatrix(5)
1 2 34 5
2 1 23 4
3 2 12 3
4 3 21 2
5 4 32 1
Alternate1:
void PrintMatrix ( int N )
{
int j = 2345;
for ( int i = 1 to N )
{
j = i * 10000 + j;
print ( j );
j = j / 10;
}
}
complexity O(n)
Page 49
You are given with a 3 sorted arrays of integers. You have to write an efficient function to find and
print the middle elements altogether from 3 arrays. The middle element is the element which will
lie exactly in middle if all 3 arrays are combined and sorted. If there are 2 such elements then print
both. You can assume that none of element is repeated again. Remember, you are not allowed to
use extra memory to hold the elements of the array.
Example:
InputArray1 - { 2,7,14,40,44,66,68,88,102}
Array2 - {3,12,15,17,23,42,47,67,108}
Array3 - {8,13,24,49,59,86,119,130,150}
Output40 ( There are exactly 13 elements smaller than 40 and 13 larger than 40)
Alternate1:
void MiddleElement ( int []a1,int []a2,int []a3)
{
sum = a1.length + a2.length + a3.length;
c = sum / 2;
for ( i =0,j=0,k=0 ; (i+j+k) < (c+1); )
{
if ( a1[i] >= a2[j] && a1[i] >= a3[k] )
num = a1[i++];
else if ( a2[j] >= a3[k] )
num = a2[j++];
else
num = a3[k++];
if ( (i+j+k) == c+1 )
{
printf ( "%d", num );
break;
}
if ( num % 2 == 0 )
c++;
}
}
complexity O(n)
Page 50
Write a program to remove duplicate words from a string ( inline - without using extra memory).
You also need to take care that duplication detection is case in-senstive. Remeber, you are not
allowed to use extra memory to hold the elements of the array.
Example:
Input- "Where there is a will there is a way"
Output- "Where there is a will way"
Input- "Who is WHO"
Output- "Who is"
char [] RemoveDuplicateWords ( char [] s )
{
swapFlag = -1;
for ( i = 2 to s.length )
{
for ( j = i-1 to 1 )
{
if ( s[j].equalsIgnoreCase(s[i]) && swapFlag == -1)
{
s[i]="";
swapFlag = i;
break;
}
if ( s[j].equalsIgnoreCase(s[i]) && swapFlag != -1)
{
s[i]="";
break;
}
if ( ! s[j].equalsIgnoreCase(s[i]) && swapFlag != -1)
{
s[swapFlag] <--> s[i];
swapFlag ++;
}
}
}
return s;
}
complexity O(n2)
Page 51
Page 52
Page 53
Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents) and pennies (1
cent), write code to calculate the number of ways of representing n cents.
Alternate1:
public static int makeChange(int n, int denom) {
int next_denom = 0;
switch (denom) {
case 25:
next_denom = 10;
break;
case 10:
next_denom = 5;
break;
case 5:
next_denom = 1;
break;
case 1:
return 1;
}
int ways = 0;
for (int i = 0; i * denom <= n; i++)
ways += makeChange(n - i * denom, next_denom);
return ways;
}
System.out.writeln(makeChange(n, 25));
Page 54
Implement the paint fill function that one might see on many image editing programs. That is,
given a screen (represented by a 2-dimensional array of Colors), a point, and a new color, fill in the
surrounding area until you hit a border of that color.
Alternate1:
boolean PaintFill(Color[][] screen, int x, int y, Color ocolor, Color ncolor) {
if ( out of range )
return false;
if (screen[y][x] == ocolor) {
screen[y][x] = ncolor;
PaintFill(screen, x - 1, y, ocolor, ncolor); // left
PaintFill(screen, x + 1, y, ocolor, ncolor); // right
PaintFill(screen, x, y - 1, ocolor, ncolor); // top
PaintFill(screen, x, y + 1, ocolor, ncolor); // bottom
}
return true;
}
Page 55
Implement an algorithm to print all valid (e g , properly opened and closed) combinations of npairs of parentheses.
EXAMPLE:
input: 3 (e g , 3 pairs of parentheses)
output: ()()(), ()(()), (())(), ((()))
Alternate1:
public static void printPar(int l, int r, char[] str, int count) {
if (l < 0 || r < l) return;
if (l == 0 && r == 0) {
System.out.println(str);
} else {
if (l > 0) {
str*count+ = (;
printPar(l - 1, r, str, count + 1);
}
if (r > l) {
str*count+ = );
printPar(l, r - 1, str, count + 1);
}
}
}
public static void printPar(int count) {
char[] str = new char[count*2];
printPar(count, count, str, 0);
}
Page 56
Thi s fi l e i s free of cha rge. You ca n downl oa d i t freel y, di s tri bute i t. However you ma y ha ve to pa y
di s tribution charges. Contents are being provided as-is without any warranty. Most of its ques ti ons a re
taken from internet a nd one of the references worth mentioning here i s the book na med Cra cki ng The
Codi ng Intervi ew by Ga yl e La a kma nn.
Page 57