type your search

Showing posts with label Data Structures. Show all posts
Showing posts with label Data Structures. Show all posts

Wednesday, January 11, 2012

Important questions in Data Structures

Trees Revisited

We complete the trees sections in this post adding some more questions to the already posted ones.

1)What are splay trees?How are they different from normal trees?

2)What are the key operations which characterize splay trees?

3)How are AVL rotations different from the operations performed in splay trees?

4)Show that if all the nodes in a splay tree are accessed sequentially,then the total access time is O(N),regardless of the initial tree?

5)Given 2 binary trees T1 and T2 with same set of nodes,show how you can transform one in to the other?

6)Give an algorithm to transform a binary tree T1 into another binary tree T2?

7)Give an algorithm to find all the elements between 2 keys K1 and K2 with K1<=K2
in a binary search tree T?

8)How do you convert the parent-child tree to a child-sibling tree(assume the tree is a binary tree)?

9)Two binary trees T1 and T2 are isomorphic if T1 can be transformed into T2 swapping left and right children of the nodes in T1.Give an algorithm to report whether 2 given binary trees are isomorphic.

10)Analyze the complexity of the above algorithm and report whether there exists a linear solution to it?

Hash Tables

1)What is the expected time to search for an element in a hash table?

2)What is the worst case time for searching a element using hash table.

3)Demonstrate the insertion of the keys 5,28,19,15,20,33,12,17,10 into a hash table with collisions resolved by chaining.Let the table have 9 slots,and let the hash function be h(k)=k mod 9.

4)Suppose we use a hash function to hash m distinct keys into an array T of length m.Assuming simple uniform hashing,what is the expected number of collisions?

5)Suggest how storage for elements can be allocated and deallocated within the hash table itself by linking all unused slots into a free list.Assume that one slot can store a flag and either one element plus a pointer or two pointers.Does the free list need to be doublt linked,or does a singly linked free list suffice?

6)Suppose we wish to search a linked list of length n,where each element contains a key k along with a hash value h(k).Each key is a long character string.How might we take advantage of the hash values when searching the list for an element with a given key?

Counting, Radix and Bubble sorts

1)Illustrate the operation of Counting-Sort on the array A={6,0,2,0,1,3,4,6,1,3,2}

2)Illustrate the operation of Radix-Sort on the following list of English words: COW,DOG,SEA,RUG,ROW,MOB,RAT,BAT,BAR,EAR,TAR,DIG,BIG,TEA,NOW,FOX}.

3)Illustrate the operation of Bucket Sort on the array A={.81,.09,.13,.61,.43,.23,.98,.60,.75,.41}.

4)Explain how to sort n integers in the range 0 to n^2-1 in O(n) time.

5)Which of the following sorting algorithms are stable: insertion sort,merge sort,heapsort and quicksort? Give a simple scheme that makes any sorting algorithm stable. How much additional time and space does the scheme take?

6)What is the worst-case running time for the bucket-sort algorithm? What simple change to the algorithm preserves its linear expected running time and makes its worst-case running time O(nlgn)?

7)Describe an algorithm that, given n integers in the range 0 to k,preprocesses its input and then answers any query about how many of the n integers fall into a range [a...b] in O(1) time.The algorithm should use THETA(n+k) preprocessing time.

8)When are Radix and Bucket sorts used?

Stacks,Queues and Linked lists

1)Explain how to implement two stacks in one array A[1,...,n] in such a way that neither stack overflows unless the total number of elements in both stacks together is n. The run time of PUSH and POP is O(1).

2)Explain how to implement a queue using two stacks. Analyse the running time of the queue operations.

3)Explain how to implement a stack using two queues. Analyse the running time of the stack operations.

4)Write four O(1)-time procedures to insert elements into and delete elements from both ends of a deque constructed from an array.

5)Implement a stack using a singly linked list L. The run time of PUSH and POP should be O(1).

6)Implement a queue using a singly linked list L. The run time of ENQUEUE and DEQUE should be O(1).

