Next Permutation in Python

The next permutation method rearranges numbers into the lexicographically next greater permutation. If no greater permutation exists, it returns the smallest possible permutation (sorted in ascending order). The solution must be in-place without using extra memory.

Examples

1,2,3 ? 1,3,2
3,2,1 ? 1,2,3  
1,1,5 ? 1,5,1

Algorithm Steps

The algorithm follows these key steps ?

  • Step 1: Find the largest index i where nums[i] < nums[i+1]
  • Step 2: If no such index exists, reverse the entire array
  • Step 3: Find the largest index j where nums[j] > nums[i]
  • Step 4: Swap nums[i] and nums[j]
  • Step 5: Reverse the suffix starting at nums[i+1]

Implementation

def next_permutation(nums):
    # Step 1: Find the largest index i such that nums[i] < nums[i+1]
    i = len(nums) - 2
    while i >= 0 and nums[i] >= nums[i + 1]:
        i -= 1
    
    # Step 2: If no such index exists, reverse the entire array
    if i == -1:
        nums.reverse()
        return nums
    
    # Step 3: Find the largest index j such that nums[j] > nums[i]
    j = len(nums) - 1
    while nums[j] <= nums[i]:
        j -= 1
    
    # Step 4: Swap nums[i] and nums[j]
    nums[i], nums[j] = nums[j], nums[i]
    
    # Step 5: Reverse the suffix starting at nums[i+1]
    nums[i + 1:] = nums[i + 1:][::-1]
    
    return nums

# Test cases
test_cases = [[1, 2, 3], [3, 2, 1], [1, 1, 5], [1, 2, 5, 4, 3]]

for case in test_cases:
    original = case.copy()
    result = next_permutation(case)
    print(f"{original} ? {result}")
[1, 2, 3] ? [1, 3, 2]
[3, 2, 1] ? [1, 2, 3]
[1, 1, 5] ? [1, 5, 1]
[1, 2, 5, 4, 3] ? [1, 3, 2, 4, 5]

How It Works

Let's trace through the example [1, 2, 5, 4, 3] ?

nums = [1, 2, 5, 4, 3]

# Step 1: Find i where nums[i] < nums[i+1]
# i=3: nums[3]=4, nums[4]=3 ? 4 >= 3 (continue)
# i=2: nums[2]=5, nums[3]=4 ? 5 >= 4 (continue)  
# i=1: nums[1]=2, nums[2]=5 ? 2 < 5 (found i=1)

# Step 2: i != -1, so continue

# Step 3: Find j where nums[j] > nums[i=1]=2
# j=4: nums[4]=3 > 2 (found j=4)

# Step 4: Swap nums[1] and nums[4]
# [1, 2, 5, 4, 3] ? [1, 3, 5, 4, 2]

# Step 5: Reverse suffix from index 2
# [1, 3, |5, 4, 2|] ? [1, 3, 2, 4, 5]

print("Final result:", [1, 3, 2, 4, 5])
Final result: [1, 3, 2, 4, 5]

Time and Space Complexity

Metric Complexity Explanation
Time O(n) Single pass to find indices, O(n) for reversal
Space O(1) In-place modification, no extra space

Conclusion

The next permutation algorithm efficiently finds the lexicographically next arrangement in O(n) time and O(1) space. It handles edge cases like the largest permutation by wrapping around to the smallest permutation.

Updated on: 2026-03-25T07:54:30+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements