Bird
Raised Fist0
Interview PrepbacktrackingmediumAmazonGoogleFacebook

Next Permutation

Choose your preparation mode4 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
</>
IDE
def next_permutation(nums: list[int]) -> None:public void nextPermutation(int[] nums)void nextPermutation(vector<int>& nums)function nextPermutation(nums)
def next_permutation(nums):
    # Write your solution here
    pass
class Solution {
    public void nextPermutation(int[] nums) {
        // Write your solution here
    }
}
#include <vector>
using namespace std;

void nextPermutation(vector<int>& nums) {
    // Write your solution here
}
function nextPermutation(nums) {
    // Write your solution here
}
0/10
Common Bugs to Avoid
Wrong: [1,2,3]No change made when next permutation exists; missed pivot detection.Scan from right to left to find first decreasing element as pivot; swap and reverse suffix.
Wrong: [3,2,1]Always reversing entire array regardless of pivot; ignoring pivot swap step.Only reverse suffix after swapping pivot with next larger element.
Wrong: [1,3,2,3]Swapping pivot with wrong element or not reversing suffix after swap.Swap pivot with next larger element strictly greater than pivot; then reverse suffix.
Wrong: [5,4,3,2,1]Failing to reverse entire array when no pivot found (highest permutation).If no pivot found, reverse entire array to get lowest permutation.
Wrong: TLE or timeoutUsing brute force generating all permutations for large n.Implement O(n) pivot-swap-reverse algorithm instead of brute force.
Test Cases
t1_01basic
Input{"nums":[2,1,3]}
Expectednull

The next permutation after [1,2,3] is [1,3,2].

t1_02basic
Input{"nums":[2,1,3,3]}
Expectednull

Next permutation after [1,3,2,3] is [1,3,3,2], swapping pivot 2 with 3 and reversing suffix.

t2_01edge
Input{"nums":[1]}
Expectednull

Single element array has only one permutation; next permutation is itself.

t2_02edge
Input{"nums":[2,2,2]}
Expectednull

All elements equal means no lexicographically larger permutation; output is same array.

t2_03edge
Input{"nums":[1,2,3,5,4]}
Expectednull

Strictly descending order is highest permutation; next is lowest ascending order.

t2_04edge
Input{"nums":[]}
Expectednull

Empty array input should return empty array as no permutations exist.

t3_01corner
Input{"nums":[1,1,5]}
Expectednull

Greedy trap: swapping wrong element leads to incorrect next permutation; correct pivot is index 0, swap with 5, reverse suffix.

t3_02corner
Input{"nums":[1,2,4,1,3,2,3]}
Expectednull

Handles suffix with duplicates correctly; pivot at index 2 (3), swap with 4, reverse suffix.

t3_03corner
Input{"nums":[3,2,1]}
Expectednull

Off-by-one error test: pivot at index 0, swap with 3, reverse suffix [1] to get [3,1,2].

t4_01performance
Input{"nums":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]}
⏱ Performance - must finish in 2000ms

n=100, O(n) time complexity expected; brute force O(n!) will TLE.

Practice

(1/5)
1. You need to generate all unique permutations of an array that may contain duplicate elements. Which approach guarantees generating all unique permutations efficiently without producing duplicates during generation?
easy
A. Use a greedy algorithm that picks the smallest unused element at each step.
B. Use backtracking with sorting and a mechanism to skip duplicates during recursion.
C. Use dynamic programming to build permutations from smaller subproblems.
D. Generate all permutations and then filter duplicates using a hash set.

Solution

  1. Step 1: Understand the problem constraints

    The problem requires generating all unique permutations of an array with duplicates, so duplicates must be avoided during generation to be efficient.
  2. Step 2: Evaluate approaches

    Greedy algorithms do not guarantee all permutations; DP is not suitable here; generating all permutations and filtering duplicates is correct but inefficient. Backtracking with sorting and skipping duplicates during recursion ensures duplicates are pruned early.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Backtracking with duplicate skipping is the standard optimal approach [OK]