7)Can the dynamic-set operation INSERT be implemented on a singly linked list in O(1) time? What about DELETE?

8)Implement the dictionary operations INSERT,DELETE and SEARCH using singly linked,circular lists.What are the running times of the procedures?

9)Give a THETA(n)-time nonrecursive procedure that reverses a singly linked list of n elements. The procedure should use no more than constant storage beyond that needed for the list itself.

10)Write the operations of INSERT, DELETE and SEARCH in a linked list.Also, how do we reverse a linked list?

Dynamic Programming

Dynamic Programming is a method of solving problems exhibiting the properties of overlapping subproblems and optimal substructure that takes much less time than naive methods.It is typically applied to optimization problems.

Longest Common subsequence and substring:

Longest Common subsequence and substring are two applications of Dynamic Programming.The longest common subsequence problem is finding the longest subsequence common to all sequences in a set of sequences (often just two) while longest common substring is finding the longest substring.

1)Determine an LCS of {1,0,0,1,0,1,0,1} and {0,1,0,1,1,0,1,1,0}.
2)Give an algorithm to find the Longest common subsequence of sequences with lengths m,n respectively and also analyze their time complexities.
3)Give an algorithm to find the Longest common string of strings with lengths m,n respectively and also analyse their time complexities.
4)Give an O(n^2) time algorithm to find the longest monotonically increasing subsequence of a sequence of n numbers.
5)Give an O(n^2) time algorithm to find the longest monotonically increasing subsequence of a sequence of n numbers.
6)What is the difference between longest common subsequence and longest common substring
7)State few applications of Dynamic Programming.

Trees - Programming Interview Questions

1. Write a C program to find the depth or height of a binary tree.



2. Write a C program to determine the number of elements (or size) in a binary tree.



3. Write a C program to delete a tree (i.e, free up its nodes)



4. Write a C program to find the minimum value in a binary search tree.



5. Write a C program to create a mirror copy of a tree (left nodes become right and right nodes become left)


6. Write C code to implement the preorder(), inorder() and postorder() traversals. Whats their time complexities?

7. Write a C program to create a copy of a tree


8. Write a C program to check if a given binary tree is a binary search tree or not?


9. Write a C program to implement level order traversal of a tree.
Solution:Breadth First Search of the tree gives the level order traversal.

10. Write a C program to delete a node from a Binary Search Tree?


11. Write a C program to search for a value in a binary search tree (BST).

12. Write a C program to count the number of leaves in a tree

13. Write a C program for iterative preorder, inorder and postorder tree traversals
Solution:Use stacks to depict the function calls.Not much different from routine traversals.

Trees - commonly asked interview questions!

1) How do you create the mirror copy of a tree (left node becomes right and viceversa)

2)How do you build a tree given inorder and postorder traversals of it?

3)How do you build a tree given inorder and preorder traversals of it?

4)Can you build a tree given preorder and postorder traversals?If yes, then give the procedure.If no,then give a reason as to why?

5)Find the closest ancestor of a 2 given nodes in a binary search tree(use the property of binary search tree)?
6)How do you implement trees in array?

7)How many binary trees can be constructed from N nodes?(the structure of the tree is debated question)

8)How do you find the greatest and least among leaves?

9)How do you check whether a tree and it mirror image are equal?

10)How do you find the minimum and maximum elements in a binary search tree?

AVL Trees

11)How is an AVL tree different from normal binary tree?

12)Give an expression for the minimum no of nodes of a AVL tree of height H?

13)Give the operations required to convert a normal binary tree in to a AVL tree?

14)How many bits are required per node to store the height of a node in a N-node AVL tree?

15)Keys 1,2,3,........,2^k -1 are inserted in order into an initially empty AVL tree.
Prove that the resulting tree is perfectly balanced.

16)Write routines for all the rotations employed in AVL trees?

17)What is the smallest AVL tree that overflows an 8-bit height counter?

