3

How do you solve this problem in O(n) time?

Given an unsorted array of integers, design algorithms to transform the array such that the integers are replaced by the nearest bigger integer on their right. If there is no bigger integer on its right, the integer remains the same. For example, the following array of integers

2 1 4 5 3 6 7 9 4 8

should become

4 4 5 6 6 7 9 9 8 8
4
  • Are you sure there is O(n) solution?
    – Saeid
    Nov 22, 2015 at 15:22
  • @sudomakeinstall2 there is. the algorithm is actually quite trivial
    – user4668606
    Nov 22, 2015 at 15:27
  • @paul If you mean the algorithm provided by orlp, then there should be a misunderstanding.
    – Saeid
    Nov 22, 2015 at 15:31
  • @cppgondnler it's actually pretty close. Or to be more precise, the algorithm you presented should do the job, if implemented properly, except for the fact that there's an additional storage required for elements that were traversed and replaced.
    – user4668606
    Nov 22, 2015 at 15:51

1 Answer 1

4
  • Init Stack of integers

  • From left to right.

  • Pop from stack while element is smaller, and replace it with the current

  • Add id of element to stack

Note that the stack will be strictly decreasing. And that each element is popped/added max 1 time. Hence O(N)

Example code in Python:

l = [2, 1, 4, 5, 3, 6, 7, 9, 4, 8]
s = [0]
for i in range(1, len(l)):
    while s and l[i] > l[s[-1]]:
        l[s.pop()] = l[i]
    s.append(i)
1
  • 1
    You were a minute earlier and properly explained it.
    – orlp
    Nov 22, 2015 at 15:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.