0% found this document useful (0 votes)
283 views13 pages

Data Structure Questions

The document discusses data structures like stacks, queues, and dequeue. It provides definitions and operations for each. It then poses 10 questions related to these data structures, providing solutions for implementing stacks and queues efficiently using a single array, and other properties related to stacks, queues, and binary trees. The last part briefly defines heaps and the heapsort algorithm, noting that a heap satisfies the heap property where a node's key is greater than or equal to its children's keys in a max heap. Common heap operations like delete-max and increase-key are also stated.

Uploaded by

Sesa Singha Roy
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
283 views13 pages

Data Structure Questions

The document discusses data structures like stacks, queues, and dequeue. It provides definitions and operations for each. It then poses 10 questions related to these data structures, providing solutions for implementing stacks and queues efficiently using a single array, and other properties related to stacks, queues, and binary trees. The last part briefly defines heaps and the heapsort algorithm, noting that a heap satisfies the heap property where a node's key is greater than or equal to its children's keys in a max heap. Common heap operations like delete-max and increase-key are also stated.

Uploaded by

Sesa Singha Roy
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 13

DATA STRUCTURE QUESTIONS :

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.

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?

Solution:Well the answer to this is child sibling relationship.

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?

Solution: Total no of pointer=2*N. And each edge is associated with 1 pointer.


So the no of null pointer is 2*N-(N-1)=N+1 .

7)Distinguish inorder , preorder and postorder traversals properly?


Solution: Inorder traversal:Left subtree is first processed ,followed by root and then by right subtree.

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.

Postorder:Left and right children are traversed before traversing root.

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

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.

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

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.

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 - 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?

Question:Write a C program to find the depth or height of a binary tree

Solution:
#include<stdio.h>

struct binarysearchtree
{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;

int max(int a,int b)


{
if(a >=b)
return a;
else
return b;
}

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);
}
}

Question:Write a C program to determine the number of elements(or size) in a binary tree?

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);
}
}

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

#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);
}
}

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

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);

Each of them traverse all the nodes.


So the complexity is O(N).

7.Write a C program to create


a copy of a tree

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.

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?


Solution:

#include<stdio.h>
struct binarysearchtree{
int data;
struct binarysearchtree* left;
struct binarysearchtree* right;
};
typedef struct binarysearchtree* tree;

tree delete_node(tree T,int num)


{
tree temp;
if (T==NULL)
exit(0);
//return NULL;
else if(num<T->data)
T->left=delete_node(T->left,num);
else if(num>T->data)
T->right=delete_node(T->right,num);
else
{
if(T->left!=NULL&&T->right!=NULL)
{
temp=min(T->right);
T->data=temp->data;
T->right=delete_node(T->right,T->data);
}
else if(T->left==NULL)
{
temp=T;
T=T->right;
}
else if(T->right==NULL)
{
temp=T;
T=T->left;
}
free(temp);
}
return T;
}

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;

tree search_node(tree T,int num)


{
if(T==NULL)
{
return NULL;
}
else
{
if(T->data>num)
search_node(T->left,num);
else if(T->data<num)
search_node(T->right,num);
return T;
}
}

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


Solution:

#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);
}

You might also like