ProgrammingVery hardTCS NQT · Accenture

For the array a = [1, 2, 3, 5, 4] the next permutation (in lexicographic order) is computed by the standard procedure: find the last i with a[i] < a[i+1], swap a[i] with the smallest larger element to its right, then reverse the suffix after position i. What is the result printed as a string of digits?

For the array a = [1, 2, 3, 5, 4] the next permutation (in lexicographic order) is computed by the standard procedure: find the last i with a[i] < a[i+1], swap a[i] with the smallest larger element to its right, then reverse the suffix after position i. What is the result printed as a string of digits?
i = largest index with a[i] < a[i+1]
j = largest index with a[j] > a[i]
swap a[i], a[j]; reverse a[i+1..n-1]
Print a
  1. A. 12345
  2. B. 12435
  3. C. 12453
  4. D. 45321

Correct answer: B. 12435

The last ascent is 3 < 5, so 3 is swapped with 4 (the smallest larger value to its right) giving 1 2 4 5 3, and the suffix 5 3 is reversed to 3 5, giving 1 2 4 3 5. Printing the sorted array, skipping the suffix reversal, and printing the reversed array each give different strings.

More Pseudocode and Code Tracing questions

Exams that ask this topic