Leetcode 31: Next Permutation

grid47
grid47
Exploring patterns and algorithms
Nov 3, 2024 5 min read

A flowing sequence of shapes or words shifting and reshaping into a new, calming formation.
Solution to LeetCode 31: Next Permutation Problem

You are given an array of integers ’nums’. Find the next lexicographically greater permutation of the array. If no such permutation exists, return the smallest possible arrangement (sorted in ascending order). The result must be computed in place with no extra space.
Problem
Approach
Steps
Complexity
Input: The input is an array of integers 'nums' where each element is a non-negative integer.
Example: nums = [1,2,3]
Constraints:
• 1 <= nums.length <= 100
• 0 <= nums[i] <= 100
Output: The output is the next lexicographically greater permutation of the input array, or the smallest possible permutation if no greater permutation exists.
Example: For nums = [1,2,3], the output is [1,3,2].
Constraints:
Goal: The goal is to determine the next permutation of the input array by modifying the array in place.
Steps:
• Find the largest index 'i' such that nums[i] < nums[i+1]. If no such index exists, reverse the entire array.
• Find the largest index 'j' such that nums[j] > nums[i]. Swap nums[i] and nums[j].
• Reverse the sub-array from nums[i+1] to the end of the array.
Goal: The size of the array can be at most 100, and each integer in the array will be between 0 and 100.
Steps:
• nums.length <= 100
• nums[i] <= 100
Assumptions:
• The array may contain repeated elements, which should be handled appropriately.
Input: nums = [1,2,3]
Explanation: The next permutation of [1,2,3] is [1,3,2] because 3 is the next greater number after 2 in the lexicographical order.

Input: nums = [3,2,1]
Explanation: The next permutation of [3,2,1] is [1,2,3] because no greater permutation exists, so the array is sorted in ascending order.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus