Anda di halaman 1dari 15

DATA STRUCTUR E QUESTIONS

Design and Implement Special Stack Data Structure | Added Space


Optimized Version
September 16, 2011
Question: Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(),
isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the
SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should
only use standard Stack data structure and no other data structure like arrays, list, .. etc.
Example:
Consider the following SpecialStack
16 --> TOP
15
29
19
18

When getMin() is called it should return 15, which is the minimum
element in the current stack.

If we do pop two times on stack, the stack becomes
29 --> TOP
19
18

When getMin() is called, it should return 18 which is the minimum
in the current stack.


Solution: Use two stacks: one to store actual stack elements and other as an auxiliary stack to store
minimum values. The idea is to do push() and pop() operations in such a way that the top of auxiliary
stack is always the minimum. Let us see how push() and pop() operations work.
Push(int x) // inserts an element x to Special Stack
1) push x to the first stack (the stack with actual elements)
2) compare x with the top element of the second stack (the auxiliary stack). Let the top element be y.
..a) If x is smaller than y then push x to the auxiliary stack.
..b) If x is greater than y then push y to the auxiliary stack.
int Pop() // removes an element from Special Stack and return the removed element
1) pop the top element from the auxiliary stack.
2) pop the top element from the actual stack and return it.
The step 1 is necessary to make sure that the auxiliary stack is also updated for future operations.
int getMin() // returns the minimum element from Special Stack
1) Return the top element of auxiliary stack.
We can see that all above operations are O(1).
Let us see an example. Let us assume that both stacks are initially empty and 18, 19, 29, 15 and 16 are
inserted to the SpecialStack.
When we insert 18, both stacks change to following.
Actual Stack
18 <--- top
Auxiliary Stack
18 <---- top

When 19 is inserted, both stacks change to following.
Actual Stack
19 <--- top
18
Auxiliary Stack
18 <---- top
18

When 29 is inserted, both stacks change to following.
Actual Stack
29 <--- top
19
18
Auxiliary Stack
18 <---- top
18
18

When 15 is inserted, both stacks change to following.
Actual Stack
15 <--- top
29
19
18
Auxiliary Stack
15 <---- top
18
18
18

When 16 is inserted, both stacks change to following.
Actual Stack
16 <--- top
15
29
19
18
Auxiliary Stack
15 <---- top
15
18
18
18
Following is C++ implementation for SpecialStack class. In the below implementation, SpecialStack
inherits from Stack and has one Stack object min which work as auxiliary stack.
?
#include<iostream>
#include<stdlib.h>

using namespace std;

/* A simple stack class with basic stack funtionalities */
class Stack
{
private:
static const int max = 100;
int arr[max];
int top;
public:
Stack() { top = -1; }
bool isEmpty();
bool isFull();
int pop();
void push(int x);
};

/* Stack's member method to check if the stack is iempty */
bool Stack::isEmpty()
{
if(top == -1)
return true;
return false;
}

/* Stack's member method to check if the stack is full */
bool Stack::isFull()
{
if(top == max - 1)
return true;
return false;
}

/* Stack's member method to remove an element from it */
int Stack::pop()
{
if(isEmpty())
{
cout<<"Stack Underflow";
abort();
}
int x = arr[top];
top--;
return x;
}

/* Stack's member method to insert an element to it */
void Stack::push(int x)
{
if(isFull())
{
cout<<"Stack Overflow";
abort();
}
top++;
arr[top] = x;
}

/* A class that supports all the stack operations and one additional
operation getMin() that returns the minimum element from stack at
any time. This class inherits from the stack class and uses an
auxiliarry stack that holds minimum elements */
class SpecialStack: public Stack
{
Stack min;
public:
int pop();
void push(int x);
int getMin();
};

/* SpecialStack's member method to insert an element to it. This method
makes sure that the min stack is also updated with appropriate minimum
values */
void SpecialStack::push(int x)
{
if(isEmpty()==true)
{
Stack::push(x);
min.push(x);
}
else
{
Stack::push(x);
int y = min.pop();
min.push(y);
if( x < y )
min.push(x);
else
min.push(y);
}
}

/* SpecialStack's member method to remove an element from it. This method
removes top element from min stack also. */
int SpecialStack::pop()
{
int x = Stack::pop();
min.pop();
return x;
}

/* SpecialStack's member method to get minimum element from it. */
int SpecialStack::getMin()
{
int x = min.pop();
min.push(x);
return x;
}