18)Write a function to generate a perfectly balanced binary search tree of height H with distinct keys 1 through 2^(H+1)-1 ?Give also the running time of the above function?

19)What are the complexities of insertion,deletion and search on an AVL tree?

20)Write routines for insertion,deletion in an AVL tree?

Heaps And Heapsort

A heap is a specialized tree-based data structure that satisfies the heap property.If Y is the child node of X,then key(X) >= key(Y). Such a heap is called a max heap and the opposite one is called a min heap.

The operations commonly performed with a heap are:

1)delete-max or delete-min:removing the root node of a max or min-heap,respectively.
2)increase-key or decrease-key:updating a key within a max or min-heap,respectively.
3)merge:joining two heaps to form a valid new heap containing all the elements of both.

Heaps are used in the sorting algorithm called heapsort.

HEAPSORT:

Heap sort is one of the best methods being in-place and with no quadratic worst case scenarios.It is a comparision based sorting algorithm, ans is part of the selection sort family.The operations performed by heap sort algorithm are:

BUILD-MAX-HEAP:To build a max heap with the given [1,n] elements.
MAX-HEAPIFY:Which modifies a heap with [1,n-1] elements so that it satifies the properties of a heap.

The following are the basic questions on heaps:

1)What are the properties of a heap?
2)What is the height of an n-element heap?
3)Where in a max-heap might the smallest element reside, assuming that all the elements are distinct?
4)Is an array that is in sorted order a min-heap?
5)What are the minimum and maximum numbers of elements in a heap of height h?
6)How many nodes are present in an n-element heap of height h?
7)What is the running time complexity of a heapsort?
8)What is the worst-case running time of a heapsort?
9)What is the running time of heapsort on an array A of length n that is alreay sorted in increasing order? What about the same in decreasing order?
10)What is the best case running time of heapsort when all the elements are distinct?
11)Name some applications of heaps

Trees -Basic Interview Questions

We will start of with some basic questions on trees and this post will be updated with tougher questions to crack..

Basic Questions

1)If a tree has N nodes, then how many are the edges?

2)Prove that there exists only a single path from each node to the root?

3)Prove that the depth of a tree is always equal to the height of the tree?

4)The structure of a typical tree is to have in each node ,besides it data, a pointer to each of its children.But this might be infeasible if there aren’t fixed number of children at each node.So how do modify this data structure to accommodate variable no of children at each node?


5)What are the maximum and minimum depths of a binary search tree?

6)How many are the no of null pointers for a binary tree of N nodes?

7)Distinguish inorder , preorder and postorder traversals properly?

8)How is a binary tree different from binary search tree?

9)Recursive calls have always been employed in the case of trees because of their recursive structural property.But linked lists aren’t that different .But why recursion is not that advisable in the case of lists?(A little theoretical …. Think in terms of limited stack size of your machine)

10)What are the complexities of insertion,deletion on a binary search tree?

11)Show that the maximum number of nodes in a binary tree of height H is 2^(H+1) -1

Some Basic Questions on Sorting

1 .In a selectionsort of n elements, how many times is the swap function called in the complete execution of the algorithm?

A. 1
B. n - 1
C. n log n
D. n^2

2 .Selectionsort and quicksort both fall into the same category of sorting algorithms. What is this category?

* A. O(n log n) sorts
* B. Divide-and-conquer sorts
* C. Interchange sorts
* D. Average time is quadratic.

3 . Suppose that a selectionsort of 100 items has completed 42 iterations of the main loop. How many items are now guaranteed to be in their final spot (never to be moved again)?

* A. 21
* B. 41
* C. 42
* D. 43

4 .Suppose we are sorting an array of ten integers using a some quadratic sorting algorithm. After four iterations of the algorithm's main loop, the array elements are ordered as shown here:

1 2 3 4 5 0 6 7 8 9

Which statement is correct? (Note: Our selectionsort picks largest items first.)