Hint: Skip duplicates during backtracking after sorting [OK]
Common Mistakes:
  • Thinking greedy or DP can generate unique permutations efficiently
2. Consider the following code snippet implementing the optimal backtracking solution for Word Search. Given the board = [["A","B","C"],["D","E","F"],["G","H","I"]] and word = "BEF", what is the return value of exist(board, word)?
easy
A. True
B. False
C. Raises IndexError
D. Infinite recursion

Solution

  1. Step 1: Trace dfs starting at cell (0,1) 'B'

    Word starts with 'B', found at (0,1). dfs(0,1,0) matches 'B'.
  2. Step 2: Explore neighbors for next chars 'E' and 'F'

    From (0,1), neighbors checked: (1,1) 'E' matches next char, then (1,2) 'F' matches last char. All matched, return True.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    All characters found sequentially with valid moves [OK]
Hint: Trace dfs calls carefully to confirm path exists [OK]
Common Mistakes:
  • Assuming no path due to adjacency confusion
  • Missing in-place marking effect
3. Consider the following buggy code for generating letter combinations. Which line contains the subtle bug that causes incorrect or incomplete results?
from collections import deque

def letterCombinations(digits):
    if digits == '':
        return ['']
    digit_map = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
                 '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
    queue = deque([''])
    for digit in digits:
        letters = digit_map[digit]
        for _ in range(len(queue)):
            prev = queue.popleft()
            for char in letters:
                queue.append(prev + char)
    return list(queue)
medium
A. Line 7: letters = digit_map[digit]
B. Line 2: if digits == '': return ['']
C. Line 10: prev = queue.popleft()
D. Line 1: from collections import deque

Solution

  1. Step 1: Analyze empty input handling

    Returning [''] for empty input is incorrect; the problem expects an empty list [] when input is empty.
  2. Step 2: Check other lines

    Digit mapping, queue operations, and imports are correct and do not cause bugs.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Empty input should return [] not [''] to match problem spec [OK]
Hint: Empty input must return empty list, not list with empty string [OK]
Common Mistakes:
  • Returning [''] instead of [] for empty input
  • Assuming digits '1' or '0' map to letters
4. Examine the following code snippet for the Word Search II problem. Which line contains a subtle bug that can cause incorrect results or infinite loops?
medium
A. Line: currNode = node.children.get(letter)
B. Line: Missing marking of board[r][c] as visited before recursion
C. Line: if currNode.word:
D. Line: board[r][c] = letter at the end

Solution

  1. Step 1: Identify visited marking necessity

    Backtracking requires marking the current cell as visited (e.g., replacing letter with '#') to avoid revisiting the same cell in the current path.
  2. Step 2: Locate missing visited marking

    The code lacks the line that marks board[r][c] as visited before recursive calls, causing revisits and potential infinite loops.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Without visited marking, recursion revisits same cells [OK]
Hint: Visited marking prevents revisiting same cell in recursion [OK]
Common Mistakes:
  • Forgetting to mark visited cells or unmark after recursion.
5. Suppose the N-Queens problem is modified so that queens can be placed multiple times in the same column (i.e., column constraint is relaxed), but diagonal attacks still apply. Which modification to the bitmask backtracking algorithm correctly adapts to this variant?
hard
A. Remove the column bitmask tracking and only track diagonal attacks in recursion
B. Keep column bitmask but allow multiple queens by resetting it each row
C. Use a greedy approach placing queens in any column without pruning
D. Track columns as before but ignore diagonal bitmasks

Solution

  1. Step 1: Understand relaxed constraints

    Since columns can have multiple queens, column bitmask is no longer needed to prune placements.
  2. Step 2: Adapt pruning to only diagonal attacks

    Keep diag1 and diag2 bitmasks to prune diagonal conflicts, but remove column mask from available_positions calculation.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Removing column mask allows multiple queens per column while still pruning diagonals [OK]
Hint: Relaxed constraints remove column pruning, keep diagonal pruning [OK]
Common Mistakes:
  • Resetting column mask each row incorrectly
  • Ignoring diagonal pruning
  • Using greedy without pruning