Forem

Tanishka V
Tanishka V

Posted on

ASSIGNMENT 12

Next Permutation (In-Place & Optimal Solution)

Understanding permutations is key in many algorithmic problems.
Let’s solve a classic one: finding the next lexicographically greater permutation πŸ‘‡

πŸ“Œ Problem Statement

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

⚠️ Constraints:
Must be done in-place
Use only constant extra memory
If no greater permutation exists β†’ return the lowest possible order (sorted ascending)
πŸ§ͺ 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

We want the next bigger arrangement, but just slightly bigger β€” not the maximum.

Find a place where the order breaks
Swap intelligently
Rearrange the remaining part

🧠 Step-by-Step Algorithm
βœ… Step 1: Find the Breakpoint

Traverse from right and find the first index i such that:

nums[i] < nums[i + 1]

❌ If No Breakpoint Found

The array is in descending order (largest permutation)

πŸ‘‰ Simply reverse it:

[3,2,1] β†’ [1,2,3]
βœ… Step 2: Find Next Greater Element

From the right side, find an element nums[j] such that:

nums[j] > nums[i]
πŸ” Step 3: Swap

Swap:

nums[i] ↔ nums[j]
πŸ”„ Step 4: Reverse the Right Half

Reverse elements from:

i + 1 β†’ end

πŸ‘‰ This ensures the smallest possible order after the swap

πŸ’» Python Implementation
def next_permutation(nums):
n = len(nums)

# Step 1: Find breakpoint
i = n - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1

Step 2: If breakpoint exists

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 suffix

left, right = i + 1, n - 1
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1

Enter fullscreen mode Exit fullscreen mode




Example usage

nums = [1, 2, 3]
next_permutation(nums)
print(nums)
🧾 Output
[1, 3, 2]
πŸ” Dry Run (Quick Insight)

For:

[1, 2, 3]
Breakpoint β†’ 2 < 3
Swap 2 and 3 β†’ [1, 3, 2]
Reverse right β†’ already minimal
⚑ Complexity Analysis
Metric Value
Time Complexity O(n)
Space Complexity O(1)

Top comments (0)