* A. The algorithm might be either selectionsort or insertionsort.
* B. The algorithm might be selectionsort, but could not be insertionsort.
* C. The algorithm might be insertionsort, but could not be selectionsort.
* D. The algorithm is neither selectionsort nor insertionsort.

5 .Suppose we are sorting an array of eight integers using a some quadratic sorting algorithm. After four iterations of the algorithm's main loop, the array elements are ordered as shown here:

2 4 5 7 8 1 3 6

Which statement is correct? (Note: Our selectionsort picks largest items first.)

* A. The algorithm might be either selectionsort or insertionsort.
* B. The algorithm might be selectionsort, but it is not insertionsort.
* C. The algorithm is not selectionsort, but it might be insertionsort.
* D. The algorithm is neither selectionsort nor insertionsort.

6 .When is insertionsort a good choice for sorting an array?

* A. Each component of the array requires a large amount of memory.
* B. Each component of the array requires a small amount of memory.
* C. The array has only a few items out of place.
* D. The processor speed is fast.

7 What is the worst-case time for mergesort to sort an array of n elements?

* A. O(log n)
* B. O(n)
* C. O(n log n)
* D. O(n^2)

8 What is the worst-case time for quicksort to sort an array of n elements?

* A. O(log n)
* B. O(n)
* C. O(n log n)
* D. O(n^2)

9 .Mergesort makes two recursive calls. Which statement is true after these recursive calls finish, but before the merge step?

* A. The array elements form a heap.
* B. Elements in each half of the array are sorted amongst themselves.
* C. Elements in the first half of the array are less than or equal to elements in the second half of the array.
* D. None of the above.

10 .Suppose we are sorting an array of eight integers using quicksort, and we have just finished the first partitioning with the array looking like this:

2 5 1 7 9 12 11 10

Which statement is correct?

* A. The pivot could be either the 7 or the 9.
* B. The pivot could be the 7, but it is not the 9.
* C. The pivot is not the 7, but it could be the 9.
* D. Neither the 7 nor the 9 is the pivot.

11 .What is the worst-case time for heapsort to sort an array of n elements?

* A. O(log n)
* B. O(n)
* C. O(n log n)
* D. O(n^2)

12.Suppose you are given a sorted list of N elements followed by f(N) randomly ordered elements.How would you sort the entire list if
* A. f(N)=O(1)
* B. f(N)=O(logN)
* C. f(N)=O(N^1/2)
* D. How large can f(N) be for the entire list still to be sortable in O(N) time?

13.Prove that any algorithm that find an element X in a sorted list of N elements requires Omega(log N) comparisons.

14.Prove that sorting N elements with integer keys in the range 1 < Key < M
takes O(M + N) time using bucket sort.

15.Suppose you have an array of N elements,containing only 2 distinct keys, true and false.Give an O(N) algorithm to sort the array.

16.Prove that any comparison based algorithm to sort 4 elements requires atleast 5 comparisons

17. In how many ways can 2 sorted arrays of combined size N be merged?

18.Show that binary insertion may reasonably be expected to be an O(n log n) sort.

19.You are given two sets of numbers Xi and Yj , where i and j run from 1 to N.
Devise an algorithm to find the M largest values of Xi −Yj . This algorithm should
not be quadratic in N, though it is permitted to be quadratic in M.
You should regard N as being of the order of 20,000 and M as being of the order
of 1,000.


20.If 1024 numbers are drawn randomly in the range 0–127 and sorted by binary
insertion, about how many compares would you expect?

Interview questions on Sorting - Quick Sort

QuickSort