/* Driver program to test SpecialStack methods */
int main()
{
SpecialStack s;
s.push(10);
s.push(20);
s.push(30);
cout<<s.getMin()<<endl;
s.push(5);
cout<<s.getMin();
return 0;
}
Output:
10
5
Space Optimized Version
The above approach can be optimized. We can limit the number of elements in auxiliary stack. We can
push only when the incoming element of main stack is smaller than or equal to top of auxiliary stack.
Similarly during pop, if the pop off element equal to top of auxiliary stack, remove the top element of
auxiliary stack. Following is modified implementation of push() and pop().
?
/* SpecialStack's member method to insert an element to it. This method
makes sure that the min stack is also updated with appropriate minimum
values */
void SpecialStack::push(int x)
{
if(isEmpty()==true)
{
Stack::push(x);
min.push(x);
}
else
{
Stack::push(x);
int y = min.pop();
min.push(y);

/* push only when the incoming element of main stack is smaller
than or equal to top of auxiliary stack */
if( x <= y )
min.push(x);
}
}

/* SpecialStack's member method to remove an element from it. This method
removes top element from min stack also. */
int SpecialStack::pop()
{
int x = Stack::pop();
int y = min.pop();

/* Push the popped element y back only if it is not equal to x */
if ( y != x )
min.push(x);

return x;
}


Archive for the Algorithm Category
Find an Item in a Sorted Array with Shifted Elements
August 20, 2010
Problem:
You are given a sorted array with shifted elements. Elements can be shifted to the left or right by i
number of places. The sign of i denotes the direction of the shift. For positive i direction of shift is
right and left for negative i.
For example, consider the sorted array 2, 3, 4, 8, 10, 11. A shift of 3 places to the right would be
denoted by i=2 and the shifted array would look like this: 10, 11, 2, 3, 4, 8,
For i=-2, the shifted array would look like: 4, 8, 10, 11, 2, 3.

Write code to find if a given number is present in this array.
Solution:
How can we leverage the sorted nature of the array? Let assume that i was 0. In that case the array
would be sorted and not shifted at all (0 shift). Whats the fastest way to search in a sorted array?
Binary Search! We can split the array in 2 halves and do a recursive search in one of the halves until
we find the number we are looking for ( or not, if its not in the array ). This approach has a running
time of O(log n), which is obviously better than n.
But, the fact that the array is shifted by i number of elements complicates things a little bit. Now,
instead of splitting the array in equal halves, we split the array at the shift index and do a recursive
binary search. There are issues we need to tackle when the shift is greater than the length of the
array or if the shift is negative.
Code: We will assume that we are provided with a method below that does binary search for us and
wont bother implementing it here.
// myArray is the input array
// startIndex and endIndex are the indexes in the
// array where the binary search starts and ends
// The method returns the index of the searchVal
// if found in the array, else it returns -1

int BinarySearch(int[] myArray, int startIndex, int endIndex, int searchVal);

// this method will return the index of the searchVal
// if found, else it return -1
int SearchElement(int[] myArray, int shift, int searchVal)
{
// to take care of scenarios where the shift is more
// than the length of the array
shift = shift % myArray.Length;

// -ve shift can be seen as positive shift equal to
// the length of the array - ( -ve shift)
if (shift < 0)
shift = myArray.Length + shift;

if(myArray[shift] <= searchVal &&
myArray[myArray.Length - 1] >= searchVal)
{
return BinarySearch(myArray, shift, myArray.Length - 1, searchVal);
}
else if(myArray[0] <= searchVal &&
myArray[shift - 1] >= searchVal)
{
return BinarySearch(myArray, 0, shift-1, searchVal);
}
return -1;
}


Q. Given an array of size N. It contains numbers in the range 1 to n. Each number is present
at least once except for 1 number which occurs twice. Find the number.
A.
ES Expected sum of N elements in the list = N ( N + 1) /2, AS Actual Sum of elements in the list
EP Expected Product of N elements in the list = N!, AP Actual Product of elements in the list
M Missing Number , R Repeted Number
AS -M + R = ES
(AP/R) * M = EP
2 Equations , 2 Unknows M/R. Solve it.
Q. Given an array a{N}, create an output array p{N} where
P{i} = Product of a{j} , Where 0 <= j && j != i && j < N ,
E.g. A{1,3,2,4} -> P{24,8,12,6}
A.
Approach 1: Division
Product = 1;
for ( i = 0; i < N; i++)
Product = Product * A[i]; //Get the product of all elements in input array a{}
for ( i = 0 ; i < N ; i++)
P[i] = Product / A[i]; // Divide Product by A[i]
Approach 2: Without Division
A is given array 1 to n
Step1 : traverse A from 1 to n and store cumulative product in array B e.g. B[i] =
prod of all A[j] j=1..to..i
time O(n)
Step2: traverse A from n to 1 and store cumulative product in array C e.g. C[i] =
prod of all A[j] j= iton
time O(n)
Step 3. Traverse from 1..n and create array D
D[i] = B[i-1] * C[i+1]
time O(n)
Total time 3O(n)
Q. Given an array a{N} of random numbers between any range and a number X.
Find in O(n) time and O(1) space a pair of numbers from the array whose sum is
equal to X ?
A.
1. Sort the array O(nlogn)
2. Take two indices : Start ( pointing to 0th element) and End (Pointing to last
element)
3. while ( Start != End) {
if ( X == a[Start] + a[End] ) { // Found }
else ( sum > a[Start] + a[End] ) { Start++; }
else End;
}
//Not found.
Another Option: Use Hashtable if space constraint is not present. Insert each
elements and then check for X a{i} until you get a HIT.
11. Can we apply binary search algorithm to a sorted linked list, why?
Ans: No we cannot apply binary search algorithm to a sorted linked list, since there is no way of indexing
the middle element in the list. This is the drawback in using linked list as a data structure.
12. What do you mean by free pool?
Ans: Pool is a list consisting of unused memory cells which has its own pointer.
13. What do you mean by garbage collection?
Ans: It is a technique in which the operating system periodically collects all the deleted space onto the
free storage list.
It takes place when there is minimum amount of space left in storage list or when CPU is ideal.
The alternate method to this is to immediately reinsert the space into free storage list which is time
consuming.
14. What do you mean by overflow and underflow?
Ans: When new data is to be inserted into the data structure but there is no available space i.e. free
storage list is empty this situation is called overflow.
When we want to delete data from a data structure that is empty this situation is called underflow.
15. What are the disadvantages array implementations of linked list?
Ans:
i) The no of nodes needed cant be predicted when the program is written.
ii) The no of nodes declared must remain allocated throughout its execution
16. What is a queue?
Ans: A queue is an ordered collection of items from which items may be deleted at one end (front end)
and items inserted at the other end (rear end).
It obeys FIFO rule there is no limit to the number of elements a queue contains.
17. What is a priority queue?
Ans: The priority queue is a data structure in which the intrinsic ordering of the elements (numeric or
alphabetic)
Determines the result of its basic operation. It is of two types
i) Ascending priority queue- Here smallest item can be removed (insertion is arbitrary)
ii) Descending priority queue- Here largest item can be removed (insertion is arbitrary)
18. What are the disadvantages of sequential storage?
Ans:
i) Fixed amount of storage remains allocated to the data structure even if it contains less element.
ii) No more than fixed amount of storage is allocated causing overflow
19. What are the disadvantages of representing a stack or queue by a linked list?
Ans:
i) A node in a linked list (info and next field) occupies more storage than a corresponding element in an
array.
ii) Additional time spent in managing the available list.
20. What is dangling pointer and how to avoid it?
Ans: After a call to free(p) makes a subsequent reference to *p illegal, i.e. though the storage to p is freed
but the value of p(address) remain unchanged .so the object at that address may be used as the value of
*p (i.e. there is no way to detect the illegality).Here p is called dangling pointer.
To avoid this it is better to set p to NULL after executing free(p).The null pointer value doesnt reference a
storage location it is a pointer that doesnt point to anything.

21. What are the disadvantages of linear list?
Ans:
i) We cannot reach any of the nodes that precede node (p)
ii) If a list is traversed, the external pointer to the list must be persevered in order to reference the list
again
22. Define circular list?
Ans: In linear list the next field of the last node contain a null pointer, when a next field in the last node
contain a pointer back to the first node it is called circular list.
Advantages From any point in the list it is possible to reach at any other point
23. What are the disadvantages of circular list?
Ans:
i) We cant traverse the list backward
ii) If a pointer to a node is given we cannot delete the node
24. Define double linked list?
Ans: It is a collection of data elements called nodes, where each node is divided into three parts
i) An info field that contains the information stored in the node
ii) Left field that contain pointer to node on left side
iii) Right field that contain pointer to node on right side
25. Is it necessary to sort a file before searching a particular item ?
Ans:
If less work is involved in searching a element than to sort and then extract, then we dont go for sort
If frequent use of the file is required for the purpose of retrieving specific element, it is more efficient to
sort the file.
Thus it depends on situation.
26. What are the issues that hamper the efficiency in sorting a file?
Ans: The issues are
i) Length of time required by the programmer in coding a particular sorting program
ii) Amount of machine time necessary for running the particular program
iii)The amount of space necessary for the particular program .
27. Calculate the efficiency of sequential search?
Ans: The number of comparisons depends on where the record with the argument key appears in the
table
If it appears at first position then one comparison
If it appears at last position then n comparisons
Average=(n+1)/2 comparisons
Unsuccessful search n comparisons
Number of comparisons in any case is O (n).
28. Is any implicit arguments are passed to a function when it is called?
Ans: Yes there is a set of implicit arguments that contain information necessary for the function to
execute and return correctly. One of them is return address which is stored within the functions data
area, at the time of returning to calling program the address is retrieved and the function branches to that
location.
29. Parenthesis is never required in Postfix or Prefix expressions, why?
Ans: Parenthesis is not required because the order of the operators in the postfix /prefix expressions
determines the actual order of operations in evaluating the expression
30. List out the areas in which data structures are applied extensively?
Ans:
Compiler Design,
Operating System,
Database Management System,
Statistical analysis package,
Numerical Analysis,
Graphics,
Artificial Intelligence,
Simulation
31. What are the major data structures used in the following areas : network data model &
Hierarchical data model.
Ans:
RDBMS Array (i.e. Array of structures)
Network data model Graph
Hierarchical data model Trees
32. If you are using C language to implement the heterogeneous linked list, what pointer type will
you use?
Ans: The heterogeneous linked list contains different data types in its nodes and we need a link, pointer
to connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointer
is capable of storing pointer to any type as it is a generic pointer type.
33. Minimum number of queues needed to implement the priority queue?
Ans: Two. One queue is used for actual storing of data and another for storing priorities.
34. What is the data structures used to perform recursion?
Ans: Stack. Because of its LIFO (Last In First Out) property it remembers its caller so knows whom to
return when the function has to return. Recursion makes use of system stack for storing the return
addresses of the function calls.
Every recursive function has its equivalent iterative (non-recursive) function. Even when such equivalent
iterative procedures are written, explicit stack is to be used.
35. What are the notations used in Evaluation of Arithmetic Expressions using prefix and postfix
forms?
Ans: Polish and Reverse Polish notations.
36. Convert the expression ((A + B) * C (D E) ^ (F + G)) to equivalent Prefix and Postfix
notations.
Ans: Prefix Notation:
^ * +ABC DE + FG
Postfix Notation:
AB + C * DE FG + ^

37. Sorting is not possible by using which of the following methods?
(a) Insertion
(b) Selection
(c) Exchange
(d) Deletion
Ans: (d) Deletion.
Using insertion we can perform insertion sort, using selection we can perform selection sort, using
exchange we can perform the bubble sort (and other similar sorting methods). But no sorting method can
be done just using deletion.
38. List out few of the Application of tree data-structure?
Ans:
The manipulation of Arithmetic expression,
Symbol Table construction,
Syntax analysis.
39. List out few of the applications that make use of Multilinked Structures?
Ans: Sparse matrix, Index generation.
40. in tree construction which is the suitable efficient data structure?
(A) Array (b) Linked list (c) Stack (d) Queue (e) none
Ans: (b) Linked list

41. What is the type of the algorithm used in solving the 8 Queens problem?
Ans: Backtracking
42. In an AVL tree, at what condition the balancing is to be done?
Ans: If the pivotal value (or the Height factor) is greater than 1 or less than 1.
43. There are 8, 15, 13, 14 nodes were there in 4 different trees. Which of them could have formed
a full binary tree?
Ans: 15
In general:
There are 2n-1 nodes in a full binary tree.
By the method of elimination:
Full binary trees contain odd number of nodes. So there cannot be full binary trees with 8 or 14 nodes, so
rejected. With 13 nodes you can form a complete binary tree but not a full binary tree. So the correct
answer is 15.
Note: Full and Complete binary trees are different. All full binary trees are complete binary trees but not
vice versa.
44. In RDBMS, what is the efficient data structure used in the internal storage representation?
Ans: B+ tree. Because in B+ tree, all the data is stored only in leaf nodes, that makes searching easier.
This corresponds to the records that shall
be stored in leaf nodes.
45. One of the following tree structures, which is, efficient considering space and time
complexities?
a) Incomplete Binary Tree.
b) Complete Binary Tree.
c) Full Binary Tree.
Ans:
b) Complete Binary Tree.
By the method of elimination:
Full binary tree loses its nature when operations of insertions and deletions are done. For incomplete
binary trees,
extra property of complete binary tree is maintained even after operations like additions and deletions are
done on it.
46. What is a spanning Tree?
Ans: A spanning tree is a tree associated with a network. All the nodes of the graph appear on the tree
once. A minimum spanning tree is a spanning tree organized so that the total edge weight between nodes
is minimized.
47. Does the minimum spanning tree of a graph give the shortest distance between any 2
specified nodes?
Ans: No.
Minimal spanning tree assures that the total weight of the tree is kept at its minimum. But it doesnt mean
that the distance between any two nodes involved in the minimum-spanning tree is minimum.
48. Whether Linked List is linear or Non-linear data structure?
Ans: According to Storage Linked List is a Non-linear one.

Anda mungkin juga menyukai