Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the next lexicographic permutation of a digit list in place.

Problem: Find the next lexicographic permutation of a digit list in place.
def next_perm(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(next_perm([1, 3, 5, 4, 2]), next_perm([3, 2, 1]), next_perm([1, 1, 5]))
What is printed?
  1. A. [1, 4, 5, 3, 2] [1, 2, 3] [1, 5, 1]
  2. B. [1, 3, 5, 2, 4] [3, 2, 1] [1, 5, 1]
  3. C. [1, 4, 2, 3, 5] [3, 2, 1] [5, 1, 1]
  4. D. [1, 4, 2, 3, 5] [1, 2, 3] [1, 5, 1]

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

Find the rightmost i with a[i] < a[i + 1] (3 at index 1), swap it with the smallest larger value to its right (4), then reverse the suffix to make it ascending: [1, 4, 2, 3, 5]. A fully descending list wraps to the smallest. Forgetting the reverse gives [1, 4, 5, 3, 2]. O(n).

More Coding Interview Problems questions

Exams that ask this topic