Next Permutation
Introduction The Next Permutation problem is an important concept in algorithms. It helps us find the next lexicographically greater arrangement of numbers. Problem Statement Given an array of inte...

Source: DEV Community
Introduction The Next Permutation problem is an important concept in algorithms. It helps us find the next lexicographically greater arrangement of numbers. Problem Statement Given an array of integers, rearrange them into the next greater permutation. If no greater permutation exists, rearrange it to the lowest possible order (sorted in ascending order). Approach We follow these steps: Find the first index i from the end such that: arr[i] < arr[i + 1] If no such index exists: Reverse the entire array (last permutation case) Otherwise: Find index j such that arr[j] > arr[i] Swap arr[i] and arr[j] Reverse the elements from i+1 to the end Python Code python def nextPermutation(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: If found 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 rest left, right = i + 1, n - 1 while left < right: