#31

Next Permutation

Medium Pivot + reverse

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Rearrange the array into the next larger ordering of its numbers in dictionary order. If it's already the largest, wrap around to the smallest. Do it in place.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the next bigger arrangement of the same digits.

Why this works: from the right, find the first digit that can be increased (smaller than its right neighbour). Swap it with the smallest bigger digit on its right, then make the tail as small as possible.

Example: [1, 3, 5, 4, 2]

pivot: 3 (since 3 < 5)smallest bigger on right: 4 → swap → [1, 4, 5, 3, 2]reverse tail [5,3,2] → [1, 4, 2, 3, 5]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Sorting the suffix instead of reversing — correct but O(n log n), and it misses the key observation.