Data Structure Questions
Data Structure Questions
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.
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).
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 ).
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).
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)
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)
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.
Tree Arithmetic
1)If a tree has N nodes, then how many are the edges?
Solution:Every node has a parent except the root.Each edge associates a node with its child.So the number of edges are N-1.
2)Prove that there exists only a single path from each node to the root?
Solution:If there are more than 1 paths from a node to the root,it means there are more than 1 parents for one of the ancestors of the
node concerned, which is impossible in a tree.
3)Prove that the depth of a tree is always equal to the height of the tree?
Solution: Height of a tree is the height of the root.Depth of a tree is the depth of the deepest node, which is the number of edges
from root to it.This should also be the node which defines the height of the root,otherwise we end up with a contradiction.
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?
Solution:In a binary tree of N nodes,the maximum depth is N-1 when it develops only on 1 side and the minimum is floor(log(N)).
6)How many are the no of null pointers for a binary tree of N nodes?
Preorder: root is first processed followed by left and right subtrees.There is no order defined between left and right
children.Essentially left and right subtrees are traversed only after the root is traversed.
Solution:In Binary search tree, all the elements in the left subtree are <= root and all the elements in the right subtree are >=
root,which is not the case with all the binary trees.
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)
Solution:The depth of a well built tree of N nodes is log(N).So recursive calls are affordable most of the times as stack overflow is
seldom possible.But if recursive calls are employed for lists, then the order of recursive call stack size is N which
is not feasible for large N.
Solution:Insertion in a well built binary search tree is O(logN) and so is the deletion.This is under assumption that depth of tree is
O(logN).
11)Show that the maximum number of nodes in a binary tree of height H is 2^(H+1) -1
Solution:In a binary tree of height H ,with maximum number of nodes,all the levels should be completely filled.At depth d, the
number of nodes should be 2^d.
Therefore, the total number of nodes =1+2+4+....+2^H=2^(H+1)-1.
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.
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:
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)
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
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.
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?
Solution:
#include<stdio.h>
struct binarysearchtree
{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;
int height(tree T)
{
if(T==NULL)
return 0;
else
{
int h1=height(T->left);
int h2=height(T->right);
return 1+max(h1,h2);
}
}
Solution:
#include<stdio.h>
struct binarysearchtree
{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;
int tree_size(tree T)
{
if(T==NULL)
return 0;
else
{
return 1+tree_size(T->left)+tree_size(T->right);
}
}
#include<stdio.h>
struct binarysearchtree
{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;
void tree_free(tree T)
{
if (T==NULL)
return;
else
{
tree_free(T->left);
tree_free(T->right);
free(T);
}
}
Solution:
#include<stdio.h>
struct binarysearchtree
{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;
tree min(tree T)
{
if (T==NULL)
return NULL;
else
{
if(T->left==NULL)
return T;
else
return min(T->left);
}
}
Question:Write a C program to create a mirror copy of a tree left nodes become right and right nodes become left)
Solution:
#include<stdio.h>
struct binarysearchtree{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;
tree mirror_copy(tree T)
{
if(T==NULL)
return T;
else
{
tree temp1=mirror_copy(T->left);
tree temp2=mirror_copy(T->right);
T->left=temp2;
T->right=temp1;
return T;
}
}
Write C code to implement the preorder(), inorder() and postorder() traversals. Whats their time complexities?
#include<stdio.h>
struct binarysearchtree{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;
void inorder_print(tree T)
{
if (T!=NULL)
{
printf("%d\n",T->data);
inorder_print(T->left);
inorder_print(T->right);
}
}
void postorder_print(tree T)
{
if (T==NULL)
{
return;
}
postorder_print(T->left);
postorder_print(T->right);
printf("%d\n",T->data);
}
void preorder_print(tree T)
{
if (T==NULL)
{
return;
}
printf("%d\n",T->data);
preorder_print(T->left);
preorder_print(T->right);
Solution:
#include<stdio.h>
struct binarysearchtree{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;
tree copy(tree T)
{
if(T== NULL)
return NULL;
else
{
tree *newtree=(tree*)malloc(sizeof(tree));
newtree->data=tree->data;
newtree->left=copy(T->left);
newtree->right=copy(T->right);
return newtree;
}
}
8. Write a C program to check if a given binary tree is a binary search tree or not?
Solution:
If the given binary tree is a Binary search tree,then the inorder traversal should output the elements in increasing order.We make use
of this property of inorder traversal to check whether the given binary tree is a BST or not.We make note of the latest element that
could have been printed and compare it with the current element.Given below is a C function to check it.
bool flag=true;
void inorder(tree T,int *lastprinted)
{
if(T==NULL)
{
printf("the tree is empty .Hence, it is a BST\n");
}
else
{
if(T->left!=NULL)
{
inorder(T->left,lastprinted);
}
if(T->data > *lastprinted)
{
*lastprinted=T->data;
}
else
{
printf("the given binary tree is not a BST\n");
flag=false;
exit(0);
}
inorder(T->right,lastprinted);
}
}
Now check the value of flag to say whether it is a BST or not.If it is not then it is already taken care by the code.
#include<stdio.h>
struct binarysearchtree{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;
11. Write a C program to search for a value in a binary search tree (BST).
Solution:
#include<stdio.h>
#include<stdbool.h>
struct binarysearchtree{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;
#include<stdio.h>
struct binarysearchtree{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;
int count_leaves(tree T)
{
if(T==NULL)
return 0;
else if(T->left==NULL && T->right==NULL)
{
return 1;
}
else
return count_leaves(T->left)+count_leaves(T->right);
}