data structur e questions

Upload: adddata

Post on 02-Jun-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/11/2019 Data Structur e Questions

    1/15

    DATA STRUCTUR E QUESTIONS

    Design and Implement Special Stack Data Structure | Added SpaceOptimized VersionSeptember 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.

  • 8/11/2019 Data Structur e Questions

    2/15

    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

  • 8/11/2019 Data Structur e Questions

    3/15

    18

    Auxiliary Stack

    18

  • 8/11/2019 Data Structur e Questions

    4/15

    #include

    #include

    usingnamespacestd;

    /* 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; }

    boolisEmpty();

    boolisFull();

    intpop();

    voidpush(intx);

    };

    /* Stack's member method to check if the stack is iempty */

    boolStack::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)

    returntrue;

    return

    false;

    }

    /* Stack's member method to remove an element from it */

    intStack::pop()

    {

    if(isEmpty())

    {

    cout

  • 8/11/2019 Data Structur e Questions

    5/15

    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 */

    classSpecialStack: publicStack

    {

    Stack min;

    public:

    intpop();

    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. */

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

    returnx;

  • 8/11/2019 Data Structur e Questions

    6/15

    }

    /* Driver program to test SpecialStack methods */

    intmain()

    {

    SpecialStack s;

    s.push(10);

    s.push(20);

    s.push(30);

    cout

  • 8/11/2019 Data Structur e Questions

    7/15

    removes top element from min stack also. */

    int

    SpecialStack::pop()

    {

    intx = Stack::pop();

    inty = 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 ElementsAugust 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 negativei.

    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.

    http://crackinterview.wordpress.com/2010/08/20/find-an-item-in-a-sorted-array-with-shifted-elements/http://crackinterview.files.wordpress.com/2010/08/sorted-array-shifted-elements.pnghttp://crackinterview.wordpress.com/2010/08/20/find-an-item-in-a-sorted-array-with-shifted-elements/
  • 8/11/2019 Data Structur e Questions

    8/15

    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 doesbinary searchfor 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;

    http://dev-interview-questions.blogspot.com/2008/12/binary-search-sorted-array.htmlhttp://dev-interview-questions.blogspot.com/2008/12/binary-search-sorted-array.htmlhttp://dev-interview-questions.blogspot.com/2008/12/binary-search-sorted-array.htmlhttp://dev-interview-questions.blogspot.com/2008/12/binary-search-sorted-array.html
  • 8/11/2019 Data Structur e Questions

    9/15

    if(myArray[shift] = searchVal)

    {

    return BinarySearch(myArray, shift, myArray.Length - 1, searchVal);

    }else if(myArray[0] = 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 P{24,8,12,6}

    A.

    Approach 1: Division

    Product = 1;

    for ( i = 0; i < N; i++)

  • 8/11/2019 Data Structur e Questions

    10/15

    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 allA[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.

  • 8/11/2019 Data Structur e Questions

    11/15

    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 indexingthe 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 thefree 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 timeconsuming.

    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. freestorage 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 oralphabetic)

    Determines the result of its basic operation. It is of two typesi) 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 anarray.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 freedbut 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 astorage location it is a pointer that doesnt point to anything.

  • 8/11/2019 Data Structur e Questions

    12/15

    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 listagain

    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 nodecontain a pointer back to the first node it is called circular list.AdvantagesFrom 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 backwardii) 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 nodeii) Left field that contain pointer to node on left sideiii) 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 tosort 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 programii) Amount of machine time necessary for running the particular programiii)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 thetableIf it appears at first position then one comparisonIf it appears at last position then n comparisonsAverage=(n+1)/2 comparisonsUnsuccessful search n comparisonsNumber 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 toexecute and return correctly. One of them is return address which is stored within the functions dataarea, at the time of returning to calling program the address is retrieved and the function branches to thatlocation.

    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 expressionsdetermines the actual order of operations in evaluating the expression

  • 8/11/2019 Data Structur e Questions

    13/15

    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:RDBMSArray (i.e. Array of structures)Network data modelGraphHierarchical data modelTrees

    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, pointerto connect them. It is not possible to use ordinary pointers for this. So we go for void pointer. Void pointeris 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 toreturn when the function has to return. Recursion makes use of system stack for storing the returnaddresses 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 postfixforms?Ans:Polish and Reverse Polish notations.

    36. Convert the expression ((A + B) * C (D E) ^ (F + G)) to equivalent Prefix and Postfixnotations.Ans:Prefix Notation:^* +ABCDE + FGPostfix Notation:AB + C * DEFG + ^

    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

  • 8/11/2019 Data Structur e Questions

    14/15

    exchange we can perform the bubble sort (and other similar sorting methods). But no sorting method canbe 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) noneAns:(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 formeda full binary tree?Ans:15In 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, sorejected. With 13 nodes you can form a complete binary tree but not a full binary tree. So the correctanswer is 15.Note:Full and Complete binary trees are different. All full binary trees are complete binary trees but notvice 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 shallbe stored in leaf nodes.

    45. One of the following tree structures, which is, efficient considering space and timecomplexities?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 incompletebinary trees,extra property of complete binary tree is maintained even after operations like additions and deletions aredone on it.

  • 8/11/2019 Data Structur e Questions

    15/15

    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 treeonce. A minimum spanning tree is a spanning tree organized so that the total edge weight between nodesis 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 meanthat 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.