Sunteți pe pagina 1din 58

CRACK THE CODE

Rohit Birla

CRACK THE CODE

Rohit Birla

CRACK THE CODE

Page 1

KEY TO DESIGN YOUR CODE:


1.
2.
3.
4.
5.
6.

Read and understand the question, if you didnt, go to step 1 again


Draw figures to get thru your ideas
Think about the base case
Write code on a paper
Talk out loud
Now move towards worst case

Dont memorize solutions

CRACK THE CODE

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

CRACK THE CODE

Page 3

ABOUT HOW THE STACK IS IMPLEMENTED


THE
FOLLOWING ARE THE ONLY FUNCTIONS THAT SHOULD
BE USED TO WRITE THIS PROGRAM: PUSH | POP | PEEK
| ISEMPTY ........................................................................................................................................................................ 20
CHECK WEATHER THE TREE IS BALANCED OR NOT. ................................................................................................ 21
GIVEN A DIRECTED GRAPH, HOW WILL YOU FIND OUT
WEATHER THERE IS ROUTE B/W NODES. .................................................................................................................. 22
GIVEN A SORTED ARRAY, CREATE A BST WITH
MINIMUM HEIGHT. ....................................................................................................................................................... 23
FIND THE INORDER SUC CESSOR OF A NODE. ........................................................................................................... 24
0-N ARE STORED IN AN ARRAY [1-N], FIND THE MISSING
NUMBER. ......................................................................................................................................................................... 25
DELETE A NODE FROM CIRCULAR SINGLY LINKED LIST........................................................................................... 26
PRINT THE KTH LARGES T ELEMENT FROM A BST..................................................................................................... 27
PRINT LAST X LINES OF A FILE. ..................................................................................................................................... 28
HOW WILL YOU TEST PERFORMANCE OF A WEB PAGE?........................................................................................ 29
HOW MANY ZEROS ARE THERE IN A FACTORIAL OF A
NUMBER. ......................................................................................................................................................................... 30
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) ............................................................................................................................................................... 32
GIVEN AN INTEGER, PRINT THE NEXT SMALLEST AND
NEXT LARGEST NUMBER THAT HAS THE SAME NUMBER
OF 1 BITS IN THEIR BINARY REPRESENTATION. ........................................................................................................ 33
MERGE ARRAY B IN ARRAY A. BOTH ARE SORTED
ARRAY. ............................................................................................................................................................................. 34
IF YOU HAVE 2 GB DATA, HOW WILL YO U SORT...................................................................................................... 35
WRITE A FUNCTION TO DETERMINE THE NUMBER OF
BITS REQUIRED TO CO NVERT INTEGER A TO INTEGER B ........................................................................................ 36
GIVEN A SORTED ARRAY OF STRINGS WHICH IS
INTERSPERSED WITH EMPTY STRINGS, WRITE A
METHOD TO FIND THE LOCATION OF A GIVEN STRING ......................................................................................... 37
SOME UNSO LVED PROBLEMS...................................................................................................................................... 38
SWAP ALL EVEN AND OD D BITS OF A NUMBER. ...................................................................................................... 39
PERMUTATION OF A STRING. ...................................................................................................................................... 40
GIVEN A MATRIX IN WHICH EACH ROW AND EACH
COLUMN IS SORTED, WRITE A METHOD TO FIND AN
ELEMENT IN IT. ............................................................................................................................................................... 41
A CIRCUS IS DESIGNING A TOWER ROUTINE
CONSISTING OF PEOPLE STANDING ATOP ONE

CRACK THE CODE

