InterviewHubPRO
Section Overview
Q16

Question 16 of 100

Part 2: Arrays, Strings & Hash Maps (6 - 18)

16%
DSA Patterns (Multi-Lang)•Part 2: Arrays, Strings & Hash Maps (6 - 18)

Next Permutation.

In Simple Words:

  1. Find rightmost pivot index $i$ where nums[i] < nums[i+1].
  2. Find successor index $j$ from right where nums[j] > nums[i] and swap them.
  3. Reverse suffix after $i$ to get lexicographically smallest continuation.
  • Time: $O(N)$ | Space: $O(1)$
Multi-Language Solutions
Switch tabs or choose All
def nextPermutation(nums: list[int]) -> None:
    i = len(nums) - 2
    while i >= 0 and nums[i] >= nums[i + 1]:
        i -= 1
    if i >= 0:
        j = len(nums) - 1
        while nums[j] <= nums[i]:
            j -= 1
        nums[i], nums[j] = nums[j], nums[i]
    nums[i + 1:] = reversed(nums[i + 1:])