• RSS
  • Facebook
  • Twitter

Knowledge is Power.

  • Who you are ?

    Working on machines without understanding them ? Then you should be here..

  • Where you are ?

    Geographical location should not become a barrier to Share our knowledge.

  • What do you do ?

    Puzzles and Interview question are intended to be discussed here.

    Sunday, February 21, 2010

    You have to give a data structure to implement push & pop (as like a simple satck ) in O(1) time &
    find minimum of the current stack also in O(1) time.
    Solution :

    push(x)
    {
    if(stack.isEmpty())
    {
    stack.push(x);
    stack.push(x);
    }
    else
    {
    if(x > stack.top)
    {
    min=stack.top;
    stack.push(x);
    stack.push(min);
    }
    else
    {
    stack.push(x);
    stack.push(x);
    }
    }
    }

    int pop()
    {
    stack.pop();
    return (stack.pop());

    }


    int min()
    {
    return stack.top;
    }

    0 comments:

    Post a Comment