Saturday, April 9, 2011

Given an Array A, calculate Array B, where B[i] contains the product of all values of Array A except A[i]

Input:
6 5 4 1 2


Output:
Printing the input Array:
6 5 4 1 2
Printing B:
1 6 30 120 120
Printing C:
40 8 2 2 1
Result Array values:
40 48 60 240 120


Code:

Find an element in a matrix, whose rows are sorted left to right and cols are sorted top to bottom

Input:
3
3
1 2 3
4 5 6
7 8 9
7
Output:
1 2 3
4 5 6
7 8 9
KEY:7
Key Search? true


Code:

Infix Order of a BinaryTree

Print a binary tree in infix order. Recursive and iterative.

Output:
These nodes are inserted into BST:
16 39 43 65 56 77 22
Printing BST inorder:
16 22 39 43 56 65 77
Printing infix order iteratively:
16 22 39 43 56 65 77

Code:

Binary search on a sorted, but rotated array.

An element in a sorted array can be found in O(log n) time via binary search. But suppose We rotate the sorted array at some pivot unknown to us beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Now devise a way to find an element in the rotated array in O(log n) time.

Idea:
idea: look at end of array. if the last item is smaller than the key i am searching for and key is less than the mid value, then the array is rotated. this means you need to search for items in the lower part of the array.


i.e. array = (456123) val = 5


else look at the beginning of array. if the first item is bigger than the key i am searching for and key is greater than the mid value, then the array is rotated. this means you need to search for items in the upper part of the array.


i.e. array = (67812345) val = 4


otherwise, the array is not rotated. so, you can proceed with normal binary search.


i.e. array = (12345678) val = any number




Input:
9 2 3 4 5 6 7 8


Output:
Elements in Array:
9 2 3 4 5 6 7 8
Searching for key: 3
Search result: true


Code:

Friday, April 8, 2011

Reverse Stack In Place

Reverse a stack in place.

Input:
3 4 5 6 7


Output:
Original stack:
3 -> 4 -> 5 -> 6 -> 7 -> Null
Reversed stack:
7 -> 6 -> 5 -> 4 -> 3 -> Null

Monday, April 4, 2011

Stack Sorting in place.

Sort the stack in place.

input:
5
3
5
4
1
2
output:
Sorted Stack:
5 4 3 2 1


Anagram sets from dictionary

Find all the anagram sets from given list of words.

Input:
5
cat
eat
act
tea
ate
output:
Anagram sets are:
eat tea ate
cat act