logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
leetcode
Title
Table Of Contents
easy
13. Roman to Integer
14. Longest Common Prefix
20. Valid Parentheses
26. Remove Duplicates from Sorted Array
35. Search Insert Position
69. Sqrt(x)
70. Climbing Stairs
88. Merge Sorted Array (In-Place)
104. Maximum Depth of Binary Tree
118. Pascal's Triangle
121. Best Time to Buy and Sell Stock
205. Isomorphic Strings
242. Valid Anagram
283. Move Zeroes
345. Reverse Vowels of a String
605. Can Place Flowers
704. Binary Search
796. Rotate String
1071. Greatest Common Divisor of Strings
1299. Replace Elements with Greatest Element on Right Side
1431. Kids With the Greatest Number of Candies
1614. Maximum Nesting Depth of the Parentheses
1752. Check if Array Is Sorted and Rotated
1768. Merge Strings Alternately
1903. Largest Odd Number in String
2965. Find Missing and Repeated Values
hard
25. Reverse Nodes in k-Group
26. Remove Duplicates from Sorted Array
27. Remove Element
42. Trapping Rain Water
51. N-Queens
55. Jump Game
80. Remove Duplicates from Sorted Array II
88. Merge Sorted Array
121. Best Time to Buy and Sell Stock
122. Best Time to Buy and Sell Stock II
189. Rotate Array
274. H-Index
medium
2. Add Two Numbers
3. Longest Substring Without Repeating Characters
5. Longest Palindromic Substring
8. String to Integer (atoi)
11. Container With Most Water
15. 3Sum
17. Letter Combinations of a Phone Number
19. Remove Nth Node From End of List
22. Generate Parentheses
33. Search in Rotated Sorted Array
34. Find First and Last Position of Element in Sorted Array
48. Rotate Image
49. Group Anagrams
50. Pow(x, n)
53. Maximum Subarray
54. Spiral Matrix
56. Merge Intervals
61. Rotate List
73. Set Matrix Zeroes
74. Search a 2D Matrix
75. Sort Colors
78. Subsets
137. Single Number II
138. Copy List with Random Pointer
150. Evaluate Reverse Polish Notation
151. Reverse Words in a String
153. Find Minimum in Rotated Sorted Array
155. Min Stack
162. Find Peak Element
169. Majority Element
198. House Robber
207. Course Schedule
215. Kth Largest Element in an Array
227. Basic Calculator II
236. Lowest Common Ancestor of a Binary Tree
237. Delete Node in a Linked List
238. Product of Array Except Self
451. Sort Characters By Frequency
540. Single Element in a Sorted Array
560. Subarray Sum Equals K
636. Exclusive Time of Functions
875. Koko Eating Bananas
1011. Capacity To Ship Packages Within D Days
1101. The Earliest Moment When Everyone Become Friends
1283. Find the Smallest Divisor Given a Threshold
2140. Solving Questions With Brainpower
3169. Count Days Without Meetings
3481. Apply Substitutions
rotate-array-approach-1
189. Rotate Array (Approach 2 )
189. Rotate Array (Approach 1 )
number-of-islands-approach-1
200. Number of Islands (Approach 2)
200. Number of Islands (Approach 1)
meeting-rooms-ii-approach-1
253. Approach Using Priority Queue
253. Meeting Rooms II
misc
Calculate Floor & Ceiling
Find Nth Root Of M
Flatten A Linked List
Implement Lower Bound
Implement Upper Bound
Number of occurrence
take-u-forward
Recently Solved
arrays
The Ultimate Array Pattern Playbook
faqs-hard
Count Inversions in an Array
Find The Repeating And Missing Number
Majority Element II
Maximum Product Subarray
Merge Sorted Array (In-Place)
Reverse Pairs
faqs-medium
3. 3Sum
4. 4Sum
Maximum Subarray
Leaders in an Array
Majority Element
Next Permutation
Get specific element from Pascal's Triangle
Pascal's Triangle II (Row Generation)
Generate Pascal's Triangle (Full)
Spiral Matrix Traversal
Rearrange Array Elements by Sign
Rotate Image
Sort Colors (Dutch National Flag)
Two Sum
fundamentals
Check if Array is Sorted
Largest Element in an Array
Array Rotation (Left and Right)
Left Rotate Array by One
Linear Search
Max Consecutive Ones
Second Largest Element in an Array
Single Number
logic-building
Missing Number
Intersection of Two Sorted Arrays (with Duplicates)
Move Zeros to End
Remove Duplicates from Sorted Array
Union of Two Sorted Arrays
binary-search
About
d-arrays
Find Row With Maximum 1'S
Search In A 2D Matrix
faqs
Aggressive Cows
Allocate Books
Find Peak Element
Kth Element Of 2 Sorted Arrays
Minimise Max Distance to Gas Stations
Split Array - Largest Sum
fundamentals
Lower Bound
Binary Search
Upper Bound
logic-building
Count Occurrences in a Sorted Array
Find Minimum in Rotated Sorted Array
Find out how many times the array is rotated
Find First and Last Position of Element in Sorted Array
Floor and Ceil in Sorted Array
Kth Missing Positive Number
Search in Rotated Sorted Array
Search in Rotated Sorted Array II (With Duplicates)
Search Insert Position
Single Element in a Sorted Array
on-answers
Capacity To Ship Packages Within D Days
Find Nth Root of M
Find Square Root of a Number
Smallest Divisor Given a Threshold
Koko Eating Bananas (Minimum Rate)
Minimum Days to Make M Bouquets
Painter's Partition Problem
Split Array Largest Sum
hashing
Theory
faqs
Subarray Sum Equals K
Count Subarrays with Given XOR K
Largest Subarray with 0 Sum
Longest Consecutive Sequence
Longest Subarray with Sum K
recursion
faqs-medium
Combination Sum II (Unique Combinations)
Combination Sum (Unbounded)
Subset Sums
hard
Letter Combinations of a Phone Number
implementation-problems
Generate Parentheses
Power Function: pow(x, n)
Subsets (The Power Set)
subsequence-pattern-problems
Subsequence Sum Existence
Count All Subsequences With Sum K
sorting
Bubble Sort
Insertion Sort
Merge Sort
Quick Sort
Selection Sort
string
Isomorphic Strings
Largest Odd Number in String
Longest Common Prefix
Reverse Words in a String
Code Scratch›take u forward›arrays›faqs medium

