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:
Find the first decreasing element from the right
(indexisuch that nums[i] < nums[i+1])If such an index exists:
- Find the element just greater than nums[i] from the right
- Swap them
- 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
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)