PLEASE HELP

HOW CAN I SOLVE THIS USING STACK?

1 Like

well, have you solved this question ? I think it can be solved in O(n) without using stack as well.

1 Like

yes i have solved it without using stack…i was just thinking how to solve this using stack…

1 Like

yes i have applied this approach…

1 Like

Initially if N = 1, print -1. Here’s a rough algorithm for the rest:

  1. while input != empty(), S.push(input())
  2. A.push(S.pop()) while the popped elements are in reverse order
  3. If S = empty(), print -1
  4. L <- S.pop()
  5. O(push(S.pop())) while S != empty()
  6. print O.pop() while O != empty()
  7. T <- 9
  8. O.push(num <- A.pop()) and T <- min(T, num) while A != empty()
  9. Print T
  10. While O != empty(), num <- O.pop() and print s.t.:
    i. T is not printed the first time it is encountered
    ii. Print L when L = min(L, num)

Done! Here’s the C++14 implementation.

1 Like

Done! Here ’s the C++14 implementation.

Is this the approach you wanted?

yes…thanks brother

1 Like

No problem :slight_smile: