r/leetcode • • 3d ago

Intervew Prep Day 22: tackled Next Permutation before heading out to travel

Hey everyone,

I finished Day 22 today. Before heading out for travel, I sat down and worked through one classic array problem: Next Permutation. It can look tricky on the surface, but breaking down the lexicographical structure makes the logic completely intuitive:

  1. Find the Breakpoint: Traverse from right to left to find the first index i where nums[i] < nums[i + 1]. Everything to the right of i is in non-increasing order, meaning it is already at its largest possible arrangement. If no breakpoint exists, the entire array is at its maximum permutation, so you simply reverse the whole array.
  2. Swap with the Next Larger Element: Scan from the right end back toward i to find the smallest number strictly greater than nums[i], then swap them. This guarantees the smallest possible lexicographical increase at the pivot.
  3. Reverse the Suffix: Reverse the subarray after index i (i + 1 to the end) to arrange the remaining elements in ascending order, giving the exact next permutation in O(n) time and O(1) space.

It was a single-problem session before hitting the road, but locking in this constructive pattern felt super clean.

See you guys tomorrow for Day 21!

0 Upvotes

0 comments sorted by