Here are some of the commonly asked and good questions on quick sort.


  1. Determine the running time of QuickSort for

    a.Sorted input
    b.reverse -ordered input
    c.random input
    d. When all the elements are equal


  2. The ones who are familiar with QuickSort as also well aware of the important phase of the algorithm-the pivot selection.Suppose we always choose the middle element as the pivot .Does this make it unlikely that QuickSort will require quadratic time?




  3. What is the worst-case behavior (number of comparisons) for quick sort?


  4. In selecting the pivot for QuickSort, which is the best choice for optimal partitioning:
    a.The first element of the array
    b.The last element of the array
    c.The middle element of the array
    d.The largest element of the array
    e.The median of the array
    f.Any of the above


  5. In its worst case QuickSort behaves like:
    a.Bubble sort
    b.Selection sort
    c.Insertion sort
    d.Bin sort



  6. Describe an efficient algorithm based on Quicksort that will find the element of a set that would be at position k if the elements were sorted.


  7. Recall that the linked-list version of quicksort() puts all items whose keys are equal to the pivot's key into a third queue, which doesn't need to be sorted. This can save much time if there are many repeated keys.

    The array-based version of quicksort() does not treat items with equal keys specially, so those items are sorted in the recursive calls.

    Is it possible to modify array-based quicksort() so that the array is partitioned into three parts (keys less than pivot, keys equal to pivot, keys greater than pivot) while still being in-place? (The only memory you may use is the array plus a constant amount of additional memory.)

    Why or why not?

Sorting - Insertion Sort

Insertion Sort Any basic sorting algorithm which uses comparison of elements involves a number of inversions to be made to the given array to sort it.

An Inversion in an array of numbers is any ordered pair (i,j) such that
(a[i] - a[j] )*( i - j) .
Pseudo Code

void InsertionSort(int A[],int N)
{
    int pos,i;
    int temp;
    
    for(pos=1; pos < n; pos++>
    {
         temp=A[pos];
         for(j=pos;j>0;j--)
         {
                if(A[j-1] > temp)
                {
                        A[j]=A[j-1];
                }
                else
                {
                    break;
                }
                A[j]=temp;
         }
    }
}


Analysis of Insertion Sort:
The efficiency of insertion sort depends upon the distribution of the data.This is because insertion sort tries to put each of the elements in the sorted array of preceding elements.If the array is presorted , then the running time of the algorithm is O(N) because the inner for loop always breaks immediately.In the worst case, it is of O(N^2) as can be observed for each position i, the inner loop is O(i).
Hence the complexity of this algorithm is O(N^2).

Questions:

1) What is the running time of the above algorithm if all the elements in the array are equal?

Solution:O(N).Each of the Inner for loop becomes O(1).Hence the complexity O(N).

2)Suggest a modified Insertion Sort algorithm to check whether an array is sorted or not?
Give also the complexity analysis


Solution:One can prove that complexity is O(N) with out fuss.The modification is when one finds that the first swap is required just print that it is not ordered and break the loop

Stack and Queue

Stack:A stack is a linear list of elements for which all insertions and deletions(usually accesses) are made at only one end of the list.
They are also called as LIFO lists(Last Input First Output).
The operations supported are :

1)IsEmpty(S): returns whether the stack is empty or not.

2)IsFull(S): return whether the stack is full or not.

3)Push(Element X,S): pushes element X on to the top of the stack.

4)Pop(S) : pops an element from the top of the stack on to the output(printing on to the output console isn't necessary though in which case we can define another function Top(S) which gives the top element of the stack).

All the above mentioned operations are of O(1) complexity.



Queue: Queue is a linear list for which all insertions are made at one end and deletions(accesses as well)
are made at the other end of the list and the lists are also called as FIFO lists(First Input First Output ).

The operations supported are

1)IsEmpty(Q):returns whether the queue is empty or not.

2)IsFull(Q): return whether the queue is full or not.

3)Enqueue(Element X,Q): inserts an element X on the rear side of the queue.

4)Dequeue(Q): removes the element pointed to by the front end of the queue.

Similar to a stack ,the operations of the queue are also of O(1) complexity.




Dequeue (double ended queue):A Dequeue is a linear list for which insertions and deletions(accesses as well) occur at the ends.
Analogous to the operations defined for stack and Queue,we can also define some operations for Dequeue.
A simple observation reveals the fact that we can simulate both stack and queue from Dequeue by input and output restrictions.

