Data Structures & AlgorithmsHardProduct Company SDE · permutation round

Problem: Find the next lexicographic permutation of the digits '1243' (the smallest permutation strictly greater than it). Run the code.

Problem: Find the next lexicographic permutation of the digits '1243' (the smallest permutation strictly greater than it). Run the code.
def next_perm(s):
    a = list(s)
    i = len(a) - 2
    while i >= 0 and a[i] >= a[i + 1]:
        i -= 1
    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 ''.join(a)
print(next_perm('1243'))
What is printed?
  1. A. 1342
  2. B. 1423
  3. C. 2134
  4. D. 1324

Correct answer: D. 1324

The pivot is 2 (index 1), it swaps with the smallest larger suffix digit 3 to give 1 3 4 2, and the suffix then sorts to 2 4, so the answer is 1324.

More Coding Interview Problems questions

Exams that ask this topic