This action might not be possible to undo. Are you sure you want to continue?

ﬁle:///Users/xianghaochen/Desktop/View.html

**Algorithms and Data Structures
**

Ajeet Singh

1. 2. 3. 4. 5. 6. 7. 8. 9.

Preface Bits Manipulations Array Stack Queue Link-List Tree General Programing Puzzle

1. Preface

These questions are from my personal study notes. Most of these questions have been asked in technical interviews of companies like Google, Microsoft, Adobe, Yahoo, etc. These questions/solutions have been selected from various sources Introduction to algorithms - Thomas H. Cormen The algorithm design manual - Steven S. Skiena Orkut community - Algorithms Web Search I have tried my level best to provide you the optimal solution but in case you want to Propose a better solution Discuss posted solution Add new problem and solution Feedback about web page Feel free to write me Email or Discuss on my Blog, Discuss in Community.

2. Bits Manipulations

Problem - 1: Compute the sign of an integer sign = +1 | (v >> (sizeof(int) * CHAR_BIT - 1)); // if v < 0 then -1, else +1

1 of 80

8/21/10 2:33 PM

Algorithms and Data Structures

ﬁle:///Users/xianghaochen/Desktop/View.html

Problem - 2: Compute the integer absolute value (abs) without branching int const mask = v >> sizeof(int) * CHAR_BIT - 1; r = (v ^ mask) - mask; //r = (v < 0) ? -v : v, Problem - 3: Compute the minimum (min) or maximum (max) of two integers without branching r = y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1))); // min(x, y) r = x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1))); // max(x, y) Problem - 4: Determining if an integer is a power of 2 f = !(v & (v - 1)) && v; Problem - 5: Conditionally set or clear bits without branching bool f; // conditional flag unsigned int m; // the bit mask unsigned int w; // the word to modify: if (f) w |= m; else w &= ~m; w ^= (-f ^ w) & m; Problem - 6: Count number of bits set in an Intger Approach -1 Brian Kernighan's way for (c = 0; v; v >>= 1) { c += v & 1; } Approach -2 static inline ulong bit_count(ulong x) // Return number of bits set { x = (0x55555555UL & x) + (0x55555555UL & (x>> 1)); // 0-2 in 2 bits x = (0x33333333UL & x) + (0x33333333UL & (x>> 2)); // 0-4 in 4 bits x = (0x0f0f0f0fUL & x) + (0x0f0f0f0fUL & (x>> 4)); // 0-8 in 8 bits x = (0x00ff00ffUL & x) + (0x00ff00ffUL & (x>> 8)); // 0-16 in 16 bits x = (0x0000ffffUL & x) + (0x0000ffffUL & (x>>16)); // 0-31 in 32 bits return x; } Approach -3 static inline ulong bit_count(ulong x) { // Return number of bits set x = (x + (x >> 4)) & 0x0f0f0f0fUL; // 0-8 in 4 bits x += x >> 8; // 0-16 in 8 bits x += x >> 16; // 0-32 in 8 bits return x & 0xff;

2 of 80

8/21/10 2:33 PM

Algorithms and Data Structures

ﬁle:///Users/xianghaochen/Desktop/View.html

} Approach - 4 static inline ulong bit_count(ulong x) { // Return number of bits set x -= (x>>1) & 0x55555555UL; // 0-2 in 2 bits x = ((x>>2) & 0x33333333UL) + (x & 0x33333333UL); // 0-4 in 4 bits x = ((x>>4) + x) & 0x0f0f0f0fUL; // 0-8 in 8 bits x *= 0x01010101UL; return x>>24; }

Problem - 7: Computing parity the naive way unsigned int v; // word value to compute the parity of bool parity = false; // parity will be the parity of b while (v) { parity = !parity; v = v & (v - 1); } Problem - 8: Swapping values with XOR #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) Problem - 9: Swapping individual bits with XOR unsigned int i, j; // positions of bit sequences to swap unsigned int n; // number of consecutive bits in each sequence unsigned int b; // bits to swap reside in b unsigned int r; // bit-swapped result goes here int x = ((b >> i) ^ (b >> j)) & ((1 << n) - 1); // XOR temporary r = b ^ ((x << i) | (x << j)); As an example of swapping ranges of bits suppose we have have b = 00101111 (expressed in binary) and we want to swap the n = 3 consecutive bits starting at i = 1 (the second bit from the right) with the 3 consecutive bits starting at j = 5; the result would b e r = 11100011 (binary).

3 of 80

8/21/10 2:33 PM

Algorithms and Data Structures

ﬁle:///Users/xianghaochen/Desktop/View.html

Problem - 10: Compute modulus division by 1 << s without a division operator const unsigned int n; // numerator const unsigned int s; const unsigned int d = 1 << s; // So d will be one of: 1, 2, 4, 8, 16, 32, ... unsigned int m; // m will be n % d m = n & (d - 1); Problem - 11: Compute modulus division by (1 << s) - 1 without a division operator unsigned int n; // numerator const unsigned int s; // s > 0 const unsigned int d = (1 << s) - 1; // so d is either 1, 3, 7, 15, 31, ...). unsigned int m; // n % d goes here. for (m = n; n > d; n = m) { for (m = 0; n; n >>= s) { m += n & d; } } // Now m is s >>= 1) // unroll for more speed... { r++; } Problem - 12: int CheckSetBit(int num, int pos) { int x = 1; x = ~(x<<pos); // creating mask in which only pos bit is unset return ((num & x) == num); // checking whether number is same... if same then pos bit is set } Problem - 13: How to reverse the odd bits of an integer? XOR each of its 4 hex parts with 0101. inline ulong reverse_bit(ulong a, ulong i) { return (a ^ 0x55555555);

4 of 80

8/21/10 2:33 PM

} Problem . ulong i) // Return a with bit[i] changed. static inline ulong delete_lowest_bit(ulong x) { return x & (x-1). static inline ulong lowest_bit(ulong x) { return x & -x.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.html } Problem . Return 0 for input == 0.18: Return word were the lowest bit set in x is cleared. { return (a ^ (1UL << i)).17: Return word where only the lowest unset bit in x is set.16: Return word where only the lowest set bit in x is set. // k1==k2 is allowed (a is unchanged then) { ulong x = ((a>>k1) ^ (a>>k2)) & 1. // change if bits differ return a.14: inline ulong change_bit(ulong a. static inline ulong lowest_zero(ulong x) { x = ~x. ulong k1. } Problem . ulong k2) // Return a with bits at positions [k1] and [k2] swapped. } Problem . } 5 of 80 8/21/10 2:33 PM . Return 0 if no bit is set. // change if bits differ a ^= (x<<k1). // one if bits differ a ^= (x<<k2). return x & -x. Return 0 if all bits are set.15: Swap k1 bits of integer a with its k2 bits static inline ulong bit_swap(ulong a. // use: -x == ~x + 1 } Problem .

one can use the function ulong m = (1UL<<2) | (1UL<<3) | (1UL<<5) | . } Problem . } Problem .. | (1UL<<31). static inline ulong set_lowest_zero(ulong x) { return x | (x+1). Example: 01011000 --> 00000111 Return 0 if all bits are set.23: Computation of the average (x + y)/2 of two arguments x and y.21: Return word where all the (low end) zeros are set. ulong y) // Return (x+y)/2 // Use the fact that x+y == ((x&y)<<1) + (x^y) 6 of 80 8/21/10 2:33 PM . return (((x-1)^x) >> 1).19: Return word were the lowest unset bit in x is set.. return (((x+1)^x) >> 1). The function gives the correct value even if (x + y) does not fit into a machine word: static inline ulong average(ulong x.20: static inline ulong low_bits(ulong x) // Return word where all the (low end) ones are set.22: in order to determine whether x is a prime less than 32. Return ~0 for input == ~0. } Problem .Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.html Problem . static inline ulong low_zeros(ulong x) { if ( 0==x ) return ~0UL. // precomputed static inline ulong is_tiny_prime(ulong x) { return m & (1UL << x). // Example: 01011011 --> 00000011 // Return 0 if lowest bit is zero: // 10110110 --> 0 { if ( ~0UL==x ) return ~0UL. } Problem .

{ ulong m = 0x0000ffffUL.html // that is: sum == carries + sum_without_carries { return (x & y) + ((x ^ y) >> 1). toward the most significant bit) { return (x<<r) | (x>>(BITS_PER_LONG-r)). } static inline ulong bit_swap_2(ulong x) // Return x with groups of 2 bits swapped.26: The 64-bit branch is omitted in the following examples.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. } Equivalently. } Problem . Adjacent groups of 2 bits are swapped by static inline ulong bit_swap_1(ulong x) // Return x with groups of 2 bits swapped.24: static inline ulong bit_rotate_left(ulong x.e. return ((x & m) << 16) | ((x & (m<<16)) >> 16). { ulong m = 0x33333333UL. return ((x & m) << 1) | ((x & (~m)) >> 1). } Problem . return ((x & m) << 2) | ((x & (~m)) >> 2). static inline ulong bit_swap_4(ulong x) 7 of 80 8/21/10 2:33 PM . ulong r) // Return word rotated r bits to the left // (i. { ulong m = 0x55555555UL. } Problem .25: When swapping half-words (here for 32-bit architectures) static inline ulong bit_swap_16(ulong x) // Return x with groups of 16 bits swapped.

//x = bit_swap_32(x).Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.27: Reverse the bits of an integer static inline ulong revbin(ulong x) // Return x with bitsequence reversed { x = bit_swap_1(x).1. v >>= 1) { r <<= 1. x = bit_swap_2(x).html // Return x with groups of 4 bits swapped. { ulong m = 0x00ff00ffUL. } and static inline ulong bit_swap_8(ulong x) // Return x with groups of 8 bits swapped. // shift when v's highest bits are zero Problem . return ((x & m) << 4) | ((x & (~m)) >> 4). return ((x & m) << 8) | ((x & (~m)) >> 8). x = bit_swap_8(x). } r <<= s. first get LSB of v int s = sizeof(v) * CHAR_BIT . x = bit_swap_16(x). required only when m/c is 64 bit return x. // r will be reversed bits of v. r |= v & 1. } Problem . // extra shift needed at end for (v >>= 1. { ulong m = 0x0f0f0f0fUL. } Problem . s--.28: Reverse bits the obvious way unsigned int v. x = bit_swap_4(x). // input bits to be reversed unsigned int r = v. v.29: Add to numbers 8 of 80 8/21/10 2:33 PM .

Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. TBD .31: Give me the best way to multiply an integer by 3.30: Dump binary void print(ulong v) { cout << "BIN:". Working out on good solution. int s = 32. Suppose a = N mod X kX + a = N 9 of 80 8/21/10 2:33 PM . v <<= 1.> may cause overflow since there is right shifted 3 times Problem .33: Calculate N%17 without using arithmetic operators. } cout << endl. and change the while condition to while( x & m ) to add one to a number Problem . m<<=1. Please mail me if you already have one.5. int m=1. } Problem .html sum = A ^ B carry A&B crud way a-(-B) Problem .32: How would you add/Subtract 1 to a number without using the arithmetic operators int x=16. (num<<3 .num)>>1 This is multiply the number by 7 and divide by 2 . There are many solutions to this but (x>>1)+x+(x<<1) is the best since it is least prone to overflowing. while( !( x & m)) { x=x^m.Below algorithm is wrong. while (s--) { cout <<((v & 0x80000000UL) >> 31). } x=x^m.

1: Find the median of two sorted arrays with minimum possible memory and time complexity? This algorithm is slight modification of quick sort. n) if median = NOT_FOUND then median = FindMedian(B. Let us say M ( Na+Nb )/2. Here is the implementation for the case where Na = Nb.k mod S) Now we have X = 17 S = 16 Calculating N % 16: (m = n & (d .html K( S +1) + a = N a = abs (N mod S . Now calculating K: divide any number by 17 = N >> 4 . n. B.Nb]. Since arrays are already sorted we can take the benefit of this information and we will try to locate Mth largest element in combined array. declare NOT_FOUND = -1 Median(A. B): n = length [X] // is same for B median = FindMedian(A.Na] and B[1.M] otherwise median will lie in A[1. B. Suppose we are having two arrays A and B of length Na and Nb respectively. n.M] and B[M.N k mod S = (N>>4 .((N>>4 .. Now recurs this until we find median M. n. The median of these two arrays would be the element at (Na+Nb)/2 of sorted combination array (A+B).1. If median of array A is greater than median of array B that means median lies in Array A[M. Now to figure out M without using any extra memory we will use divide and conquer approach.. 1..N) &3 Remainder m = Abs (N & 3 . n) return median FindMedian(A.N) &3)) 3. where S = d pow 2) a = N & 3. Array Problem . A.1).Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. low.. high): if low > high then return NOT_FOUND else K=(low+high)/2 if(2*k == n and A[n] <= B[1]) then return A[n] else if (k < n and B[n-k] <= A[k] <= B[n-k+1]) then 10 of 80 8/21/10 2:33 PM .

FindNumberOfRotations(A): 1. k-1) else return FindMedian(A. high) Time complexity : O(log n) Space complexity : O(1). if (A[0] < A[n-1]) then There is no rotation made return 0 2.3: Find out kth smallest element in two sorted arrays of different size? We will again use divide and conquer approach and binary search algorithm to solve this problem.e. n. B. high =1 3. We will apply the same algorithm as Binary search to find out the point where smallest and largest element meet (transition point).2: Given an array of N elements initially sorted then it is rotated right K times where 0 <= K <= N. B. else transition lies in right half of array if(A[mid] > A[mid+1]) then return mid+1 else low = mid+1 Go to step 3 Time complexity : O(log n) Space complexity : O(1).html return A[k] else if( A[k] > B[n-k+1]) then return FindMedian(A. Write a algorithm to find out number of rotation made i. If k is smaller that means if we sort these two array kth element will be in A otherwise B. if(A[mid] < A[high]) then transition lies in left half of the array if A[mid-1] > A[mid] then return mid else high = mid-1 Go to step 3. Check if K is smaller or larger than (sizeA+sizeB)/2 2. constant Problem . constant Problem . K? To solve this problem we will again use divide and conquer approach. n. low. 11 of 80 8/21/10 2:33 PM . mid = (low + high)/2 4. low = 0. k+1.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. We are going to use following information in below algorithm 1.

. now we can eliminate B[(c+d)/2 .d]..d].(a+b)/2].(c+d)/2]. B[(c+d)/2+1.d]. k-(c+d)/2) 12 of 80 8/21/10 2:33 PM .b] and B[c. sizeB = d . determine the kth smallest number based on the return location of search } else // both subarrays have at least two elements { midA = A[(a+b)/2] // the middle value of subarray A midB = B[(c+d)/2] // the middle value of subarray B if midA <= midB then { if k <= sizeA/2 + sizeB/2 then // search the kth smallest but eliminate the right half of B search(A[a. 5. B[c.d].(c+d)/2)th smallest but eliminate the left half of B search(A[a.d] Search (A[a. B[c. Suppose median of B is greater than median of A. Repeat #5 till we get kth element. k . k) { sizeA = b .b]..Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.c + 1 if sizeA == 1 then { //apply binary search of A[a] in array B[c.... 4 No we can divide our search based on the information we got from #3.d]..b]....b]..a + 1.d] elements since kth element is in either A or rest half of B 6.b]... determine the kth smallest number based on the return location of search } else if sizeB == 1 then { //apply binary search of B[c] in array A[a.. k) else // search the (k.html 3. Let us assume we have two arrays A[a.b]. k) else // search the (k-(a+b)/2)th smallest but eliminate the left half of A search(A[(a+b)/2+1. Now compare the median of these two array. B[c. B[c.(a+b)/2) } else // if midA > midB { if k <= sizeA/2 + sizeB/2 then // search the kth smallest but eliminate the right half of A search(A[a.

