Data Structures & AlgorithmsVery hardProduct company OA

What is the next lexicographic permutation of [1, 5, 8, 4, 7, 6, 5, 3, 1]?

  1. A. [1, 5, 8, 5, 7, 6, 4, 3, 1]
  2. B. [1, 5, 8, 4, 7, 6, 5, 1, 3]
  3. C. [1, 5, 8, 5, 1, 3, 4, 6, 7]
  4. D. [1, 5, 8, 6, 1, 3, 4, 5, 7]

Correct answer: C. [1, 5, 8, 5, 1, 3, 4, 6, 7]

Find the rightmost i with a[i] < a[i+1]: a[3] = 4 (the suffix 7 6 5 3 1 is non-increasing). Swap 4 with the smallest suffix value greater than 4, which is 5 → [1, 5, 8, 5, 7, 6, 4, 3, 1], then REVERSE the suffix to make it smallest: 1, 3, 4, 6, 7. Forgetting the reversal gives [1, 5, 8, 5, 7, 6, 4, 3, 1]; swapping 4 with 6 gives [1, 5, 8, 6, 1, 3, 4, 5, 7].

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic