Problem 31

Abstract / Summary

Find the next lexicographically greater permutation of a given sequence of numbers by rearranging its elements in place..

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0031.cpp

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        next_permutation(nums.begin(), nums.end());
    }
};
6 lines | 138 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 46% (5+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Two Pointers
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single public member function nextPermutation. The function receives a reference to a vector<int> and delegates the entire operation to the C++ Standard Library algorithm std::next_permutation. By leveraging this well-tested routine, the code achieves the required permutation transformation with minimal custom logic.

Key Steps

The core of the algorithm is a single call to std::next_permutation. This call rearranges the elements of the input range into the next lexicographically greater permutation. If such a permutation does not exist because the current arrangement is the highest possible order, the algorithm transforms the range into the lowest (sorted ascending) order.

void nextPermutation(vector<int>& nums) {
    next_permutation(nums.begin(), nums.end());
}

The function signature uses a non-const reference, allowing the algorithm to modify the original container directly. The use of nums.begin() and nums.end() supplies the exact range to be processed.

Edge Cases Handled

When the input vector is empty, the range supplied to std::next_permutation is empty as well. The standard algorithm detects the empty range and performs no modifications, leaving the vector unchanged. A single-element vector also falls under the same logic: there is no alternative ordering, so the algorithm leaves the element as-is.

If the vector is already sorted in descending order, representing the maximal permutation, std::next_permutation reverses the entire range, producing a sorted ascending order. This behavior satisfies the requirement that the next permutation of the highest arrangement wraps around to the lowest.

When duplicate values are present, the algorithm treats equal elements as indistinguishable, ensuring that the next permutation respects the multiset ordering. The resulting arrangement is the smallest lexicographic change that respects the existing duplicates.

Performance Optimizations

By delegating to std::next_permutation, the implementation inherits the algorithmic optimizations of the standard library. The routine operates in-place, requiring no additional dynamic memory allocations beyond the original container. It performs a single linear scan from the end to locate the pivot element, followed by a reverse operation on the suffix, both of which are executed with tight loops and minimal branching. The use of iterators (begin() and end()) enables the compiler to generate efficient pointer arithmetic, further reducing overhead.

Because the function does not introduce any auxiliary data structures or explicit copying, the overall runtime is bounded by the intrinsic cost of the standard algorithm, which is highly tuned for typical hardware caches and branch prediction patterns. This results in a fast, low-memory-footprint solution for generating the next permutation.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a row of wooden blocks, each with a different number painted on it. You are playing a game where you want to arrange these blocks in a specific order to make a new number. Think of the blocks as a secret code that you are trying to unscramble.

The code works like a tiny helpful robot that looks at the blocks you have right now. It knows every possible way those blocks could be lined up. When you ask the robot to perform this task, it looks at the order of your blocks and quickly swaps them around to find the very next pattern in the sequence. It is just like flipping to the next page in a book of patterns to see what comes right after the one you are looking at. The blocks will move into different spots so that they spell out a brand new, slightly larger number than the one you started with.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 28 | median = 8 | μ = 6.82 | σ = 2.95

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python C# JS Java Go PHP TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu C++
DimitrisJim C
everthis JS
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
XiaotaoGuo C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, JavaScript, PHP, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
AdelDaniel Dart
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu C++
DimitrisJim C
everthis JavaScript
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
XiaotaoGuo C++
zfang399 C++
56 links | 39 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Next Permutation πŸ”₯πŸ”₯| Array | Love Babbar DSA Sheet | Leetcode 31 | Amazon | Google'
Ayushi Sharma 15 mins
Next Permutation πŸ”₯πŸ”₯| Array | Love Babbar DSA Sheet | Leetcode 31 | Amazon | Google
YouTube video 'Next Permutation | Leet code 31 | Theory explained + Python code'
Sai Anish Malla 20 mins
Next Permutation | Leet code 31 | Theory explained + Python code
YouTube video 'Next Permutation Python Solution - LeetCode #31'
Professor Oakes 5 mins
Next Permutation Python Solution - LeetCode #31
YouTube video '[Java] Leetcode 31. Next Permutation [Array #11]'
Eric Programming 12 mins
[Java] Leetcode 31. Next Permutation [Array #11]
YouTube video 'LeetCode 31. Next Permutation Explanation and Solution'
happygirlzt 8 mins
LeetCode 31. Next Permutation Explanation and Solution
YouTube video 'LeetCode 31. Next Permutation δΈ­ζ–‡θ§£ι‡Š Chinese Version'
happygirlzt 6 mins
LeetCode 31. Next Permutation δΈ­ζ–‡θ§£ι‡Š Chinese Version
YouTube video 'Next Permutation | Leetcode 31'
Coding Decoded 16 mins
Next Permutation | Leetcode 31
YouTube video 'LeetCode: 31. Next Permutation (Visualized)'
Code With Zi 14 mins
LeetCode: 31. Next Permutation (Visualized)
YouTube video 'Leetcode 31 - Next Permutation (JAVA Solution Explained!)'
LC Bear 11 mins
Leetcode 31 - Next Permutation (JAVA Solution Explained!)
YouTube video 'Microsoft Coding Interview Question | Leetcode 31 | Next Permutation'
WorkWithGoogler 21 mins
Microsoft Coding Interview Question | Leetcode 31 | Next Permutation
YouTube video 'Daily Leetcode #733: Apr 03, 2022 - 31. Next Permutation'
Programming Live with Larry 19 mins
Daily Leetcode #733: Apr 03, 2022 - 31. Next Permutation
YouTube video 'Leetcode 31 πŸ”₯ Next Permutation | Optimal Approach + Dry Run | Java Solution'
Study Placement 15 mins
Leetcode 31 πŸ”₯ Next Permutation | Optimal Approach + Dry Run | Java Solution
YouTube video 'Next Permutation | LeetCode 31 | Coders Camp'
Coders Camp 14 mins
Next Permutation | LeetCode 31 | Coders Camp
YouTube video 'LeetCode 31. Next Permutation'
Happy Coding 15 mins
LeetCode 31. Next Permutation
YouTube video 'Daily Leetcode #306: Jan 31, 2021 - 31. Next Permutation'
Programming Live with Larry 22 mins
Daily Leetcode #306: Jan 31, 2021 - 31. Next Permutation
YouTube video '31. Next Permutation (Leetcode Medium)'
Programming Live with Larry 35 mins
31. Next Permutation (Leetcode Medium)
YouTube video 'DAY 297: LeetCode Problem 31. Next Permutation - Swift'
iOSxBank 16 mins
DAY 297: LeetCode Problem 31. Next Permutation - Swift
YouTube video 'Leetcode Question 31 "Next Permutation" in Javascript'
Ghumman Tech 6 mins
Leetcode Question 31 "Next Permutation" in Javascript
YouTube video '31. Next Permutation || Leetcode Medium || Cpp'
Komal Pal 23 mins
31. Next Permutation || Leetcode Medium || Cpp
YouTube video 'No Sound Leetcode 31: Next permutation'
ExtremeProgrammer 4 mins
No Sound Leetcode 31: Next permutation
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality