Article start
DSA Course: Interview Patterns and Problem Solving
Module 10: Sorting & Searching

Next Permutation: Pivot and Suffix Reversal Pattern

Generate the next lexicographic arrangement in-place.

May 29, 2026·25

Learning Outcome

After this lesson, you should be able to identify the rightmost pivot and rebuild the smallest larger suffix.

Problem Statement

Given an integer array, rearrange it into the next lexicographically greater permutation. If none exists, rearrange it into the lowest order.

InputOutputWhy
nums = [1,2,3][1,3,2]The next arrangement after 1,2,3 is 1,3,2.

Brute Force Approach

Generate all permutations, sort them, and select the next one. This is factorial time.

Optimized Approach

Find the rightmost index i where nums[i] < nums[i + 1]. Swap it with the smallest larger value in the suffix, then reverse the suffix.

Exact Pseudocode

i = n - 2
while i >= 0 and nums[i] >= nums[i + 1]:
  i -= 1
if i >= 0:
  j = n - 1
  while nums[j] <= nums[i]:
    j -= 1
  swap nums[i], nums[j]
reverse nums from i + 1 to end

Reference Code

class Solution:
    def nextPermutation(self, nums):
        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:])

Sample Dry Run

StepStateResult
Find pivotIn [1,2,3], i = 1 because 2 < 3pivot is 2
Find next largerj = 2, value 3swap 2 and 3
Reverse suffixsuffix after pivot is [2]unchanged
Return[1,3,2]next permutation

Complexity

MeasureValueReason
TimeO(n)At most three linear scans are performed.
SpaceO(1)The array is modified in-place.

Edge Cases

  • A fully descending array becomes ascending.
  • Duplicates are allowed.
  • Single-element arrays stay unchanged.

Interview Checklist

  • Find the rightmost increasing pivot.
  • Swap with the rightmost larger suffix value.
  • Reverse only the suffix after the pivot.

FAQs

Why reverse the suffix?

The suffix is descending, so reversing it gives the smallest possible order after making the prefix larger.

What if no pivot exists?

The array is the largest permutation, so reversing the full array returns the smallest permutation.

What is the core pattern?

Lexicographic pivot plus suffix reversal.

Test your knowledge

Take a quick quiz based on this chapter.

Discussion

0 comments

Sign in to share a question or add to the discussion.
Start the discussion

Ask a question or share what stood out to you.