Question : Get Minimum element in O(1) from input numbers..
- With any traditional way we can't get minimum element in O(1)
- so we need to come up with different data structure.
- As its very old and famous question We are directly explaining logic
Logic 1)
Keep Two Stacks A and B.
A will contain all numbers which are input by users.
B will contain only minimum number from all input numbers.
ex. Input 10,20,5,30,2
Pros
- storing minimum element for each input.
- if current minimum element is popped , we still have minimum element in present stack
Cons
- O(n) Extra Space.
Thanks Dhaval for Code.
C Working Code : Find here : http://ideone.com/qOtFoG
C++ Working code : Find here : http://ideone.com/mgtTQY
Logic 2)
Instead of keeping a stack of minimum elements in B, we can optimism the solution with single minimum number.
B can be a pointer which always points to Minimum value from inputted elements in A.
( Ba can be pointer type variable or even simple integer which stores index value "i" of minimum element in A )
Thanks Dhaval for suggesting Logic 2) & writing the code
Code Coming soon :
- With any traditional way we can't get minimum element in O(1)
- so we need to come up with different data structure.
- As its very old and famous question We are directly explaining logic
Logic 1)
Keep Two Stacks A and B.
A will contain all numbers which are input by users.
B will contain only minimum number from all input numbers.
ex. Input 10,20,5,30,2
Consider the following input A B (minimum elements)
2 --> TOP 2 ... 30 5 ... 5 5 (smallest in 10,20,5 input) 20 10 (smallest in 10,20 input) 10 10 (smallest at beginning)
so as shown in figure B (minimum element stack will keep all smallest numbers wrt input)
Pros
- storing minimum element for each input.
- if current minimum element is popped , we still have minimum element in present stack
Cons
- O(n) Extra Space.
Thanks Dhaval for Code.
C Working Code : Find here : http://ideone.com/qOtFoG
C++ Working code : Find here : http://ideone.com/mgtTQY
Logic 2)
Instead of keeping a stack of minimum elements in B, we can optimism the solution with single minimum number.
B can be a pointer which always points to Minimum value from inputted elements in A.
( Ba can be pointer type variable or even simple integer which stores index value "i" of minimum element in A )
Thanks Dhaval for suggesting Logic 2) & writing the code
Code Coming soon :