Saturday, January 5, 2013

Search in Sorted but Rotated Array

Given a sorted array that is sorted by rotated, find a given number. For example take an array: 1 3 8 10 12 56 and rotate it so you have 10 12 56 1 3 8 and then find a candidate e.g. 3 in it.


Input/Ouput:

Array:
10 12 56 2 3 8 9
3 is present at index: 4

Get Sentence from raw text


String getSentence(String text, Set<String> dictionary);

// text is a string without spaces, you need to insert spaces into text, so each word seperated by the space in the resulting string exists in the dictionary, return the resulting string

// getSentence("iamastudentfromwaterloo", {"from, "waterloo", "hi", "am", "yes", "i", "a", "student"}) -> "i am a student from waterloo"


Approach:
String [] tokens = {"from", "waterloo", "hi", "am", "as", "stud", "yes", "i", "a", "student"};
String text = "iamastudentfromwaterloo";


Lets create a hashtable named tokenMap which will contain all the token of tokens array.

We will also have 2 stacks, lets say indexStack to keep track of starting index of all the matched tokens in text (this will become clear below .. keep on reading :))
And another stack resultStack which will store all the tokens of the final expected sentence.

We will also have a StringBuffer sb which will keep track of substring from text which would be a candinate token (we will verify that by checking in hashtable tokenMap)

Now,
We will read one character at a time from "text"
StringBuffer sb = "i";
Our start index = 0
Lets push index onto indextStack
sb = "i" is present in the hashtable tokenMap, so now we have following
indexStack = 0 -> null
resultStack = "i" -> null

we now reset sb = "";
Next we see sb = "a"
"a" is in tokenMap so now we have following
indexStack = 1 -> 0 -> null;
resultStack = "a" -> "i" -> null

Now things get interesting as we keep on reading the characters from text and appending to sb but the string is not there in hashtable tokenMap
like sb = "mastudent" ...
So we need to decide to backtrack in such case (logic can be if sb length goes beyond max length of any of the given tokens in tokens array)

So when we backtrack we pop the stacks and reset StringBuffer sb
indexStack = 0 -> null
resultStack = "i" -> null
sb = "";

now again we start appending characters to sb till sb has a match in tokenMap HashTable

We keep repeating the above steps till we have constructed our sentence or till we decide its NOT possible to do so.

Input:

String [] tokens = {"from", "waterloo", "hi", "am", "as", "stud", "yes", "i", "a", "student"};
String text = "iamastudentfromwaterloo";

Output:

Max Token Length: 8
Sentence is: i am a student from waterloo




Sunday, November 4, 2012

Binary Search Tree: Any Path Sum

You are given a binary tree in which each node contains a value. Design an algorithm to print all paths which sum up to that value. Note that it can be any path in the tree - it does not have to start at the root.



Input/Output:

printing inorder: 
1 3 4 5 6 7 8 9 10 12 13 15 17 
printing preorder: 
7 5 3 1 4 6 12 9 8 10 15 13 17 
printing path(s):
7 -> 5 -> null
5 -> 3 -> 4 -> null
12 -> null

Saturday, November 3, 2012

Binary Tree: Is SubTree ?

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 subtree of T1.

Approach 1:
T1 has 10 million nodes—this means that the data alone is about 40 mb. We could create a string representing the inorder and preorder traversals. If T2’s preorder traversal is a substring of T1’s preorder traversal, and T2’s inorder traversal is a substring of T1’s inorder traversal, then T2 is a substring of T1. We can check this using a suffix tree. However, we may hit memory limitations because suffix trees are extremely memory intensive. If this become an issue, we can use an alternative approach.

Approach 2:
Find all the occurances of  T2's root node in T1 and then check recursively if the binary tree matches or not.

Binary Search Tree: Least Common Ancestor

Least common ancestor of 2 nodes in a binary search tree:

Approach:
The main idea of the solution is — While traversing Binary Search Tree from top to bottom, the first node n we encounter with value between n1 and n2, i.e., n1 < n < n2 is the Lowest or Least Common Ancestor(LCA) of n1 and n2 (where n1 < n2). 
So just traverse the BST in pre-order, if you find a node with value in between n1 and n2 then n is the LCA,
 if it's value is greater than both n1 and n2 then our LCA lies on left side of the node,
 if it's value is smaller than both n1 and n2 then LCA lies on right side.

Binary Tree: Least Common Ancestor


Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. NOTE: This is not necessarily a binary search tree.

Approach:
Do the inorder traversal and store it in an array I
Then do the preorder traversal and store it in an array P



Inorder: D B F G E A C
PreOrder: A B D E F G C


Suppose we need to find LCA for nodes D and F
mark the positions in inorder array and find first preorder ptr which seprates it into two
different parts of Inorder array

for above example first preorder ptr is "B" which seprates inorder into "D" and "F G E A C"
so "B" is first commom ancester of "D" and "F".

Binary Tree: Inorder Predecessor


Write an algorithm to find the ‘previous’ node (e.g., in-order predecessor) of a given node in a binary search tree where each node has a link to its parent.


To Find the inorder predecessor of node u:
If u has a left child, l, then pred(u) is the rightmost descendent of l
Otherwise, pred(u) is the closest ancestor, v, of u (if any) such that u is de-
scended from the right child of v.
If there is no such ancestor, then pred(u) is undefined.



The running time of TREE-SUCCESSOR on a tree of height his O(h), since we either follow a path up the tree or follow a path down the tree. The procedure TREE-PREDECESSOR, which is symmetric to TREE-SUCCESSOR, also runs in time O(h).

Taking the nodes one at a time and applying the rule:
node C: Does not have a left child. Closest ancestor such that node-C is de-
scended from the right child is node-A. Therefore, the predecessor of node-C
is node-A.
node A: Has a left child, node-B. Rightmost descendent of node-B is node-E.
node E: Has a left child, node-F. Rightmost descendent of node-F is node-G.
node G: Does not have a left child. Closest ancestor such that node-G is de-
scended from the right child is node-F.
node F: Does not have a left child. Closest ancestor such that node-F is de-
scended from the right child is node-B.
node B: Has a left child, node-D. Rightmost descendent of node-D is node-D
itself.
node D: Does not have a left child. There is no ancestor such that node-D is
descended from the right child. Therefore, the predecessor of node-D is
undefined.

BinaryTree: Inorder Successor


Write an algorithm to find the ‘next’ node (e.g., in-order successor) of a given node in a binary search tree where each node has a link to its parent.Inorder Successor

Approach:
To Find the inorder successor of node u:
If u has a right child, r, then succ(u) is the leftmost descendent of r

Otherwise, succ(u) is the closest ancestor, v, of u (if any) such that u is de-
scended from the left child of v. If there is no such ancestor, then succ(u) is
undefined.


The running time of TREE-SUCCESSOR on a tree of height his O(h), since we either follow a path up the tree or follow a path down the tree. The procedure TREE-PREDECESSOR, which is symmetric to TREE-SUCCESSOR, also runs in time O(h).

Taking the nodes one at a time and applying the rule:
node D: Does not have a right child. Its successor is the closest ancestor, v
such that node-D is descended from the left child of v. Node-D is descended
from the left child of node-B, so succ(D) is node-B.
node B: Has a right child (node-E), so successor is the leftmost descendent of
node-E, namely node-F.
node F: Has a right child (node-G), so successor is the leftmost descendent of
node-G, namely node-G itself.
node G: Does not have a right child. Its successor is the closest ancestor, v
such that node-G is descended from the left child of v. Node-G is descended
from the left child of node-E, so succ(G) is node-E.
node E: Does not have a right child. Its successor is the closest ancestor, v
such that node-E is descended from the left child of v. Node-E is descended
from the left child of node-A, so succ(E) is node-A.
node A: Has a right child (node-C), so successor is the leftmost descendent of
node-C, namely node-C itself.
node C: Does not have a right child. Its successor would be the closest ances-
tor, v such that node-C is descended from the left child of v. However,
there is no such ancestor, so succ(C) is undefined (node-C has no succes-
sor).

Code:

Friday, November 2, 2012

Binary Tree: level order linked list


Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists).

Approach:
We can do breadth first traversal of the tree keeping track of the levels, and create a linkedlist of all the nodes at any particular level

Input/Output:
iterative inorder:
3 7 9 15 17 21 25
printing level order:
15
7 21
3 9 17 25

Printing linked list at each level:
Level: 0
15
Level: 1
7 21
Level: 2
3 9 17 25

Binary Tree: Min Height


Given a sorted (increasing order) array, write an algorithm to create a binary tree with minimal height.

Approach:
We need to create a binary tree such that the number of nodes in left subtree and right subtree are equal if possible.

1. Pick the mid element of the array as the root of the binary tree.
2. The left part of the subarray goes into the left subtree.
3. The right part of the subarray goes into the right subtree.
4. Recurse.

Thursday, November 1, 2012