Having dwelt at such a length on these linear lists,we shall also see some interesting questions based on the simple properties of these linear lists.




Questions
1)How do you implement 2 stacks using only one array.Your stack routines should not indicate an overflow unless every slot in the array is used?


Solution:given an Array,start the first stack S1 from left end and other stack S2 from the right end.while S1 gets grows towards right ,S2 grows towards left.



2)Propose a data structure which supports the stack Push and Pop operations and a third operation FindMin,which returns the smallest element in the data strucuture all in O(1) worst case time.
Solution:Use 2 stacks S1 in to which the elements are pushed and S2 in to which only the current minimum is pushed.
When one needs to insert an element E ,we first push E on to S1 and then access the top element T of S2 which is the minimum before E has been inserted.If only E is less than T , we push E on to S2 .
When one needs to pop an element ,pop the top element of S1 and if this element is also equal to the one on top of S2, then pop it off S2 as well.

Hence the current minimum will always be on top of S2 .Hence along with other normal stack operations, access of minimum element is also possible in O(1).



3)Show how to implement 3 stacks in a single array efficiently?(debated question)

Solution: It is still up for debate ,as we haven't yet figured out the exact solution.We will soon put the best solution for this problem.


4)Consider a empty stack of integers.Let the numbers 1,2,3,4,5,6 be pushed on to this stack only in the order they appeared from left to right.Let S indicates a push and X indicate a pop operation.Can they be permuted in to the order 325641(output) and order 154623?(if a permutation is possible give the order string of operations.
(Hint: SSSSSSXXXXXX outputs 654321)


Solution: SSSXXSSXSXXX outputs 325641.
154623 cannot be output as 2 is pushed much before 3 so can appear only after 3 is output.


5)Given a string containing N S's and N X's where S indicates a push operation and X indicates a pop operation, and with the stack initially empty,Formulate a rule to check whether a given string S of operations is admissible or not (Hint: A string S of operations should always abide by the properties of the stack which in this case only means you never pop an element from an empty stack)


Solution:Given a string of length 2N, we wish to check whether the given string of operations is permissible or not with respect to its functioning on a stack.
The only restricted operation is pop whose prior requirement is that the stack should not be empty.So while traversing the string from left to right,prior to any pop the stack shouldn't be empty which means the no of S's is always greater than or equal to that of X's.
Hence the condition is at any stage on processing of the string,
no of S's > no of X's




6)Find a simple formula for An, the number of permutations the can be printed on an input of n distinct characters to a stack (similar to question 4)


Solution:The numbers are input in the order 1,2,3,...,N.
So the problem amounts to the number of strings each of N pushes(denoted by S) and N pops(denoted by X).
The only criteria to select a string is at any stage of its processing character by character we should have no of S's > no of X's .

This problem is no different from parenthesis problem where N needs to give the no of possible permutations of N parenthesis , which if given by Nth catalan number Cn=(2n)!/((n+1)! n!).
For more insite into catalan number refer this link.
en.wikipedia.org/wiki/Catalan_number





7)Show that it is possible to obtain the permutation P1P2.........Pn from 1,2,.........n using a stack
if and only if there are no indices i < j < k such that Pj < Pk < Pi.



Solution:The solution can be arrived simply by veirfying that among the 6 possible
orders of Pi,Pj,Pk the rest 5 are possible and the ordering in question i.e is Pi,Pj,Pk is not possible.

We leave it to the reader the verification of possibility of the 5 orderings and deal only with proving that the order Pi,Pj,Pk is not possible.

Suppose say that the order Pi,Pj,Pk is possible.
As Pi is the largest and printed first (i < j < k) followed by Pj and Pk,just before the popping of Pi the ordering of these 3 on the stack shall be Pi,Pk followed by Pj(from top).But as j<k ,Pj is printed prior to Pk contradicting the ordering on the stack. Hence this ordering is not possible.



Please Post Your answers to these Questions in the comments section.Your valuable comment might invoke a good discussion and learning process.