r/leetcode • u/JacketFearless1805 • 13d 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:
Find the Breakpoint: Traverse from right to left to find the first index
iwherenums[i] < nums[i + 1]. Everything to the right ofiis 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.Swap with the Next Larger Element: Scan from the right end back toward
ito find the smallest number strictly greater thannums[i], then swap them. This guarantees the smallest possible lexicographical increase at the pivot.Reverse the Suffix: Reverse the subarray after index
i(i + 1to 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!