15% off all plans & roadmaps Use code
See plansLeetCode 31 · Solution & editorial
A permutation of an array of integers is an arrangement of its members into a sequence or linear order.
Next Permutation is a Backtracking Patterns problem, in the Permutations subpattern. The pattern covers subsets, permutations, combinations, N-Queens, and word search
Generate all permutations using backtracking. Handle duplicates and next permutation.
The reference solution runs in O(n) time and O(1) space.
Next Permutation has been reported in interviews at Facebook, Amazon, Google, Microsoft, Rubrik, Bloomberg, Apple, Morgan Stanley.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Next Permutation is a Backtracking Patterns problem, in the Permutations subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.