Friday 26 February 2016

Nearest Larger Number in Stack

Nearest larger number (NLN) of  element of stack is defined as the closest greater number that are pushed before the element, if there are no such element then NLN will be -1. Given a stack of unique positive integer, return another stack with NLN of each element in the same order of original stack.
Consider example of stack, where 4 is top-most and 3 bottom-most.
3 7 5 6 8 4
Then NLN of each element is given by
-1 -1 7 7 -1 8
Explanation:
  • Number greater than 4 which is closest and below stack is 8,
  • Similarly the number greater 7 is greater than 6 and closest to 6
  • Since there is no element greater than 8 below the stack NLN is -1
and so on ..

You have complete returnStackWithNearestGreater(Stack inputStack) that return the NLN Stack.

Input
N
a1 a2 a3 a4 .. aN
where N is number of elements in the stack, ai are elements of the stack where aN is top-most element of the stack
Ouput:
b1 b2 b3 b4 .. bN
where b1  is NLN for a1, b2 is NLN for a2 and so on….

Solution -:
After deadline is over

1 comment: