Back to articles
Finding the Next Permutation of an Array in Python

Finding the Next Permutation of an Array in Python

via Dev.to PythonSri Mahalakshmi

Problem Explanation A permutation is an arrangement of elements in a specific order. Given an array nums , your task is to find the next permutation — the next greater arrangement of numbers in lexicographical order . If such an arrangement is not possible (i.e., the array is in descending order), you must rearrange it into the smallest possible order (ascending) . Example: Input: nums = [1, 2, 3] Output: [1, 3, 2] Input: nums = [3, 2, 1] Output: [1, 2, 3] Method Used: Next Permutation Algorithm (Step-based Approach) Idea: Find the first decreasing element from the right Find the next greater element and swap Reverse the remaining part Why This Method? Time complexity: O(n) Space complexity: O(1) (in-place) Efficient and commonly asked in interviews Python Code with Explanation class Solution : def nextPermutation ( self , nums ): Defines the function to modify the array in-place. i = len ( nums ) - 2 Start from the second last index. while i >= 0 and nums [ i ] >= nums [ i + 1 ]: i -=

Continue reading on Dev.to Python

Opens in a new tab

Read Full Article
2 views

Related Articles