Graphs: find path between 2 nodes.


Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

Approach:
This problem can be solved by just simple graph traversal, such as depth first search or breadth first search. We start with one of the two nodes and, during traversal, check if the other node is found. We should mark any node found in the course of the algorithm as ‘already visited’ to avoid cycles and repetition of the nodes.

Binary Tree: Is Balanced or not.


Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.

Approach:
The idea is: the difference of min depth and max depth should not exceed 1, since the difference of the min and the max depth is the maximum distance difference possible in the tree.

Input/Output:

Inorder:
3 7 9 15 17 19 21 25
is tree balanced: true
Inorder:
3 7 9 15 17 19 20 21 25
is tree balanced: false


Sunday, October 28, 2012

Set of stacks

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).
FOLLOW UP
Implement a function popAt(int index) which performs a pop operation on a specific sub-stack.

Approach:
In the first part of the question its evident that we need to maintain a list of stacks and as and when one stack exceeds its full capacity we need to switch to next stack.

What about the follow up question? This is a bit trickier to implement, but essentially we should imagine a “rollover” system. If we pop an element from stack 1, we need to remove the bottom of stack 2 and push it onto stack 1. We then need to rollover from stack 3 to stack 2, stack 4 to stack 3, etc.
We could make an argument that, rather than “rolling over,” we should be OK with some stacks not being at full capacity. This would improve the time complexity (by a fair amount, with a large number of elements), but it might get us into tricky situations later on if someone assumes that all stacks (other than the last) operate at full capacity.

Stack: Push Pop Min in O(1)


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.

Approach 1:

class Node {
Integer data;
Integer min;
}

push(4)
stack: (data:4|min:4) -> null;

push(1)
we compare top min ie 4 with value (1) and we have min so far as 1; Now our stack looks like:
stack: (data:1|min:1) -> (data:4|min:4) -> null;

push(5)
stack: (data:5|min:1) -> (data:1|min:1) -> (data:4|min:4) -> null;

Top give us 5
min gives: 1

With above approach we need additional space of size (n) where n is the size of the stack.

Approach 2:
1. We will have one normal stack S1 which supports usual operations push, pop, and peek.
2. Lets declate another stack called minStack where we will keep the min elements seen so far.

Lets trace now:
push(5)
S1: (5) -> null;
minStack: (5) -> null;

push(4)
S1: (4) -> (5) -> null;
minStack: (4) -> (5) -> null;

push(2)
S1: (2) -> (4) -> (5) -> null;
minStack: (2) -> (4) -> (5) -> null;

push(7)
S1: (7) -> (2) -> (4) -> (5) -> null;
// no change in min stack as 2 is still the min element so far.
minStack: (2) -> (4) -> (5) -> null;

push(9)
S1: (9) -> (7) -> (2) -> (4) -> (5) -> null;
// no change in min stack as 2 is still the min element so far.
minStack: (2) -> (4) -> (5) -> null;

element (2) from the minStack will only be popped out when it's popped from S1.

This approach also has additional space requirement and in worst case it will be of size (n) if all the data is unique and sorted in decreasing order.

Input/Output:

TOP: 9
null -> 4 -> 1 -> 5 -> 7 -> 9
TOP: 1
null -> 4 -> 1

Stacks: implement 2 stacks in an array.


Describe how you could use a single array to implement three stacks.

Approach 1:
Divide the array in three equal parts and allow the individual stack to grow in that limited space.
note: “[“ means inclusive, while “(“ means exclusive of the end point.
»»for stack 1, we will use [0, n/3)
»»for stack 2, we will use [n/3, 2n/3)
»»for stack 3, we will use [2n/3, n)
This solution is based on the assumption that we do not have any extra information about the usage of space by individual stacks and that we can’t either modify or use any extra space. With these constraints, we are left with no other choice but to divide equally.


Approach 2:
In this approach, any stack can grow as long as there is any free space in the array.
We sequentially allocate space to the stacks and we link new blocks to the previous block. This means any new element in a stack keeps a pointer to the previous top element of that particular stack.
In this implementation, we face a problem of unused space. For example, if a stack deletes some of its elements, the deleted elements may not necessarily appear at the end of the array. So, in that case, we would not be able to use those newly freed spaces.
To overcome this deficiency, we can maintain a free list and the whole array space would be given initially to the free list. For every insertion, we would delete an entry from the free list. In case of deletion, we would simply add the index of the free cell to the free list.
In this implementation we would be able to have flexibility in terms of variable space utilization but we would need to increase the space complexity.

Singly Linked List: loop start detection


Given a circular linked list, implement an algorithm which returns node at the beginning of the loop.
DEFINITION
Circular linked list: A (corrupt) linked list in which a node’s next pointer points to an earlier node, so as to make a loop in the linked list.
EXAMPLE
Input: A -> B -> C -> D -> E -> C [the same C as earlier]
Output: C

Approach:
If we move two pointers, one with speed "v" and another with speed "2v", they will end up meeting if the linked list has a loop. Why? Think about two cars driving on a track—the faster car will always pass the slower one!

The tricky part here is finding the start of the loop. Imagine, as an analogy, two people racing around a track, one running twice as fast as the other. If they start off at the same place, when will they next meet? They will next meet at the start of the next lap.

Now, let’s suppose Fast Runner had a head start of k meters on an n step lap. When will they next meet? They will meet k meters before the start of the next lap. (Why? Fast Runner would have made k + 2(n - k) steps, including its head start, and Slow Runner would have made n - k steps. Both will be k steps before the start of the loop.)


For the slow ptr we have:
n = v * t
for fast ptr we have
k+x = 2*v * t

now if we solve for x we have
(k+x)/2 = n
x = 2*n - k

So if fast pointer has a head start of k meters on an n step lap then both will meet k meters before the start of the next lap.

Now, going back to the problem, when Fast Runner (n2) and Slow Runner (n1) are moving around our circular linked list, n2 will have a head start on the loop when n1 enters. Specifically, it will have a head start of k, where k is the number of nodes before the loop. Since n2 has a head start of k nodes, n1 and n2 will meet k nodes before the start of the loop.

So, we now know the following:
1. Head is k nodes from LoopStart (by definition).
2. MeetingPoint for n1 and n2 is k nodes from LoopStart (as shown above).
Thus, if we move n1 back to Head and keep n2 at MeetingPoint, and move them both at the same pace, they will meet at LoopStart.

Saturday, October 27, 2012

Adding 2 Singly linked lists


You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3 -> 1 -> 5), (5 -> 9 -> 2)
Output: 8 -> 0 -> 8

Approach:
We can implement this recursively by adding node by node, just as we would digit by digit.
1. result.data = (node1 + node2 + any earlier carry) % 10
2. if node1 + node2 > 10, then carry a 1 to the next addition.
3. add the tails of the two nodes, passing along the carry.


Input/Output:
A = 8 -> 7 -> 1 -> 1 -> null
B = 6 -> 3 -> 4 -> null
Adding the above linked lists:
Result: 4 -> 1 -> 6 -> 1 -> null

Singly LinkedList: Delete Node


Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node.
EXAMPLE
Input: the node ‘c’ from the linked list a->b->c->d->e
Result: nothing is returned, but the new linked list looks like a->b->d->e


Approach:
Lets say the list is a->b->c->d->e
We have point p1 pointing to "c" node.
Get a pointer p2 to point to the next node of p1 ie to node "d" here.
Now copy "d" node data to node pointed by p1 and delete node pointed by p2.
new list is "a->b->d->e";

NOTE: this problem can not be solved if pointer p1 is pointing to the last node of the singly linked list.

Singly Linked List: Nth Node from end


Implement an algorithm to find the nth to last element of a singly linked list.

Approach:
lets assume n = 3;
declare 2 ptrs, prev and current which point to the head of the linked list.
advance current by n (3) positions.
then advance both prev and current pointers one at a time till current becomes null.
At this point prev is the nth node from end of the linked list.

Input/Output:
51 -> 70 -> 74 -> 32 -> 10 -> 90 -> 18 -> 21 -> 30 -> null
3 node from end: 18
7 node from end: 74
9 node from end: 51
10 node from end is null

19 -> 16 -> 15 -> null
3 node from end: 19
7 node from end is null
9 node from end is null
10 node from end is null

Time complexity: O(n) - where n is the size of the singly linked list.

Remove duplicates from singly link list.



Write code to remove duplicates from an unsorted linked list.

Approach:
Create a hashtable.
Iterate through the list and check the node if its already present in the hashtable, if present then delete it from the list.
If not then add it to the hashtable and move ahead in the list.


Input/Output:
Original linked list:
2 -> 3 -> 2 -> 5 -> 2 -> 8 -> 2 -> 3 -> 8 -> null
After deleting duplicate node:
2 -> 3 -> 5 -> 8 -> null

Time complexity: O(n) -> n is the length of the linked list.
Space complexity: O(n) -> size of the hashtable.