Next Permutation

# Question

Given an array of integers nums, find its next lexicographically greater permutation in-place using O(1)O(1)O(1) extra memory. If such an arrangement is impossible (i.e., the array is sorted in descending order), rearrange it into the lowest possible order (ascending).

# Solution

# Pattern

Suffix Reversal (Narayana Pandita's Algorithm) Identify the longest non-increasing suffix. The element immediately preceding it is the "pivot". Swap the pivot with its next-largest successor in the suffix, then reverse the suffix to yield the smallest possible lexicographical jump.

# How to Identify

  • The problem explicitly asks for a "next", "previous", or "k-th" permutation.
  • The term "lexicographical order" is emphasized.
  • Requirements force in-place modification without utilizing combinatorial generation algorithms.

# Description

Step-by-step explanation:

  1. Find the Pivot: Traverse the array from right to left to find the first pair of adjacent elements where nums[i] < nums[i+1]. The index i is our pivot. (Everything to the right of the pivot is strictly in descending/non-increasing order, meaning that suffix is at its maximum possible permutation).
  2. Handle Max Permutation: If no such pivot exists (i.e., the pointer drops below 0), the entire array is in descending order. It is the absolute last permutation. We simply reverse the whole array to reset to the first permutation.
  3. Find the Successor: If a pivot is found, we traverse from right to left again to find the first element nums[j] that is strictly greater than nums[pivot]. This is the smallest possible number we can swap the pivot with to increase the overall sequence.
  4. Swap: Swap the elements at pivot and successor.
  5. Reverse Suffix: Even after the swap, the suffix remains in descending order. To make the sequence as small as possible (the immediate next permutation), the suffix must be in ascending order. We achieve this efficiently by simply reversing the suffix from pivot + 1 to the end.

# The Intuition

Think of permutation like an odometer or a dictionary. Consider the sequence [1, 3, 5, 4, 2]. If you want to find the very next word in a dictionary, you look at the suffix [5, 4, 2]. This suffix is already fully maximized (descending). You cannot rearrange 5, 4, 2 to make a larger number. Therefore, you must increment the number just before it, which is 3 (the pivot). What do you replace 3 with? You look in your suffix for the smallest number larger than 3. That's 4. Swap them: [1, 4, 5, 3, 2]. Now, your prefix [1, 4] is correct, but your suffix [5, 3, 2] is huge. To make the smallest possible word starting with 1, 4, the remaining letters must be in alphabetical (ascending) order. Since [5, 3, 2] is currently strictly descending, reversing it makes it strictly ascending: [2, 3, 5]. Final result: [1, 4, 2, 3, 5].

# Complexity

LabelWorstAverage
Time ComplexityO(N)O(N)O(N)O(N)O(N)O(N)
Space ComplexityO(1)O(1)O(1)O(1)O(1)O(1)

# Time Complexity

Finding the pivot takes O(N)O(N)O(N). Finding the successor takes O(N)O(N)O(N). Reversing the suffix takes O(N)O(N)O(N). The sequential operations scale strictly linearly. Thus, worst-case time complexity is O(N)O(N)O(N).

# Space Complexity

The algorithm modifies the array strictly in-place, requiring only a few integer pointers (pivot, successor). Thus, auxiliary space is O(1)O(1)O(1).

# Code

class Solution {
    public void nextPermutation(int[] nums) {
        if (nums == null || nums.length <= 1) return;
        
        int pivot = nums.length - 2;
        
        // 1. Find the first dip from the right
        while (pivot >= 0 && nums[pivot] >= nums[pivot + 1]) {
            pivot--;
        }
        
        // 2. If a dip exists, find the rightmost element greater than the dip
        if (pivot >= 0) {
            int successor = nums.length - 1;
            while (nums[successor] <= nums[pivot]) {
                successor--;
            }
            swap(nums, pivot, successor);
        }
        
        // 3. Reverse the descending suffix to make it ascending
        reverse(nums, pivot + 1, nums.length - 1);
    }
    
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
    
    private void reverse(int[] nums, int i, int j) {
        while (i < j) {
            swap(nums, i++, j--);
        }
    }
}

# Caveats

  • Duplicate Elements: The condition nums[pivot] >= nums[pivot + 1] (note the >=) is critical. If you use >, the algorithm fails on arrays with duplicates (e.g., [1, 1, 5]), either deadlocking or swapping incorrectly.
  • Sorting vs Reversing: Never use Arrays.sort() on the suffix. It degrades the complexity to O(Nlog⁡N)O(N \log N)O(NlogN). Mathematical proof guarantees the suffix is always descending, making a simple two-pointer reverse O(N)O(N)O(N) mathematically sound and optimal.
  • Lexicographical Generation: This algorithm is the basis for generating all permutations in order.
  • Dictionary Order: The logic mimics how words are ordered in a dictionary (e.g., "ABZ" -> "AC B").
  • Partial Sorting: Reversing a descending suffix is a shortcut for sorting it in ascending order.
  • Pivot Logic: This "pivot and swap" pattern appears in other problems like "Previous Permutation with One Swap."

# Concepts to Think About

  • Previous Permutation: The exact inverse of this algorithm yields the previous permutation. You look for the first ascending break from the right, swap it with the largest element smaller than it, and reverse the suffix.
  • Factorial Number System: Permutations can be mapped 1-to-1 with integers using the Factorial Number System (Lehmer codes). This is how you calculate the exact rank/index of a permutation mathematically.
  • Graphing the Array: If you plot the array values on a line graph, the algorithm essentially finds the highest peak from the right, and modifies the element immediately preceding that peak.

# Logical Follow-up

Question: How would you find the kkk-th permutation of the sequence [1, 2, ..., n] without generating all permutations in between? (LeetCode 60: Permutation Sequence)

Solution: You cannot use the "Next Permutation" algorithm kkk times, as that would be O(k⋅n)O(k \cdot n)O(k⋅n) which is too slow (since kkk can be up to n!n!n!). Instead, we use math. We know there are (n−1)!(n-1)!(n−1)! permutations that start with '1', (n−1)!(n-1)!(n−1)! that start with '2', etc. By dividing kkk by (n−1)!(n-1)!(n−1)!, we can mathematically determine the first digit in O(1)O(1)O(1) time. We remove that digit from our available pool, update k=k(mod(n−1)!)k = k \pmod{(n-1)!}k=k(mod(n−1)!), and repeat for the next digit. This determines the exact sequence in O(n2)O(n^2)O(n2) time (due to array element removal) or O(nlog⁡n)O(n \log n)O(nlogn) using a specialized tree.

Question: What if the problem asked for the next palindrome instead of the next permutation?

Solution: The core philosophy is similar (mirroring/reversing halves). You mirror the left half of the string onto the right half. If the resulting string is greater than the original, you are done. If it is smaller or equal, you must increment the middle character(s) by 1 (handling carries if it's '9'), and then mirror the left half onto the right half again.

# Logical Follow-up

Question: How would you find the Previous Permutation? Solution: Reverse the logic. Find the first increasing element from the right (nums[i]>nums[i+1]nums[i] > nums[i+1]nums[i]>nums[i+1]), find the largest element smaller than it in the suffix, swap, and then reverse the suffix (which will be in ascending order) to make it descending.

Question: How can you find the k-th permutation of nnn numbers without generating all of them? Solution: Use the Factorial Number System. Since there are (n−1)!(n-1)!(n−1)! permutations starting with a specific digit, you can mathematically determine which digit belongs at each position by dividing kkk by the current factorial.

PreviousMajority ElementNextGet specific element from Pascal's Triangle
CONTENTS
QuestionSolutionPatternHow to IdentifyDescriptionThe IntuitionComplexityCodeCaveatsConcepts to Think AboutLogical Follow-upLogical Follow-up