_green = N-1. _red++. Three color problem : Partition the given integer array in three parts such that all the elements of part P1 < Part p2 < part p3. Yes they form the permutation + Complexity would be O(n) . A[_red]) _blue++. "green". "red". Approach . } } 13 of 80 8/21/10 2:33 PM .4: We need to show that the elements of A' form a permutation of the elements of A. If M = M' and S = S'. "blue".html } } } Time complexity : O(log n) Space complexity : O(1). while(_red <= _green) { if (A[_red] == "blue") { Swap(A[_blue].This can cause multiplication overflow and multiplication is costly operation Approach . (Two color problem sort binary array) A[N] = { "blue".2 Sort A and A' if A = A' they form permutation + No overflow.1 Multiply and add all the elements in both that array.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. A[_red]) _green--. else { Swap(A[_green]. "red". Partition (A[N]): _blue = 0. "red". "red"}.complexity will be O(nlogn) Problem . "green".5: Dutch National Flag problem. _red = 0. Simple approach . constant Problem . } else if (A[_red] == "red") _red++.

} else { B[index_new] = A[indexA]. index_new--. indexB--. Sort the elements in S. indexA--. 34. 0} Merge(B[2n]. 99} Set B[2*n] = = {4. 0. n ) : indexA=n -1 indexB=n -1 index_new=2n -1 while (index_new >= 0) { if (A[indexA] < B[indexB]) { B[index_new] = B[indexB]. constant Problem . 54. 11.6: Merge two sorted array Set A[n] = {2. } else if (!(indexA+1)) break. } // Optimization if A or B can be directly copied if (!(indexB+1)) { while((index_new+1)) B[index_new--] = A[indexA--]. Time complexity: O(n log n) 4. } Time complexity : O(n) Space complexity : O(n) Problem . Form the set S'= {z : z = x − y for some y ∈ S}.1 1. remove all but one instance. 0. Time complexity: O(n log n) 2.html To solve two color / Binary array problem remove inner 'if else' Time complexity : O(n) Space complexity : O(1). Sort the elements in S'. If any value in S appears more than once. break. 0. Do the 14 of 80 8/21/10 2:33 PM .7: Check if S has tow elements that sums upto X Approach . 67. Space complexity: O(n) 3. 87. 98. 0.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. index_new--. 9.

2 Problem .sort the array and keep to pointers one at beg and one at end if A[beg]+A[end] > sum then end-else if A[beg]+A[end] < sum beg++ else return (beg. Merge the two sorted sets S and S'.1 for each i in 0 to n . There exist two elements in S whose sum is exactly x if and only if the same value appears in consecutive positions in the merged output.html same for S'. constant 2 15 of 80 8/21/10 2:33 PM . end) Total Time complexity : O(n log n) Total Space complexity : O(1).Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. return max and min from each array. We will keep dividing the array in to two parts while we reached below threshold(say 10 elements or whatever u feel comfortable ). Time complexity: O(n) Total Time complexity : O(n log n) Total Space complexity : O(n) Approach -2 One more approach to this is .1 inclusive do: if A[ i ] > A[ i + 1 ] then swap( A[ i ]. constant Problem -8: You have an array. Comparision 3N/2 . Time complexity: O(n) 6. A[ i + 1 ] ) swapped := true end if end for while swapped End Total Time complexity : O(n ) Total Space complexity : O(1).9: Sorting for arrays BubbleSort( A : list of sortable items ) defined as: n := length( A ) do swapped := false n := n . Time complexity: O(n) 5. Find the maximum and minimum numbers in less number of comparisons.

j := j . int lo. lo.html InsertionSort(array A) begin for i := 1 to length[A] . constant QuickSort (int[] a. while j >= 0 and A[j] > value do begin A[j + 1] := A[j]. j--. end.1 do begin value := A[i].Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. end. j := i . hi is the upper index // of the region of array a that is to be sorted int i=lo. A[j + 1] := value. i. if (i<=j) { h=a[i]. } } while (i<=j). a[i]=a[j]. while (a[j]>x) j--. end. // partition do { while (a[i]<x) i++. } 2 16 of 80 8/21/10 2:33 PM . // recursion if (lo<j) quicksort(a. Total Time complexity : O(n ) Total Space complexity : O(1). j=hi. h. i++. j). if (i<hi) quicksort(a. hi). int hi) { // lo is the lower index. int x=a[(lo+hi)/2].1. a[j]=h.1.

j=lo.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. m). m. k=lo. k.html Total Time complexity : Avg.O(n ) Total Space complexity : O(1). Worst Case . int hi) { if (lo<hi) { int m=(lo+hi)/2. constant + It is in place sorting with good avg complexity .O(n log n ) Total Space complexity : O(n) C Implementation : Bubble Sort: 17 of 80 8/21/10 2:33 PM 2 . mergesort(m+1. // copy first half of array a to auxiliary array b while (j<=m) b[i++]=a[j++].O(n log n ). } } Merge(int lo. // copy back next-greatest element at each time while (k<j && j<=hi) if (b[i]<=a[j]) a[k++]=b[i++]. merge(lo. mergesort(lo. hi).Quick Sort can result into stack overflow because of excessive recursion MergeSort(int lo. } Total Time complexity : Avg. i=0. // copy back remaining elements of first half (if any) while (k<j) a[k++]=b[i++]. int hi) { int i. i=0. hi). int m. else a[k++]=a[j++]. j.

int i = 0. } int partition (int* A.j<n. } A[i+1]=key. i < n.i. } } Quick Sort: Very efficient version optimized for worst case and stack over flow inline int median3(const int &x. while(A[i]>key && i>=0) { A[i+1]=A[i]. j++) if (A[ i ] > A[ j ]) swap( A[ i ]. int j = n-1.j++) { key=A[j]. i=j-1. const int &y. i++) for( int j= 0. A[n-1]). A[ j + 1 ] ). int n) { for(int i = 0. for(int j=1. j++) if (A[ j ] > A[ j + 1 ]) swap( A[ j ]. } Selection Sort: extern "C" void Selection_Sort(int* A. i++) for( int j= i. j < n . int n) { for(int i = 0. A[n/2]. } Insertion Sort: extern "C" void Intertion_Sort(int* A. while(--n) 18 of 80 8/21/10 2:33 PM . int n) { int key = median3(A[0]. i--.html extern "C" void Bubble_Sort(int* A.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. int n) { int key. const int &z) { return x<y ? (y<z ? y : (x<z ? z : x)) : (z<y ? y : (z<x ? z : x)). A[ j ] ). i < n. j < n .

} } extern "C" void Quick_Sort(int* A. int ln = p+1. n). int * B = new int [lenB].indexB +1. i < lenB. for(int i = 0. int indexA = mid. int n) { while(true) { if(n < 8) { Selection_Sort(A. indexB = lenB-1. while (hi >= 0) 19 of 80 8/21/10 2:33 PM . i++) B[i] = A[indexB+i]. if(ln > rn) { Quick_Sort(A+ln. if(i < j) SWAP(A[i].Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. while(A[j] > key)j--. int hi) { int indexB = mid + 1. n = ln. A += ln.html { while(A[i] < key)i++. int rn = n-ln. rn). } else { Quick_Sort(A. int lenB = hi . return. } int p = partition(A. int lo. int lenA = hi+1. A[j]). n = rn. int mid. n). } } } Merge Sort: void Merge(int* A. ln). else return j.

int hi) { if(lo < hi) { int mid = (lo+hi)/2. hi). mid+1. } else if(indexB < 0) break. We can now do a binary search with each of the m elements in the 2 sorted set.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. Merge_Sort(A. if(indexA < 0) { while(indexB >= 0) A[hi--] = B[indexB--]. looking to see if it exists in the small one. } extern "C" void Merge_Sort(int* A. Merge(A.3 nd 20 of 80 8/21/10 2:33 PM . } } Problem 10: Give an efficient algorithm to determine whether two sets (of size m and n. mid. Merge_Sort(A. respectively) are disjoint. int lo. First sort the big set. Time complexity O(n log n) Total Time complexity : O((n+m) log m ) Approach . else A[hi--] = B[indexB--]. We can now do a binary search with each of the n elements in the big set. mid). First sort the small set.Time complexity O(n log n) 2. hi).html { if(A[indexA] > B[indexB] ) A[hi--] = A[indexA--]. Time complexity O(m log m) 2. break. Analyze the worst-case complexity in terms of m and n. } delete B.Time complexity O(m log n ) Total Time complexity : O((n+m) log n ) Approach -2 1. lo. considering the case where m is substantially smaller than n. looking to see if it exists in the big one. Approach -1 1. n>m. lo.

beg.11: Suppose that you are given a sorted sequence of distinct integers {a1. We can compare the smallest elements of the two sorted sets. 5.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. 3. For example. 4.13: You have an unordered array X of n integers. You can use extra memory. In {2. mid-1) else if(mid < A[mid]) Search(A. 7}. 6.A B C D E F 21 of 80 8/21/10 2:33 PM . ARRAY . constraint-: You can't chose 2 consecutive numbers.12: You are given an array contaning +ve integers(a[n]).Time complexity O(m log m + n log n) 2. Sort both sets. end) else return mid End Total Time complexity : O(log n ) Total Space complexity : O(1). mid+1. 7}. beg. in {−10.−3. an}. i i You may not use division. and discard the smaller one if they are not identical.html 1. a2. end): if(beg > end) return -1 mid = (beg+end)/2 if(mid > A[mid]) Search(A. Apply Binary search beg = 0 end = n-1 Search (A. Observe that once the two sets are sorted. . . Problem . . By repeating this idea recursively on the now smaller sets. 3. we can test for duplication in linear time after sorting. Find the array M containing n elements where M is the product of all integers in X except for X . Time complexity O(m) Total Time complexity : O(n log n +m log m + m) Problem . Find a sub-array from the given array whose sum is maximum. Give an O(lg n) algorithm to determine whether there exists an i index such as A[i] = i. there is no such i. constant Problem . 5. . a3 = 3. we no longer have to do binary search to detect a common element.

Let n1 be the position where x-1 fits in i. count 'candidate' in array. Now we need to prove that 'candidate' repeats more than n\2 times.html PASS 1. 22 of 80 8/21/10 2:33 PM . Approach -1 Count sort can be applied but the space complexity will be huge.1 A AB ABC ABCD ABCDE Now multiply from end of the array pASS2 . Time complexity : O( n ) Sub Problem: What if array is sorted? If array is sorted we can find that element in log(n) time. Assume the numbers appear in an array nums[n]: 1. Find majority element in 'nums' like below. A[n1] <= x-1 < A[n1+1] 3) Perform binary search for x+1. since 'candidate' is in majority.Time complexity : O( n ) MajorityElement (nums): candidate = nums[0] count = 1 for i = 1 to n-1 { if nums[i] == candidate { count = count+1 } else { count = count-1 } if count == 0 { candidate = nums[i] count = 1 } End 2. finds all the elements that appear more than n/4 times. There could be only one element in set that can repeat more than n\2 times.e.1. finds all the elements that appear more than n/2 times in the list. else there doesn't exist any such element in the array. given a list of n elements.FEDCB AFECD ABFED ABCFE ABCDF ABCDE. 1) Let x = A[N/2] 2) Perform binary search for x-1. A[n2] < x+1 <= A[n2+1] 4) If n2 . Time complexity : O(log n ) Sub Problem: Design an O(n) algorithm that.n1 -1 >= N/2. Let n2 be the position where x+1 fits in i.1 Problem .14: Design an O(n) algorithm that. It Won't be O(1) because you have you don't know whether median repeats n\2 time or not.e. then A[N/2] is the element that occured more than N/2 times. given a list of n elements.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.

6. If the key value is already present then we can just increment the counter . If it is one then it is accepted otherwise we decrement its count and take the next element from the array . If no such j occurs then print -1. Eg: Input---> A={1. we can scan the original array and for each element in the array we search it in the BST . Give an O(n log log n) worst-case time algorithm to sort such sequences. TBD -Ajeet Singh 7/1/10 12:44 PM Problem .8} Output---> 3 5 7 8 8 8 -1 if (stack is empty) push element.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.3.7. a) then again apply quicksort on 1st half with k/4 and for second half use 3k/4.18: You are given an array (unsorted) and for every element i. find the first occurrence of an element j (in the remaining array) that is greater than or equal to i. constant Problem . Approach -1 Use a temporary array of size (k-1) and scan the whole array to record the count of each element. If we can do partition of array around these three we can prove the problem easily.16: We seek to sort a sequence S of n integers with many duplications. rewrite the whole array.17: Implement an algorithm that takes an input array and returns only the unique elements in it. repeat (a) until beg < end Time complexity : O( n log k ) Space complexity : O( 1).html TBD -Ajeet Singh 7/1/10 12:44 PM Approach . Once the BST is constructed . Time complexity : O( n ) Space complexity : O( k ) Approach .2 There could be only three possible element.2 We know the range of elements (1 to k) now partition the array on median (k\2).15: Show that n positive integers in the range 1 to k can be sorted in O(n log k) time. We check its count value . Thus the order of the elements can be preserved . Problem . Construct a balanced BST using n elements . 23 of 80 8/21/10 2:33 PM .4. such that the number of distinct integers in S is O(log n). Each node can keep a counter . TBD -Ajeet Singh 7/1/10 12:44 PM Problem .5. The interesting case is when k << n.

top) { while . right. left.stack is not empty & stack. pivotNewIndex+1. pivotIndex) if k = pivotNewIndex return list[k] else if k < pivotNewIndex return select(list.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. right. right. right. k) Total Time complexity : O(Kn ) Total Space complexity : O(1).html else if(element > stack. k) else return select(list. using system stack 24 of 80 8/21/10 2:33 PM . left. k) select pivotIndex between left and right pivotNewIndex := partition(list.top < element { a = pop. if (a < element) print element } push element. left. } Time complexity : O( n ) Space complexity : O( n) Problem .19: Finding Kth Max or Min (median) in unsorted array O(Kn) time function partition(list. pivotNewIndex-1. left. } else { push element. pivotIndex) pivotValue := list[pivotIndex] swap list[pivotIndex] and list[right] // Move pivot to end storeIndex := left for i from left to right-1 if list[i] < pivotValue swap list[storeIndex] and list[i] storeIndex := storeIndex + 1 swap list[right] and list[storeIndex] // Move pivot to its final place return storeIndex function select(list.

j]) newI = i + 1 newJ = j if ((j+1 <= Q) && (M [newI. newJ] > M [i+1. newJ] > M[i. 0) and Max M (P.0) everything else is in proper condition.html Problem . j): if(i+j > p+Q) return newI = i newJ = j if ((i + 1 <= P) && (M [newI. Q). Pronlem and Solution: Young tableau Since matrix is sorted row and col wise For Example .j+1]) newI = i newJ = j + 1 if ((newI != i) || (newJ != j)) swap( M[i.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. 0] After calling re arrange except M(0. 0)) Rearrange(M[p*Q].1: Reverse a Stack in place: 25 of 80 8/21/10 2:33 PM . 0] M[0. M[newI.M (4*4) 1 5 8 20 2 6 9 24 10 12 15 30 14 16 23 40 We know min M (0.You have to print the matrix in sorted order in O(n) without using extra space.Q] while (M[0. newI. j].20: you are given a matrix which is sorted row wise and column wise. newJ) 4. Stack Problem . 0] < Max) print M[0. 0] = Max+1 rearrange M[0.0) to MinimumOf(M . PrintMatrix(M[P*Q]): Max = M [P. newJ]) Rearrange(M. Now we will try to swap M(0. i.M(0.

Push(a). } Percolate(). Push(a). Reverse(). } void Reverse() { Element a. a = Pop(). PercolateUp(). if(IsEmpty()) { Push(a).1: Implement circular queues /*class Queue { public: Queue() { cout << "Inside Queue()" << endl. b = Pop(). if(IsEmpty()) return. } 5. _front = 0. a = Pop().html void PercolateUp() { Element a. if(IsEmpty()) return. 26 of 80 8/21/10 2:33 PM .Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. Queue Problem .b. return. Push(b).

return 0. }. bool isEmpty(). int pop(). _data[_rear] = data. cout << "Queue::pushed: "<< _data[_rear] << endl. } int push(int data). bool isFull(). return -1. int Queue::push(int data){ if(!isFull()) { _rear = (_rear + 1) % _size. return _data[_front]. int _front. cout << "Queue::poped: "<< _data[_front] << endl. } } bool Queue::isEmpty() { if (_front == _rear) 27 of 80 8/21/10 2:33 PM . int _rear.html _rear = 0.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. int _data[_size]. } else { cout << "Under Flow!" << endl. ~Queue() { cout << "Inside ~Queue()" << endl. } } int Queue::pop() { if(!isEmpty()) { _front = (_front + 1) % _size. return -1. } else { cout << "Over Flow!" << endl. } private: static const int _size = 10.

} bool Queue::isFull() { if ((_rear+1) % _size == _front) return 1. pTempNode != NULL. int nCurrentElement = 0. } else if ( nCurrentElement .html return 1.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.NthNode > 0) { pNthNode = pNthNode ->pNext.1: Return Nth the node from the end of the linked list in one pass. else return 0. Node * GetNthNode ( Node* Head . } 6. int NthNode ) { Node * pNthNode = NULL. else return 0. Node * pTempNode = NULL. } } if (pNthNode ) { return pNthNode.NthNode == 0 ) { pNthNode = Head. 28 of 80 8/21/10 2:33 PM . Link-List Problem . if ( nCurrentElement . for ( pTempNode = Head. pTempNode = pTempNode->pNext ) { nCurrentElement++.

if(!L) return NULL.Iterative version with three variable Node* ReverseList( Node ** List ) { Node *temp1 = *List. Node * temp2 = NULL. constant Approach 2 Recursive reverse List recursiveReverse(List L) { List first. rest = L->next. //set the head to last node temp2= temp1->pNext. while ( temp1 ) { *List = temp1.2: Reverse a singly linked list Approach 1 .Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. } return *List. first = L. temp1 = temp2. rest. if(!rest) return NULL. // change next to privous temp3 = temp1. } Time complexity : O( n ) Space complexity : O(1). // save the next ptr in temp2 temp1->pNext = temp3. } Time complexity : O( n ) Space complexity : O(1). 29 of 80 8/21/10 2:33 PM .html } else return NULL. constant Problem . Node * temp3 = NULL.

} } Time complexity : O( n ) Space complexity : O(1). constant Approach 3 Iterative version with only one variable Swap (Node* A. A =(node *) ((unsigned long) A ^ (unsigned long) B).Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. Swap(head. } void reverse (node* head) { node *temp=NULL. B= (node *) ((unsigned long) A ^(unsigned long) B). L=rest.3: Delete a node in single non circular linked list void deleteNode(node *n) { if(n == NULL) return. } Time complexity : O( n ) Space complexity : O(1). temp). } Swap(head->next. p = NULL. while(true) { if(head->next==NULL) { head->next=temp. return L. first->next = NULL. constant Problem . break. temp).html rest = recursiveReverse(rest). first->next->next = first. if(n->next == NULL) { 30 of 80 8/21/10 2:33 PM . Node* B) { A = (node *) ((unsigned long) A ^(unsigned long) B).

} Time complexity : Avg O(1 ).next.next = list2. constant Problem .next == NULL) return list1. } delete p.4: Implement "Merge Sort" for "Link List"? line merge_sort (line list1) { if (list1 == NULL || list1.next. } } else { p = n->next n->data = p->data. n->next = p->next.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. list2 = merge_sort (list2). if (list1. n = n->next. list1 = merge_sort (list1). line list2 = list1. } line split (line list1) { if (list1 == NULL) return list1. return list2.next = split (list2. line list2 = split (list1). list2). list1. line list2) { 31 of 80 8/21/10 2:33 PM .next).next == NULL) return list1. return merge (list1. worst case O(n) Space complexity : O(1). list2.html while(n->next != NULL) { p = n.next. } line merge (line list1.

e. if (A->C > B->C) { r->c = A->C. list2). return list2. 32 of 80 8/21/10 2:33 PM . return list1. constraints: no extra space i. constant Problem .data < list2. }. Subtract (Poly* A. lists are in orders of descending powers. AddLL(r). } else { list2. we have to find difference b/w lists l1-l2. struct node{ int coeff.next = merge (list1. if (list1. int power. if (list2 == NULL) return list1. Poly* B) { while (A && B) { poly * r = new poly ().Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.next = merge (list1. O(1) space O(m+n) time complexity m and n and nodes in the lists. } } Time complexity : O(n log n ) Space complexity : O(1).next.data) { list1.next). list2. node *next.html if (&list1 == NULL) return list2.5: There are two singly linked lists l1 and l2 representing polynomials in X. r->P = A->P.

6: Evaluate a polynomial typedef struct node { 33 of 80 8/21/10 2:33 PM . } else { r->c = A->C. } } } Problem .Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. r->P = A->P. AddLL(r). } else if (A->C < B->C) { r->c = B->C. } else { r->c = A->C . AddLL(r). B = B->Next. } } while (A || B) { poly * r = new poly (). if(A != NULL) { r->c = B->C. B = B->Next. AddLL(r). A = A->Next. AddLL(r). A = A->Next.html A = A->Next. r->P = B->P. r->P = B->P.B->C. B = B->Next. r->P = A->P.

. 6) Initialize the two pointers again with the two linked lists heads.find the point of intersection in O(n) time and constant extra space. start counter. float x.having a common tail. poly->py).. }mynode. 1) Take 2 pointers. ptr1 and ptr2 2) Start moving towards tail. 8) start moving both pointers now and as soon as they hit the same node. float px. poly != head.y. } return(sum).. mynode *poly. it is the intersection.e they are in a Y shape. sum = 0.. float y) { float x. Problem . stop counter. 3) As soon as one of pointer reaches last node. 5) Now you know. poly = poly->next) { sum = sum + poly->cf * pow(x. } Problem .7: There are two link list. else fast = fast->next->next slow = slow->next 34 of 80 8/21/10 2:33 PM .i. for(poly = head->next. Loop Detection: Take two pointers Fast and Slow (Slow jumps one step at a time while Fast two step) While (Fast != NULL) if(Fast == Slow) return true.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.. float evaluate(mynode *head. so that now the lengths are equal for both.sum. struct node *next. 7) move the pointer with longer linked list by counter number of nodes. float py.html float cf. poly->px) * pow(y. what is difference in length of two list..8: Detect and remove loop in link list 1. 4) When the next pointer also reaches last node.

pTempNode = pTempNode->pNext ) { nCurrentElement++. Slow++ EndLoop 4. Node * pTempNode = NULL. Fast = Slow = Start Fast += LoopLenght Loop If Fast != Slow Fast++.html return false. Problem . if ( nCurrentElement .NthNode == 0 ) { pNthNode = Head. Loop if(Slow == Fast->next) break. else slow++ LoopLength++ EndLoop 3. 2.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.9: Return Nth the node from the end of the linked list in one pass. Loop Length: After detecting loop stop one pointer and increment other pointer by 1 step untill Loop if (fast == slow) break. pTempNode != NULL. Loop Removal:Fast and Slow Both are pointing to the start of loop position. int nCurrentElement = 0. Loop Position: You can find out loop start position also. for ( pTempNode = Head. Fast->next = NULL. Node * GetNthNode ( Node* Head . Fast = Fast->next. } 35 of 80 8/21/10 2:33 PM . int NthNode ) { Node * pNthNode = NULL.

1)) & 1 //GET MSB which is 1 for -ve Son[0] = Root -> Left. } 7. } } if (pNthNode ) { return pNthNode.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.html else if ( nCurrentElement . Tree Problem .NthNode > 0) { pNthNode = pNthNode ->pNext. Key). 2 /\ 2 3 36 of 80 8/21/10 2:33 PM . key): if root == NULL then return root res = Root->Data . create a new duplicate node. return BinSearch(Son[idx].. } else return NULL. The resulting tree should still be a binary search tree. So the tree. and insert the duplicate as the left child of the original node.. Son[1] = Root -> Right..Key if res == 0 then return root idx = (res >> (sizeof(Key) .. 2 /\ 1 3 Is changed to.2: For each node in a binary search tree.1: Implement "Binary Search" in less than two comparison? BinarySearch(root. Problem .

// duplicate this node to its left oldLeft = node->left. one empty. doubleTree(node->right). return true if they are structurally identical. node->left->left = oldLeft. how many structurally unique binary search trees are possible that store those keys.html / / 1 3 / 1 void doubleTree(struct node* node) { struct node* oldLeft. both empty -> true if (a==NULL && b==NULL) return(true). node->left = newNode(node->data). int countTrees(int numKeys) { if (numKeys <=1) { return(1).3: Given two trees. b->right) ).Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. 37 of 80 8/21/10 2:33 PM .. int sameTree(struct node* a. Recursively find the size of the left and right subtrees. } // 3. one not -> false else return(false). } Problem . // 2. b->left) && sameTree(a->right. Strategy: consider that each value could be the root. struct node* b) { // 1..4: For the key values 1. // do the subtrees doubleTree(node->left).numKeys. both non-empty -> compare them else if (a!=NULL && b!=NULL) { return( a->data == b->data && sameTree(a->left. if (node==NULL) return. } Problem .

int left. root<=numKeys. mirror(node->right). 38 of 80 8/21/10 2:33 PM . for (root=1.1).. right. } } Problem .Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. with whatever remains // on the left and right each forming their own subtrees. // do the subtrees mirror(node->left)... right = countTrees(numKeys . root. } else { struct node* temp.5: Change a tree so that the roles of the left and right pointers are swapped at every node. 4 /\ 5 2 /\ 3 1 void mirror(struct node* node) { if (node==NULL) { return.. // number of possible trees with this root == left*right sum += left*right. // Iterate through all the values that could be the root.html } else { // there will be one value at the root. 4 /\ 2 5 /\ 1 3 is changed to. } return(sum). root++) { left = countTrees(root .. int sum = 0.root).. So the tree.

i++) { printf("%d ".Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. } /* Recursive helper function -. int len) { int i. path. pathLen). for (i=0. void printArray(int ints[]. // it's a leaf. */ void printPathsRecur(struct node* node. print out all of its root-to-leaf paths. one per line. pathLen). 0). and an array containing the path from the root node up to but not including this node. } } Problem . path. i<len.given a node. int pathLen) { if (node==NULL) return. node->right = temp. // append this node to the path array path[pathLen] = node->data. } printf("\n").html // swap the pointers in this node temp = node->left. } 39 of 80 8/21/10 2:33 PM . } } // Utility that prints out an array on a line. path. print out all the root-leaf paths. Uses a recursive helper to do the work. so print the path that led to here if (node->left==NULL && node->right==NULL) { printArray(path. void printPaths(struct node* node) { int path[1000]. node->left = node->right. printPathsRecur(node->right. int path[].6: Given a binary tree. pathLen++. ints[i]). printPathsRecur(node. } else { // otherwise try both subtrees printPathsRecur(node->left. pathLen).

} else { // otherwise check both subtrees int subSum = sum . return true if there is a path from the root down to a leaf. int hasPathSum(struct node* node.7: Given a tree and a sum.html Problem . Strategy: subtract the node value from the sum when recurring down. subSum) || hasPathSum(node->right. such that adding up all the values along the path equals the given sum.node->data. return(hasPathSum(node->left. and check to see if the sum is 0 when you run out of tree. LevelOrder(Root): Queue q EnQueue(q. } } Problem . int sum) { // return true if we run out of tree and sum==0 if (node == NULL) { return(sum == 0). subSum)). else return (FindLeafNodes(root->left) + FindLeafNodes(root->right)) 40 of 80 8/21/10 2:33 PM .8: Implement "level order search" for "Binary Tree"? This problem is same as "breadth first search" for "Binary Tree".9: Find Leaf node in a tree FindLeafNodes(Tree *root) { if (root->left == NULL && root->right == NULL) return 1.Root) Loop if (q is not empty) Node t = deQueue(q) Visit(t) if (it's left child is not NULL) then EnQueue(leftChild) if (it's right child is not NULL) then EnQueue(rightChild) EndLoop Problem .Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.

else return (1 + CountElements(T->left) + CountElements(T->right)). } Program . Tree T) // To Delete whole tree recursively { if(!T) { DeleteTree(T->left).Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. } Tree DeleteTree( int x.y) ((x)>(y)?(x):(y)) int height(Tree T) { if(!T) return -1.html } Problem . else return (1 + max(height(T->left). free(T).10: Height of a tree #define max(x. else if( !T->left ) return T. DeleteTree(T->right).11: No of nodes in a tree int CountElements( Tree T ) { if(!T) return 0. 41 of 80 8/21/10 2:33 PM . else return findMin( T->left ). free up its nodes) Tree findMin( Tree T) // Recursively finding min element { if( !T ) return NULL. height(T->right))) } Problem .e.12: Write a C program to delete a tree (i.

