DEV Community

Navin S
Navin S

Posted on

πŸ” Next Permutation (Step-by-Step Explanation)

The Next Permutation problem is a classic algorithm question that helps you understand how to generate the next lexicographically greater arrangement of numbers.


πŸ“Œ Problem Statement

Given an array nums, rearrange it into the next greater permutation.

If such a permutation is not possible (i.e., the array is in descending order), rearrange it into the smallest possible order (ascending).

The modification must be done in-place using constant extra memory.


πŸ” Examples

Example 1:
Input: [1, 2, 3]
Output: [1, 3, 2]

Example 2:
Input: [3, 2, 1]
Output: [1, 2, 3]

Example 3:
Input: [1, 1, 5]
Output: [1, 5, 1]


🧠 Intuition

To find the next permutation:

  • We need to find a position where we can increase the number slightly
  • Then rearrange the remaining part to get the smallest possible order

πŸ”„ Approach (Optimal Algorithm)

Step-by-Step:

  1. Find the first decreasing element from the right
    (index i such that nums[i] < nums[i+1])

  2. If such an index exists:

  • Find the element just greater than nums[i] from the right
  • Swap them
  1. Reverse the part of the array after index i

πŸ’» Python Code

def next_permutation(nums):
n = len(nums)
i = n - 2

# Step 1: find decreasing element
while i >= 0 and nums[i] >= nums[i + 1]:
    i -= 1

# Step 2: swap with next greater element
if i >= 0:
    j = n - 1
    while nums[j] <= nums[i]:
        j -= 1
    nums[i], nums[j] = nums[j], nums[i]

# Step 3: reverse the remaining array
left, right = i + 1, n - 1
while left < right:
    nums[left], nums[right] = nums[right], nums[left]
    left += 1
    right -= 1

return nums
Enter fullscreen mode Exit fullscreen mode

print(next_permutation([1, 2, 3]))


🧾 Dry Run

For: nums = [1, 2, 3]

Step 1: Find i β†’ i = 1 (because 2 < 3)
Step 2: Find just greater element β†’ swap 2 and 3 β†’ [1, 3, 2]
Step 3: Reverse after index β†’ no change

Final Output: [1, 3, 2]


⚑ Complexity

Time Complexity: O(n)
Space Complexity: O(1)


πŸ”₯ Why This Works

  • Finds the smallest possible increase
  • Ensures lexicographically next arrangement
  • Uses in-place operations only

⚠️ Edge Case

If the array is completely descending (e.g., [3, 2, 1]):

  • No next permutation exists
  • Reverse entire array β†’ [1, 2, 3]

🏁 Conclusion

Next Permutation is an important problem that teaches:

  • Greedy thinking
  • Array manipulation
  • Lexicographic ordering

Mastering this helps in solving permutation-based problems efficiently.

Top comments (0)