Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Rearrange the digits of a version list into the next lexicographically greater permutation.

Problem: Rearrange the digits of a version list into the next lexicographically greater permutation.
def nxt(a):
    i = len(a) - 2
    while i >= 0 and a[i] >= a[i+1]: i -= 1
    if i >= 0:
        j = len(a) - 1
        while a[j] <= a[i]: j -= 1
        a[i], a[j] = a[j], a[i]
    a[i+1:] = reversed(a[i+1:])
    return a
print(nxt([1, 3, 5, 4, 2]))
What is printed?
  1. A. [1, 4, 5, 3, 2]
  2. B. [1, 4, 2, 5, 3]
  3. C. [1, 4, 2, 3, 5]
  4. D. [1, 3, 5, 2, 4]

Correct answer: C. [1, 4, 2, 3, 5]

The rightmost ascent is at 3 (index 1). Swap it with the smallest larger value to its right, 4, giving [1,4,5,3,2], then reverse the suffix to make it smallest: [1,4,2,3,5]. Forgetting the reverse leaves [1,4,5,3,2].

More Coding Interview Problems questions

Exams that ask this topic