else if( x > T->element ) T->right = DeleteNode( x. int rightDepth = maxDepth(node->right). 42 of 80 8/21/10 2:33 PM . free(tmp). } } Problem . Tree T ) // To Delete a Node with element x { Tree tmp. T->left ). T->right ). if(!T) return NULL. if( T->left ) T = T->left. T->right ). else if( x < T->element ) T->left = DeleteNode( x. } else { tmp = T. } Tree DeleteNode( int x. T->right = DeleteNode( T->element. T->element = tmp->element.html } return NULL. } else { int leftDepth = maxDepth(node->left). else if( T->right ) T = T->right.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. else if( T->left && T->right ) { tmp = findMin( T-> right ).13: Write a C program to compute the maximum depth in a tree? int maxDepth(struct node* node) { if (node==NULL) { return(0).

temp->left = NULL.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. else return(rightDepth+1). *prev. } } Problem . while(cur) { prev = cur. temp->right = NULL. } if(value > prev->value) prev->right = temp. if(root == NULL) { root = temp. temp = malloc(sizeof(mynode)). else prev->left = temp. cur = root.html if (leftDepth > rightDepth) return(leftDepth+1). temp->value = value. } else { prev = NULL.15: Tree Traversal Preorder Recursive: 43 of 80 8/21/10 2:33 PM . } } Problem . cur = (value < cur->value)? cur->left : cur->right. *cur.14: Function to add a new value to a Binary Search Tree add(int value) { mynode *temp.

while (top != 0) { root = save[--top].Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. int top = 0. if (root->left != NULL) save[top++] = root->left. } } Postorder Recursive : void postorder(mynode *root) { if(root) { postorder(root->left). if (root->right != NULL) save[top++] = root->right. root->value). preorder(root->left). printf("[%d] ". root->value). 44 of 80 8/21/10 2:33 PM .html void preorder(mynode *root) { if(root) { printf("[%d] ". } save[top++] = root. preorder(root->right). if (root == NULL) { return. } } Preorder Iterative: void iterativePreorder(mynode *root) { mynode *save[100].

// Visited left? unsigned vright :1. } } Postorder Iterative: void iterativePostorder(mynode *root) { struct { mynode *node. save[top++]. continue. } printf("[%d] ". root = root->right. save[top++]. // Visited right? }save[100].vleft) { save[top]. printf("[%d] ".vleft = 1.vright = 1. continue.node = root. unsigned vleft :1. } /* Move to the right subtree if present and not visited */ if(root->right != NULL && !save[top]. root = root->left. int top = 0. while ( top != 0 ) { /* Move to the left subtree if present and not visited */ if(root->left != NULL && !save[top].Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. root->value). root->value).html postorder(root->right).vright ) { save[top]. 45 of 80 8/21/10 2:33 PM .node = root.node = root. save[top++].

} root = save[--top].Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. /* Move up */ root = save[--top]. int top = 0.html /* Clean up the stack */ save[top]. printf("[%d] ". } } Inorder Recursive : void inorder(mynode *root) { if(root) { inorder(root->left). save[top]. root->value). } } Inorder Iterative : void iterativeInorder (mynode *root) { mynode *save[100]. while(root != NULL) { while (root != NULL) { if (root->right != NULL) { save[top++] = root->right. } save[top++] = root. inorder(root->right).node.vleft = 0.vright = 0. 46 of 80 8/21/10 2:33 PM . root = root->left.

} Problem .Contents of the nodes are irrelevant. and keeping tab of sum of elements. Given a number N...so after doing inorder traversal we will get the pattern interrms of L.P... B. root = (top != 0) ? save[--top] : (mynode *) NULL. return((ContainsSum(root->left. Problem . find a path from root to leaf which sums to N. remsum)) || (ContainsSum(root->right.html while(top != 0 && root->right == NULL) { printf("[%d] ".root->value.. that is. root->value).... root = save[--top].. Do iterative pre-order traversal.18: Given a binary tree with the following node structure struct node { //data //pointer to left subtree 47 of 80 8/21/10 2:33 PM .. A .17: Determine the largest common subtree (structurally) of two given binary trees T1 and T2. A. remsum))). the largest subtree of T1 that is structurally identical to a subtree in T2. bool ContainsSum(btree *root.. root->value). } } Problem . int N) { if(!root) return(N == 0) else{ int remsum = N .Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. } printf("[%d] ".) so find the longest common substring among the two trees traversals. we can easily determine if sum of elements from root to any of the leaves is equals to N.. We will have to modify the inorder tree traversal and put leaf as L and all inner node as p.(. Content matters.16: A binary tree contain integer values (both positive and negative) in its data field..this the one common structure.

Make a link with sblings void link(node* root) { queue<node*> q. } if(root) { if (cur->left) q. q. // since it is binary tree.push(NULL).right != NULL) 48 of 80 8/21/10 2:33 PM . keeping a marker to mark the end of a 'level' .Make the sibling pointers point to their respective nodes in O(n)time complexity Nodes from same parent called siblings.push(root). add marker q.If such a tree is given 2's sibling should point to 3 4's to 5. if(Q.push(NULL).19: Find the inorder successor and predecessor from a BST.empty() == false) { root = Q. Do BFS level order traversal 2. struct node FindSuccessor(struct node X) { if (X. } } Problem .push(cur->left). The sibling pointers are NULL for all the nodes.push(cur->right).sibling = Q. 6's to 7 1.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. q.empty() == false && root != NULL) { root..Here is is 'NULL' 3.front(). if(root == NULL) return. if (cur->right) q. while(Q. node* cur = root.html //pointer to right subtree //pointer to sibling }.pop().

} Y = X. If it exists . d) Find the successor of y. Time complexity : O(log n ) c . d .parent.html { return FindMinimumInBST(X. Storing inorder in and array of n (and taking 2 pointers j=0. } return Y .right)) { X = Y.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.20: Find two nodes in BST such that there sum is equal to X Approach -1 1. else j++.Else if sum is less than SUM then go to successor of minimum node. while(max->data>min->data) { if(max->data+min->data == sum) return(1). e) repeat steps b to d.k). Total Time complexity : O(n log n ) Total Space complexity : O(1). else if(max->data+min->data>sum) 49 of 80 8/21/10 2:33 PM . Time complexity : O(n ) Space complexity : O(n) Approach -2 a) Find the min element in the BST. Time complexity : O(log n ) b) z=x-y c) do a binary search for z in BST. } Problem .If the sum is greater than SUM then go to predecessor of maximum node.k=n-1) if(a[j]+a[k]>sum) k--. here goes a pair. while ((Y != NULL) && (X == Y. else if ( a[j]+a[k]==sum) return (j. say 'y'. Time complexity : O(log n ) b . constant Approach -3 a.Take one pointer pointing to maximum of BST.right).Take one pointer pointing to minimum of BST. Y = Y.parent.

right else: //x < curr && y < curr curr = curr.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. Node x.value = n ln. else min = inordersucessor(min). Node y): Node curr = root while !(x < curr && curr < y): // x.next = after after = ln 50 of 80 8/21/10 2:33 PM .html max = inorderpredecessor(max).left return curr // assume x and y are in the tree Common Ancestor for Binary Tree: class Node: int value Node left Node right Node parent class ListNode: Node value //Node is Binary Tree node ListNode next Node getLCA_BT(Node root. Node x. Node y): ListNode lx = getPath(x) // Get list of path ListNode ly = getPath(y) // Get list of path return getLCAFromPaths(lx.value if curr < x && curr < y: curr = curr. } Problem .21: Find common ancestor in a binary tree in less than O(n log n) in constant space? Common Ancestor for BST: Node getLCA_BST(Node root. ly) // find largest match ListNode getPath(Node n): ListNode ln = null ListNode after = null while (n != null): ln = new ListNode() ln.value < curr.

int val) { if(!root) return NULL. node* nextBig = NULL.html n = n.value lca = lx.value. will find the next biggest node value in the tree node* NextBigNode(node* root. } // If value at current node is LESS than value. } 51 of 80 8/21/10 2:33 PM .value //or ly. ListNode ly): Node lca = null while (lx. then // Go to the right subtree of current to see if there is another potential candidate for nextBig else { cur = cur->right. then current could be the potential candidate for nextBig // Go to the left subtree of current to see if there is another potential candidate for nextBig if(cur->data > val) { nextBig = cur.value == ly.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.value lx = lx.next ly = ly. node* cur = root.22: Write a function that. cur = cur-> left. while(cur) { // If value at current node is GREATER than value.value): // lx. } } return nextBig.next return lca Problem .parent return ln Node getLCAFromPaths(ListNode lx. given a binary search tree and a value.

Algorithms and Data Structures

ﬁle:///Users/xianghaochen/Desktop/View.html

Problem - 23: Given a binary tree, write a program to find the maximum number and print its path from the root. int maxsofar, maxpos; //global variables Inorder(node *n, int position) { Inorder(n->left, position*2); if(n->data > maxsofar) { maxsofar = n->data; maxpos = position; } Inorder(n->right, position*2 + 1); } By the end of this traversal, you'll have the maximum value in "maxsofar", and the position encoded in an integer "maxpos". If you don't have parent pointer support in tree node structure, You can print the path like below suppose the maxpos is 23, 1<-2<-5<-11<-23/2 root->left->right->right->right Now to print the path of max value 1. Array[(maxpos/2)+1] 2. i = 0 3. Loop while (maxpos > 1) { maxpos =/2 Array[i++] = maxpos } 4. while (--i >= 0) { print (root->data) if (i %2 == 0) root = root->left; else root = root->right } Problem -24: Construct a "Doubly Link List" form a given "Tree". void TreeToDlinklist(Tree* pNode):

52 of 80

8/21/10 2:33 PM

Algorithms and Data Structures

ﬁle:///Users/xianghaochen/Desktop/View.html

{ Tree* pWalk; if (pNode != NULL) { TreeToDlinklist(pNode->pLeft); pWalk = node->pRight; AppendToList(pNode); TreeToDlinklist(pWalk); } }

8. General Programing

Problem - 1: You have an array consisting of 2n+2 elements, n elements in it are married, i.e they occur twice in the array, however there are two element which only appears once in the array. You need to find those numbers assuming that all are positive numbers in O(N) time and O(1) space complexity. Assume Array elements (array): 1 2 3 4 5 6 7 8 0 10 11 12 13 0 15 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Now we are having 30 numbers. Each number is repeated exactly two times except a (9) and b( 14). 1. Get the XOR of each value in array res = array[0] for i = 1 to N-1: res = res ^ array[i] 2. Take leftmost set bit of this "res" (call it Y) 3. Mask is Y, now XOR all elements which are greater or equal than mask. result would be missing number "b" (14). 4. Now XOR this "b" with your earlier "res". result would be missing number "a" (9).

Problem - 2: Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1 using only one call to strstr "C" routine? (eg given s1 = ABCD and s2 = CDAB, return true) (given s1 = ABCD, and s2 = ACBD , return false) strstr(strcat(s1,s1), s2); so if the string is ABCD, the concatenation will make it ABCDABCD and hence any rotation will fall within the concatenated string

53 of 80

8/21/10 2:33 PM

Algorithms and Data Structures

ﬁle:///Users/xianghaochen/Desktop/View.html

Problem - 3: Find number of zeros in n! ? num_zeros = floor(n/5) + floor(n/5^2) + floor(n/5^3) ... The logic is straight forward. There will be as many zeros as there are no of 5s in the numbers, as 5 * 2 = 10 and num(5) < num (2) .Note that these 5s also include the multiples of 10. So we don't need extra logic for them int zeros = n/5; // round down to nearest integer while(zeros > 0) { zeros += zeros/5; } Problem - 4: Arrange the following pattern a0 a1 a2 a3 a4 a5 a6 bo b1 b2 b3 b4 b5 b6 as a0 b0 a1 b1 a2 b2 a3 b3 a4 b4 a5 b5 a6 b6 with minimum time and memory complexity. This problem can be solved using recursion. We will be traversing whole pattern from 0-(n-1) recursively in order to push all the data in program stack. and while stack unwinding we will arrange data in the desired pattern. Following is C++ implementation of the fiven problem const int size = 12; int len = size; string str[size] = {"a0", "a1", "a2", "a3", "a4", "a5", "b0", "b1", "b2", "b3", "b4", "b5"}; void move(string a, string b, int ip,int jp) { if(jp >= len-1) { str[--len] = b; str[--len] = a; return; } ip++; jp++; move(str[ip], str[jp], ip, jp); if (len > 0) { str[--len] = b; str[--len] = a; } return;

54 of 80

8/21/10 2:33 PM

Algorithms and Data Structures

ﬁle:///Users/xianghaochen/Desktop/View.html

} int main () { move("","",-1,(size/2)-1); cout << "\n Output Array: "; for (int index = 0; index < size; index++) { cout << str[index] << " "; } return 0; } Problem - 5: Give a sorting algorithm that sorts 3 (distinct) numbers using 3 comparisons in the worst case? void max (int a, int b, int c) { if (a < b) if (b < c) cout << "sorted form small to large:" << a <<" "<< b <<" "<< c; else if (a < c) cout << "sorted form small to large:" << a <<" "<< c <<" "<< b; else cout << "sorted form small to large:" << c <<" "<< a <<" "<< b; else if( c < b) cout << "sorted form small to large:" << c <<" "<< b <<" "<< a; else if (c < a) cout << "sorted form small to large:" << b <<" "<< c <<" "<< a; else cout << "sorted form small to large:" << b <<" "<<a <<" "<< c; } Problem - 6: Write atoi and itoa function with all test cases. char* itoa(int x) { int i = x < 0 ? 3 : 2; int t = abs(x); while (t = t / 10) ++i; char* s = new char[i];

55 of 80

8/21/10 2:33 PM

string::const_iterator it = v.. bool find (string [n] = 'micosoft'. we need to find out whether a given string("microsoft") exists in the given matrix.ot. it can also be in this form. t = abs(x). if(v[0] == '-') sign = -1.but NOT diagonal. maze[P * Q] = array....begin().(like the snake in the cell games ) m.f.7: There exists 2D char array. } Problem . return s.html s[--i] = '\0'. while (i) s[--i] = '0' + (t % 10). } i = (i << 3) + (i << 1) + (*it-'0').Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.. c. int i. if (x < 0) s[0] = '-'. continue. int j) { if (pStr > n) retrn FOUND 56 of 80 8/21/10 2:33 PM .end()) { if(*it == '-') { it++. . int pStr... ir. . t = t / 10.. while (it != v. int i = 0.. } return i*sign.. it++. } int AtoI(const string& v) { int sign = 1. the string can be vertical or horizontal.

j). maze. count++.8: Find square root of an integer. pStr. j] == string [pStr]) { pStr++. } Problem . pStr.i+=2) { sum+=i. } else { if(i == P && j < Q) { i = 0. } return (count).Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.empty() || str2. } } } Problem . i+1 .html if (i*j > P*Q ) return NOT_FOUND while (I*J < P*Q) { if(maze[i. j + 1).9: Find Longest common substring. find (string. maze. Sq_root(n) { count=0. const string& str2) { if(str1. find (string. i . int LongestCommonSubstring(const string& str1.sum<=n.empty()) 57 of 80 8/21/10 2:33 PM . for(int i=1. j++ } else if( i < P && j < Q) i++.

} //The next if can be replaced with: //maxSubstr = max(maxSubstr.size()]. } else { if(i == 0 || j == 0) { curr[j] = 1. return maxSubstr. ++i) { for(int j = 0. curr=prev.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. 58 of 80 8/21/10 2:33 PM .size(). } delete [] curr.size()].html { return 0. j<str2. for(int i = 0. int maxSubstr = 0. } } } swap=curr. i<str1. delete [] prev. table[i][j]). int *prev = new int [str2.h library for using max()) if(maxSubstr < curr[j]) { maxSubstr = curr[j]. } else { curr[j] = 1 + prev[j-1]. int *swap = NULL.size(). } int *curr = new int [str2. //(You need algorithm. ++j) { if(str1[i] != str2[j]) { curr[j] = 0. prev=swap.

int count =0.486999999999995" to approximate it.6 so the loop will go on. n*=1 Case ..0000001 && n-(int)n<0. -1 if outside. I guess If P is on the triangle the sum would be 180..B.C are the vertices.10: Given three points of a triangle and one arbitrary point.56 and multiply with 10. int count = 0.best way to do is convert to string and do it. Lets say ur input number = 10. In the IEEE 754 Specifications. This wont work for point on the triangle. the number indicated by float in c is "73.0000001)){ count++. int isInside(Triangle. APB and BPC. TBD -Ajeet Singh 7/1/10 12:44 PM Problem . The 7 bits indicate the mantissa.000 output=0 double no =3. on or outside the traingle. if given 3.1 If P is the point to be tested.487 in float type. while (!(n-(int)n>-0. no=no*10. There are some numbers that can not be indicated by float type. a 32 bit float is divided as 24+7+1 bits.5999999998 instead 102345. for example. e.23456. point). and A.23456 once u r @ 10234. case -1 double n=1. in floating point number.g.html } Problem .44. never complete. there is no 73. the point is inside. not. while(no!=((int)no)) { count++.count). the next number comes as 102345. } printf("%d". determine whether that point lies inside. find angles APC. 0 if on the traingle Sol. and thts the behavior of double and float.11: How do you compute the number of digit after . But simple and can be used. Else.2 59 of 80 8/21/10 2:33 PM . If the sum of angles is equal to 360. /return 1 if inside. need to check.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.554 output=3 for 43.

i++) { if((set[begin] !=s et[begin+i]) || ( i==0)) { swap(&set[begin]. swap(&set[begin]. set). gets(s). &set[begin+i]). char *s. &set[begin+i]). int end) { int i.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. return 0. } /* set back */ } } } 60 of 80 8/21/10 2:33 PM .begin. end). } else { for(i=0.12: Permutation of string. } Problem . if (range == 1) { printf("set: %s\n". while(*s++) { if(*s++=='. begin+1.') while (*s++) { count++. } } cout<<count.html #include<iostream> using namespace std. i<range. int main() { int count=0. permute(set. int begin. int range = end . void permute(char* set.

here we do a lot of rework in calculating the values for calling the functions. Approach . You should take all the possible scenorios and write an efficient code it I hope stack will work in this case... return fibo(nth-1. 61 of 80 8/21/10 2:33 PM .num1+num2) } One more drawback with the recursive approach apart from the drawback of using the stack is that.num2.1 1) Associate a Prime number with each letter. if the string is {adbc(xyz}the) bad string.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. 2) Hash by product of the word letter. of corresponding braces. brackets and parathesis.bad string {abs{jeu} .15: fibonanci int fibo(int nth.int num1. For ex: {abcdteeh} . And when we get any closing bracket then we will check whether the top element of the stack is opening bracket of current closing otherwise there is some error. if(n==2) return num2. For e. 3) Maintain a list of words for each key 4) Iterate and print all lists having more than one word But this wont work if word is very long since it will cause overflow Problem .good string (bans{xyzhs}aj) . Problem . When we get an opening bracket then we add that bracket in the stack. For example. Space is the only seperator.13: Given a string and print the words which have the same exact letters.bad string If the string contains the equal no. int num2) { if(n==1) return num1. Moreover. abc bbe abcd derwe eeb will print nothing.html Problem .g: while calculating f(5). Thus we calculate the same value again which is nothing but waste of resources. we calculate values for f(4) and f(3) and while calculating the value of f(4). abc bbe bca derwe eeb it will print abc bca.14: Write a program to determine whether it is a good string or bad string. This is actually a problem of dynamic programming. we again calculate f(3).good string }this{ .

else { int k = 2. [F2] [1 0] 2 [1 [1 0] * 1] [ F0] [F1] [1 = 0] * [F1] = [F2] [F0] * [F3] [1 1] [1 1] [F1] [Fn] = [Fn+1] [1 1] [1 0] n [F0] * [F1] If you solve this 62 of 80 8/21/10 2:33 PM . } } Is there a faster way to compute the nth Fibonacci number than by fib2 (page 13)? One idea involves matrices. } return sum. f1 = f2. We start by writing the equations F1 = F1 and F2 = F0 + F1 in matrix notation [ F1] = [ F2 ] Similarly.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. if (n == 1) return 0. int f2 = 1. f2 = sum. else if (n == 2) return 1.html int FindnthFibonacciNumber(int n) { int f1 = 0. k++. int sum = 0. while (k < n) { sum = f1 + f2.

Problem . When Data is more. // because we are fororming invalid string if ( closed > n || open > n ) return . . n ) . n ) . lookup the prefix in the trie for all three letters whenever a key is pressed Problem .18: Give an algorithm to find all valid permutation of parentthesis for given n for eg for n=3 {}{}{} {{{}}} {{}}{} {}{{}} base condition : if ( closed > open ) return . int n ) { if ( closed > open ) return . if ( str.When data are comparatively less. closed . 0 . fun ( str + ')' . E. how do I store a text file containing a dictionary on a cell phone and efficiently read from it. open+1 .17: To design the T9 system.. int open . fun ( str + '(' . void fun ( string str . closed+1 . } main() { fun ( "(" . 1 .Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.Insertion/Deletion are not frequently required. if ( closed > n || open > n ) return . open .length == 2*n) then print str.html Fn = Problem . .When Data is in ascending/descending order .Sorted sequence is not required. Hashing might require more extra location to avoid Collision. . int closed . which is the predictive text system on cell phones.g type 49556 and get "hello" and also other words that matches 49556. More specifically. check if (str. // initially no of open paranthesis is 1 and closed is 0 } 63 of 80 8/21/10 2:33 PM .size() == 2*n ) print str .16: Hash Table is recommended over Binary Search Tree .Searching is a prevalent operation. n ) . I would keep the dictionary in a trie ..

Maybe we can just implement the iterative version of the code as it avoids recursion overhead and is also as ituitive as the recursive version Approach . int denom) { if (numerator < denom) { return 0. else { while(dividend >= divisor) { dividend-=divisor.divisor) { int count = 0. denom)... } else { return 1 + getQuotient(numerator . } What if numerator = -100 and denom = 10 ??? #define sign(v) (+1 | (v >> (sizeof(int) * CHAR_BIT . result_sign = sign(numerator) * sign(denom). I would say recursion would be a overkill for such small operation. 64 of 80 8/21/10 2:33 PM . } } return count.2 public int getQuotient(int dividend. count++.1))). if(dividend < divisor) return 0.19: Implement Devision Approach .denom.1 int getQuotient(int numerator.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. } } The algo is perfect but for the fact you need to call the function getQuotient instead of divide in the last line of code.html Problem . else if(divisor==0) return error.

scanf("%d%d". abs(denom)) Approach . q = q + 1.&d).q=1. } 65 of 80 8/21/10 2:33 PM . int sign = 1.html return result_sign * getQuotient(abs(numerator).3 int main() { int n.d. sign = -1. } else if(d<0) { d = -d. sign *= -1. } while((t+d)<=n) { t = t + d.&n. /* n: numerator d: denominator q: quotient t: temp variable sign:sign of quotient */ printf("Enter the numerator and denominator:"). q = q<<1.t. if((n!=0&&d!=0)&&(d<n)) { while(((t<<1)-n)<0) { t = t<<1. if(n<0) { n = -n.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. } t = d.

} Problem .Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. and the low-order byte at the highest address.) For example. (The big end comes first..q*sign). would then be stored as: Base Address+0 Byte3 Base Address+1 Byte2 Base Address+2 Byte1 Base Address+3 Byte0 Problem . a 4 byte LongInt Byte3 Byte2 Byte1 Byte0 will be arranged in memory as follows: Base Address+0 Byte0 Base Address+1 Byte1 Base Address+2 Byte2 Base Address+3 Byte3 Intel processors (those used in PC's) use "Little Endian" byte order..) Our LongInt.. } return 0. "Big Endian" means that the high-order byte of the number is stored in memory at the lowest address. }//end of if(n!=0. if(d) printf("%d is the quotient\n".html } else if(n==0) { q = 0. As per my understanding if the input is ABCDEEDCFFCDE Two palindrome exist in this string CDEEDC EDCFFCDE So the largest palindrome is EDCFFCDE 66 of 80 8/21/10 2:33 PM . (The little end comes first. else { printf("Exception:Tryin to do divide by zero\n").20: "Little Endian" means that the low-order byte of the number is stored in memory at the lowest address. and the high-order byte at the highest address.21: Finding the largest palindrome you can easily modifying this algo finding largest even palindrome and odd palindrome.

html Logic: Start reading char from left and push into the stack We set two pointers one is stack pointer and another is match pointer If the current char match with the char pointed by match pointer then we increase count var and decrease match pointer else we set match pointer = stack pointer and set count = 0 First read A 0A Stack Pointer = 0 Match Pointer = 0 count = 0 Max count = 0 Result = “”. since E = [matchpointer] read D 6d 5e 4e 3d 67 of 80 8/21/10 2:33 PM . D . read C. read E 5e 4e 3d 2c 1B 0A Stack Pointer = 5 MatchPointer = 3 count = 1 Max count = 0 Result = “e”.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.E 4e 3d 2c 1B 0A Stack Pointer = 4 MatchPointer = 4 count = 0 Max count = 0 Result = “”. read B 1B 0A Stack Pointer = 1 MatchPointer = 1 count = 0 Max count = 0 Result = “”.

since d = [matchpointer] read F 8F 7C 6d 5e 4e 3d 2c 1B 0A Stack Pointer = 8 MatchPointer =1 count = 3 Max count = 0 Result = “edc”.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.And we can subdivide them in 2 catego 68 of 80 8/21/10 2:33 PM . Now start reading and find for another palindrome if we found other palindrome whose count is greater then max count then we store that string in result. Since f not equal to stack [matchpointer] that means we got palindrome string of length = count*2 =6 We set Max count = 6 And change result = “cdeedc” And set matching pointer = stack pointer = 8.html 2c 1B 0A Stack Pointer = 6 MatchPointer = 2 count = 2 Max count = 0 Result = “ed”. since d = [matchpointer] read C 7C 6d 5e 4e 3d 2c 1B 0A Stack Pointer = 7 MatchPointer = 1 count = 3 Max count = 0 Result = “edc”. At the time of finding palindrome in this way we can easily find either it is odd or even palindrome.

for (int i = 0. ++i) semaphore++. void ReaderThread::run() { ..html Problem .. End--.. Once done..23: Reverse a string void ReverseString (char *String) { char *Begin = String.22: Implement a reader writer lock.1. } void WriterThread::run() { . semaphore--. . i < MaxReaders. read_file().. mutex. Begin++. mutex. } Problem .Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. semaphore -= MaxReaders. } } 69 of 80 8/21/10 2:33 PM . (multiple readers. char TempChar = '\0'. also implement upgrade and downgrade of the locks. *Begin = *End. while (Begin < End) { TempChar = *Begin... *End = TempChar. .unlock(). semaphore++. char *End = String + strlen(String) .. one writer).lock(). write_file().

25: Angle between clock A general approach to such problems is to consider the rate of change of the angle in degrees per minute. Equation for the degrees on the hour hand (0. 'Example: The time is 1:35' 1:35 is 1(60)+35=95 minutes past noon.5*95))=cos (cos(522. This is equivalent to 360 degrees in 720 minutes or 0.95372)=162. The minute hand turns 360 degrees in 60 minutes or 6 degrees per minute.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.26: Sorting order Sort Average Best Bubble sort O(n^2) O(n^2) Worst O(n^2) Space Stability Remarks Always use a modified bubble sort Stops after reaching a sorted array Constant Stable Modified Bubble O(n^2) sort O(n) O(n^2) Constant Stable 70 of 80 8/21/10 2:33 PM .5 degrees between the hands -1 -1 -1 -1 Problem . The hour hand of a normal 12-hour analogue clock turns 360 degrees in 12 hours.5))=cos (-.5 degrees per minute on the hour hand) * (the time on the hour hand * 60 minutes per hour) + (0.html Problem .5*24)=162 degrees The degrees on the minute hand is 6*24=144 degrees Angle between hands = 162-144 = 18 Equation for the degrees between the hands The angle between the hands can also be found using the formula cos (cos(5.(unsigned long)(char *)(type *)0 Problem .5*5*60)+(0.24: Sizeof operator (unsigned long)(char *)((type *)0+1) .5x)).5 degrees per minute. where x=the number of minutes past noon.5 degrees per minute on the minute hand) * (the time on the minute hand) Equation for the degrees on the minute hand (6 degrees per minute on the minute hand) * (the time on the minute hand) 'Example: The time is 5:24' The degree on the hour hand is (0. This will always give an angle between 0 and 180 degrees. cos (cos(5.

merge sort requires constant space Insertion O(n^2) Sort O(n) O(n^2) Constant Stable Heap Sort O(n*log(n)) O(n*log(n)) O(n*log(n)) Constant Instable Merge Sort O(n*log(n)) O(n*log(n)) O(n*log(n)) Depends Stable Quicksort O(n*log(n)) O(n^2) Constant Stable Randomly picking a pivot value 71 of 80 8/21/10 2:33 PM . on linked lists. merge sort requires O(n) space.html Selection O(n^2) Sort O(n^2) O(n^2) Constant Stable Even a perfectly sorted input requires scanning the entire array In the best case (already sorted). every insert requires constant time By using input array as storage for the heap.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. it is possible to achieve constant space On arrays.

} int sub (a. there are no negetive numbers. b) You can set a variable = another variable. v++. so you can't count on truncating at any point. d) You can loop. You can use as many variable as you need. There are NO comparisons allowed.27: You have an abstract computer. and its a post increment. (i) Write a function that decrements by 1. Problem . this one only does what i'm about to tell you it does. loop(b) { r = v. your loop would execute 10 times.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. they could be infinitely large. if you were to say loop(v1) and v1 = 10. You need to do 2 things. no if statements or anything like that. c) You can increment a variable(only by 1). So. You do not know the size of the integers. int Dec1 (b) { r = 0. but the value in v1 wouldn't change so the first line in the loop can change value of v1 without chaning the no of times you loop. There are only four operations you can do on a variable. b) 72 of 80 8/21/10 2:33 PM . v = 0.html (or shuffling the array prior to sorting) can help avoid worst case scenarios such as a perfectly sorted array. all numbers are integers. (ii) Write a function that subtracts one variable from another. a) You can set a variable to 0. so just forget everything you know about computers. } return r.

} int dev (a. The smallest counterexample with composite P + 1 is (2 × 3 × 5 × 7 × 11 × 13) + 1 = 30. H. loop(b) { r = dec1(r) } return r. loop(a) loop(b) count++ return count. b) { mul = 0. That conclusion relies on a hypothesis later proved false. then it is not divisible by any primes and "is therefore itself prime" (quoting G. and think that Euclid's proof says the prime product plus 1 is always prime.html { r = a. Then it is asserted that if P + 1 is not divisible by any members of that set.031 = 59 × 509 (both primes). Many more proofs of the infinity of primes are known. b) { } Problem . This sometimes leads readers to conclude mistakenly that if P is the product of the first n primes then P + 1 is prime. 73 of 80 8/21/10 2:33 PM . and so cannot be considered proved. This confusion arises when the proof is presented as a proof by contradiction and P is assumed to be the product of the members of a finite set containing all primes. Adding the reciprocals of all primes together results in a divergent infinite series: [10] Fermat's little theorem is used to test the primality .Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.28: Prove there are infinite numbers of prime The proof is sometimes phrased in a way that falsely leads some readers to think that P + 1 must itself be prime. } int mul(a. Hardy ).

int thisSum = 0.html Problem . S++. p2 3.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. int maxSum = 0.30: Remove duplicate elements in a string. while (j < N) { 74 of 80 8/21/10 2:33 PM . p1 = p2 = str[0] 4. Now take two pointers for array say p1. 1. int i=0. int seqStart = 0. } } Problem . Write a routine in C for the above.microsoft in O(n) and without using extra memory. p2++ 5. int j=0. Read string using pointer p1 check if (int)*p1 bit is set in I a) if Yes p1++ b) if No set (int)*p1 bit in integer I using bitwise operator p1++. *(p2++) = '\0' Problem .29: Covert a string to upper case void ToUpper(char * S) { while (*S!=0) { *S=(*S >= 'a' && *S <= 'z')?(*S-'a'+'A'):*S.31: leap year //Use this if() condition to check if a year is a leap year or not if(year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) Problem .32: You are 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). Save occurrence of a particular character using 32 bits of an integer I 2. seqEnd = N-1.

int i. t = (t* t)%n. while(u) { if(u&1) s = (s* t)%n.33: (x pow y) mod N unsigned long qe2(unsigned long x. return ((tmp* tmp)%N). thisSum = 0.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. s = 1.html thisSum =thisSum + a[j]. seqStart = i.N). } printf ("%d->%d\n".y/2. } return(s). } Another. unsigned long n) { unsigned long s. seqStart. } j=j+1.(y-1)/2. if ((y&1)==0) { tmp = fast_exp(x. algorithm is: unsigned long fast_exp(unsigned long x.N). if( thisSum > maxSum ) { maxSum = thisSum. tmp = (tmp* tmp)%N. } else { tmp = fast_exp(x. seqEnd). t = x. u = y. unsigned long y. unsigned long y. recursive.t. 75 of 80 8/21/10 2:33 PM . unsigned long N) { unsigned long tmp. } else if( thisSum < 0 ) { i = j + 1.u. if(y==1) return(x % N). u>>=1. seqEnd = j. Problem .

. x2. /* optimization. i<m. int *x) { size_t i. y = g. ++i) { g = gcd(g. } } This algorithm can be generalized to return the gcd of an array of m numbers: /* returns the gcd of x1. if (y < 0) y = -y. since for random x[i]. if (x + y == 0) ERROR. while (x > 0) { g = x.xm */ int multiple_gcd (int m. if (x < 0) x = -x. g==1 60% of the time: */ if (g == 1) return 1.34: Returns gcd of x and y int gcd (int x. return (tmp). 76 of 80 8/21/10 2:33 PM . if (m < 1) return 0. x = y % x. } } Problem .Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. } return g. g = x[0]..html tmp = (tmp* x)%N. int y) { int g. for (i=1. g = y. int g. x[i]).

// memcopy() would have done this directly. and may therefore be more efficient to implement.35: Implement MemMove and MemCopy memmove() offers guaranteed behavior if the source and destination arguments overlap. 77 of 80 8/21/10 2:33 PM . void *mymemmove(void *to. p2 = p2 + size. It's always safer to use memmove(). const unsigned char *p2. size_t count).html } return g. p2 = (const unsigned char *) from. p2 = p2 + size. } } else { // No overlap OR they overlap as CASE 2 above. memcpy() makes no such guarantee. const void *from. } Problem . p1 = (unsigned char *) to.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View.!= 0) { *--p1 = *--p2. // Check if there is an overlap or not. p1 = p1 + size. void *memmove(void *dest. size_t size) { unsigned char *p1. while (size-. while (p2 != from && --p2 != to). if (p2 != from) { // Overlap detected! p2 = (const unsigned char *) from. const void *src.

First 5 races: divide 25 horses into 5 groups and that gives you 5 winners now race 5 of them that will tell u which two are the bottom most group. find the no. Race them u get ur top 3 Problem .2. The defective bag will be Sumation(10)*10 . But there is one bag that contains false coin weighing one gram less than original coin.html while (size-. i.2: There are 25 horses which runs at different speed.. The answer is 7.3rd place. of races required minimum. Puzzle Problem .e. Take 1 coin from First bag 2 from second and so on. In 2 weighings how do you find the defective one? First take 6 balls.3: You have 8 balls. placing each ball on each side. Problem . the horse that came 2nd. If the balance is balanced.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. You have a balance to measure balls against each other. the 78 of 80 8/21/10 2:33 PM .w'. 3 in each side. } 9.There is a digital weighing M/C that tells the weight of things. his group can only bid for 3rd place so we take him for next level. the horse that came first . his group can bid for 1. Reject them Now consider first 3 groups the horse that came 3rd . his group can bid for 2& 3rd spots we take 2 from this group. in one race you can race not more than 5 horses. weight the accumulated coins w'. One of them is defective and weighs less than others. then weigh the other two balls.!= 0) { *p1++ = *p2++. and you have to find out the top three horses. } } return(to). find out the defective bag in one weighing. so we need only to take 2 from this group so that leave us with 5 horses. but we have already got our first.1: You have 10 bags full of gold coin each coin weighing 10 grams. You will get the defective ball.

Now suppose the first egg breaks in the second attempt. 79 of 80 8/21/10 2:33 PM . You must identify the lowest floor for which a marble will break if you drop it from this floor. 77. I. It can be done in 14 trail Here is the right reasoning. Keep one ball from the three aside. Then we only have 'n-1' attempts left (to do with the second egg). 50. Put the two balls on 2 sides. the 'n' we seek is the smallest 'n' such that n+(n-1)+(n-2)+(n-(n-2))>=97 => n*(n+1)/2 >=98 The smallest such n is 14. 27. After the second attempt.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. 84. The first attempt was done from the 'n'-th floor. 99 The worst case number of drops is 14. we want the last two floor to be 97 and 100. Problem .html one which is weighing less. 69. For the optimum 'n'. Continuing this way. which is the answer we seek. the ball kept aside will be the defective one. Therefore the first egg must be dropped from the 'n'-th floor. So the first egg is dropped from the following floor (starting the counting from 1): 14. we only have 'n-2' attempts left (to do with the second egg). Now suppose the first egg breaks in the first attempt. or as close as possible (so as not to waste drops). Suppose that the optimum number of steps (in the worst case) is 'n'. If balance is not balanced in the 1st case. 95.4: You have a 100-story building and a couple of marbles. We do not know what 'n' is.e. the third attempt (if the first egg survives the first two falls) must be from the [n+(n-1)+(n-2)]-th floor. when 6 balls are taken. then take the group of three balls which weigh less. If the 2 balls are of equal weight. 60. 90. How fast can you find this floor if you are given an infinite supply of marbles? What if you have only two marbles? Asymmetric Binary search.. 39. Therefore the second attempt must be from 'n+n-1=2*n-1'-th floor. otherwise the ball weighing less will be the defective one.

B4 Weigh 2 . either A1 or A2 is heavy or B1 is light. If X was equal to Y Weigh 3 . we will do 3rd weigh Weigh 3 .C each has 4 balls.A with B. Whichever is lighter is answer. If equal. B is light Divide in 3 groups X = A1. These solutions have been taken from community and web search any usage of these algorithms is on your own risk.2010. its the answer.Algorithms and Data Structures ﬁle:///Users/xianghaochen/Desktop/View. If A = B.B2. pretty simple take 3 from A and 3 from C.Weigh A1 with A2 Whichever is heavy. If equal.Aug. Last Modified: 01.C1 Z= A4. A.5: You are given 12 coins.B. Identify this coin in just three weighings. If X is heavy.Weigh B2 with B4.html Problem . A4 is heavy and is defective. A3 is heavy and defective. then we know the answer. author is not responsible for any incident. B1 is answer. 80 of 80 8/21/10 2:33 PM .A3. either A3 is heavy or 3 could is light.A2.B3 Y= B1.Weigh X with Y If Y is heavy. rest is easy A is heavy.12:01 AM Disclaimer: I have tried not to put any patented information on this document but in case you find any thing offensive please mail me. we have 4 balls and 2 weighs. Weigh 1 . One of them is heavier or lighter than the rest.

Are you sure?

This action might not be possible to undo. Are you sure you want to continue?

We've moved you to where you read on your other device.

Get the full title to continue

Get the full title to continue reading from where you left off, or restart the preview.

scribd