Page 4

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 TOW ER. ........................................................................................................................................................ 42
HOW WOULD YOU DESIGN A DATABASE THAT CAN
STORE TERABYTES OF DATA. IT SHOULD SUPPORT
EFFICIENT RANGE QUERIES. ......................................................................................................................................... 43
SUM 2 NUMBERS, WITHOUT + OPERATOR............................................................................................................... 44
SUM OF 2 NUMBERS WITHOUT ANY ARITHMETIC
OPERATOR....................................................................................................................................................................... 45
HOW WILL YOU CHECK WEATHER A NUMBER IS POWER
OF 2 OR NOT. .................................................................................................................................................................. 46
PRINT THE SPIRAL MATRIX. .......................................................................................................................................... 47
SORT THE ARRAY OF 0S N 1S. ...................................................................................................................................... 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 3 4 5 2 1 2 3 4 3 2 1 2 3
4 3 2 1 2 5 4 3 2 1 ........................................................................................................................................................... 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} OUTPUT- 40 ( THERE
ARE EXACTLY 13 ELEMENTS SMALLER THAN 40 AND 13
LARGER THAN 40) .......................................................................................................................................................... 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"........................................................................................................................... 51

CRACK THE CODE

Page 5

PRINT
23451

THE FOLLOWING PATTERN


12345
34512
45123
51234 ............................................................................................................... 52

SWAP TWO NUMBERS WITHOUT USING THIRD


VARIABLE. ........................................................................................................................................................................ 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............................................................................................................................. 54
IMPLEMENT THE PAINT FILL FUNCTION THAT ONE
MIGHT SEE ON MANY IMAGE EDITING PROGRAMS.
THAT IS, GIVEN A SCREEN (REPRESENTED BY A 2DIMENSIONAL ARRAY OF COLORS), A POINT, AND A
NEW COLOR, FILL IN THE SURROUNDING AREA UNTIL
YOU HIT A BORDER OF THAT CO LOR.......................................................................................................................... 55
IMPLEMENT AN ALGORITHM TO PRINT ALL VALID (E G ,
PROPERLY OPENED AND CLOSED) COMBINATIONS OF
N-PAIRS OF PARENTHESES. .......................................................................................................................................... 56

CRACK THE CODE

Page 6

Write an algorithm to determine if string has unique characters


Alternate1:

Time Complexity: O(n)

boolean char_set[] = new char_set[256];


for ( int i = 0 to str.length() )
{
int v = str.charAt(i);
if ( char_set[v] ) return false;
char_set[v] = true;
}
return true;
Alternate2:

Time Complexity: O(n)

assuming string has only small characters a to z


int character = 0;
for ( i = 0 to str.length() )
{
int v = str.charAt(i) a ;
if ( ( character & ( 1 << v ) ) > 0 ) return false;
character |= ( 1 << v ) ;
}
return true;
Alternate3:

Time Complexity: O(n2)

Modify the insertion sort loop


Every time, you encounter a character, inner loop will go back and search weather the same
character is exist or not.
This alternative however takes more time, but there is no need of extra space.

CRACK THE CODE

Page 7

Write a method to decide if two strings are anagrams or not.


Alternate 1:
int anagram ( String s1, String s2 )
{
return (sort(s1) == sort(s2));
}

CRACK THE CODE

Page 8

Write a method to replace all spaces in a string with %20


Alternate1:
1. Count number of spaces
Time: O(n)
2. New length = old length + spaces count * 2;
3. for ( i = str.length() to 0 )
{
copy if not space;
if space, insert 0,2,%;
}
Time: O(n)

CRACK THE CODE

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:

Time Complexity: O(n2)

We need M + N extra space


void set_zeroes ( int [][] m )
{
int[] rows = m.rows;
int[] cols = m.cols;
for( int i = 0 to rows )
for ( int j = 0 to cols )
if ( m[i][j] = 0 )
rows[i] = cols[j] = 1;
for( int i = 0 to rows )
for ( int j = 0 to cols )
if ( rows[i] == 0 || cols[j] == 0 )
m[i][j] = 0;
}

CRACK THE CODE

Page 10

Write code to remove duplicates from an unsorted linked list.


Alternate1:
extra space, but time O(n)
void deletedup ( LinkedListNode n )
{
HashTable table = new HashTable();
LinkedListNode previous = null;
while ( n != null )
{
if ( table.containsKey(n.data) )
previous.next = n.next;
else
{
table.put ( n.data , true );
previous = n;
}
n = n.next;
}
}
Alternate2:
no extra space, but time O(n 2)
void deletedup ( struct node *p)
{
while ( p -> next -> next != null )
{
if ( search_if_exist ( p->next->info , p ) )
{
p1 = p->next;
p->next = p->next->next;
delete p1;
}
p = p -> next;
}
}
boolean search_if_exist ( int i , struct node * p )
{
start with first, move till p is reached
if info is same as of I return true
else false after loop
}

CRACK THE CODE

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 )

CRACK THE CODE

Page 12

Find nth element from last in singly link-list.


Alternate1:
1. Count number of nodes
2. Print accordingly desired node

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;

CRACK THE CODE

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;

CRACK THE CODE

Page 14

Sum of two numbers, which are represented by linked list.


Ex:

123 = 1 -> 2 -> 3


456 = 4 -> 5 -> 6

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;

CRACK THE CODE

Page 15

Use single array for 3 stacks.


Alternate1:
stack1 [0 to n/3)
stack2 [n/3 to 2n/3)
stack3 [2n/3 to n)

CRACK THE CODE

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

CRACK THE CODE

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.

CRACK THE CODE

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.

CRACK THE CODE

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

CRACK THE CODE

Page 20

Check weather the tree is balanced or not.


Alternate1:
int maxheight ( Tree r )
{
if ( r == null ) return 0;
return 1 + max ( maxheight ( r.left ) + maxheight ( r.right ) );
}
int minheight ( Tree r )
{
...
}
int isBalanced ( Tree r )
{
return ( ( maxheight(r) - minheight(r) ) <= 1 ) ;
}

CRACK THE CODE

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.

CRACK THE CODE

Page 22

Given a sorted array, create a BST with minimum height.


Alternate1:
Insert middle element as root
Insert left element to left side
Insert right element to right side
TreeNode add ( arr, L, R )
{
mid = ( L + R ) / 2 ;
TreeNode n = new TreeNode ();
n.value = arr[mid];
n.left = add ( arr , L , mid - 1 );
n.right = add ( arr , mid + 1 , R );
return n;
}

CRACK THE CODE

Page 23

Find the inorder successor of a node.

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;

CRACK THE CODE

Page 24

0-n are stored in an array [1-n], find the missing number.


Alternate1:
missing number = sum of n numbers sum of array elements

CRACK THE CODE

Page 25

Delete a node from circular singly linked list.

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

CRACK THE CODE

Page 26

Print the kth largest element from a BST.


Alternate1:
we need to maintain the total num_elements.
void inorder ( struct node *p , int count, int k1 )
{
if ( p != null )
{
inorder ( p-> left , count , k1 );
count ++
if ( count == k1 )
print ( p-> info )
inorder ( p-> right , count , k1 );
}
}
ex: inorder ( first , 0 , num_elements - k + 1 );

CRACK THE CODE

Page 27

Print last x lines of a file.


Alternate1:
read file and count number of lines
read file again and print last x lines
Alternate2:
1. Use array of x lines
2. Every time read one line & store it in array
3. Once u are at end of file, print the array.
step 1 (initially): array = {a, b, c, d, e, f}. p = 0
step 2 (insert g): array = {g, b, c, d, e, f}. p = 1
step 3 (insert h): array = {g, h, c, d, e, f}. p = 2
step 4 (insert i): array = {g, h, i, d, e, f}. p = 3

CRACK THE CODE

Page 28

How will you test performance of a web page?


1. Response Time
2. Throughput
3. Resource Utilization
4. Maximum load that system can bear

CRACK THE CODE

Page 29

How many zeros are there in a factorial of a number.


Alternate1:
There will be zero every time a 5 and a 2 will appear. So, we will count number of 5.
int numZeroes ( int n )
{
int count = 0;
for ( int i = 5 ; num / i > 0 ; i *=5 )
count += num / i ;
return count;
}

CRACK THE CODE

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

CRACK THE CODE

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 )

CRACK THE CODE

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)

CRACK THE CODE

Page 33

Merge array B in array A. Both are sorted array.


Alternate1:
start comparing from last in both the arrays and also insert to the last of A and so on

CRACK THE CODE

Page 34

If you have 2 GB data, how will you sort.


Alternate1:
Remember, you have 2GB of data, that simply means, you can not store them in main memory. So,
assuming, you have X MB of main memory.
that means, you will be having 2GB / X MB = k chunks.
1. Now sort each chunk and place it back
2. Then merge them one by one

CRACK THE CODE

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

CRACK THE CODE

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

CRACK THE CODE

Page 37

Some Unsolved Problems

1. Queens Problem
2. Print all subsets of a set

CRACK THE CODE

Page 38

Swap all even and odd bits of a number.

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

CRACK THE CODE

Page 39

Permutation of a string.
Alternate1:

Time Complexity: O(n!)

ArrayList<String> getPerms ( String s )


{
ArrayList<String> permutation = new ArrayList<String> ();
if ( s == null ) return null;
else if ( s.length() == 0 )
{
permutations.add("");
return permutations;
}
char first = s.charAt(0);
string reminder = s.substring(1);
ArrayList<String> words = getPerms ( reminder );
for ( String w : words )
for ( j = 0 ; j < words.length() ; j ++ )
permutation.add ( insertCharAt(w,first,j) );
return permutation;
}

CRACK THE CODE

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

CRACK THE CODE

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

CRACK THE CODE

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

CRACK THE CODE

Page 43

Sum 2 numbers, without + operator.


Alternate1:
sum = a (-1)*b

CRACK THE CODE

Page 44

Sum of 2 numbers without any arithmetic operator.


Alternate1:
fun ( int a , int b )
{
if ( b == 0 ) return a;
sum = a ^ b;
carry = ( a & b ) << 1;
return fun ( sum , carry );
}

CRACK THE CODE

Page 45

How will you check weather a number is power of 2 or not.


Alternate1:
keep on dividing by 2, if every time, there is no reminder and number becomes 0
Alternate2:
(n & (n-1) ) == 0

CRACK THE CODE

Page 46

Print the spiral matrix.


Alternate1:
int i,j,k=0,count=0,n,arr[5][5];
n=5;
while(count<(n+1)/2)
{
for(i=count,j=count;j<n-count;j++)
arr[i][j]=++k;
for(i=count+1,j=j-1;i<n-count;i++)
arr[i][j]=++k;
for(i=i-1,j=j-1;j>=count;j--)
arr[i][j]=++k;
for(i=i-1,j=j+1;i>=count+1;i--)
arr[i][j]=++k;
count++;
}

CRACK THE CODE

Page 47

Sort the array of 0s n 1s.


Alternate1:
Use traditional sorting approach.

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

CRACK THE CODE

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)

CRACK THE CODE

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)

CRACK THE CODE

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)

CRACK THE CODE

Page 51

Print the following pattern


12345
23451
34512
45123
51234
Alternate1:
Use two nested loops and print the pattern.
Alternate2:
num=12345,q,rem;
for ( i = 0 to 5 )
{
printf("%ld\n",num);
q=num/10000;
rem=num%10000;
num=rem*10+q;
i++;
}

CRACK THE CODE

Page 52

Swap two numbers without using third variable.


Alternate1:
a = b - a;
b = b - a;
a = a + b;
Alternate2:
a = a^b;
b = a^b;
a = a^b;
Alternate3:
b^=a^=b^=a;

CRACK THE CODE

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

CRACK THE CODE

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

CRACK THE CODE

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

CRACK THE CODE

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.

CRACK THE CODE

Page 57

S-ar putea să vă placă și