PPractick

DSA interview question

Next Permutation

Medium · Algorithms · Topics: array, two pointer

The problem

A lock-cracking training game shows the digits of a combination and asks for the next combination in dictionary order using the same digits. If the digits are already in their largest arrangement (like 3 2 1), it wraps around to the smallest (1 2 3). Generating all permutations and sorting them is hopeless for even ten digits. The classic in-place algorithm finds the answer in O(n) by looking from the right for the first place where the digits stop increasing.

Example: [1, 2, 3] → [1, 3, 2]; [3, 2, 1] → [1, 2, 3].

Function signature

void nextPermutation(vector<int>& nums);  // in place; wraps to the smallest permutation after the largest

Test cases

Input numsOutputExplanation
[1, 2, 3][1, 3, 2]
[3, 2, 1][1, 2, 3]Last permutation wraps to the first
[1, 1, 5][1, 5, 1]Duplicates
[1, 3, 2][2, 1, 3]
[2, 3, 1][3, 1, 2]
[1][1]

(Confirm: in place with O(1) extra space; the behaviour matches std::next_permutation, which the code cross-checks on random arrays.)

How interviewers phrase it

Clarifying questions to ask

  1. What should happen after the last permutation: wrap to the first?
  2. In place, with O(1) extra space?
  3. Can there be duplicate values?

Follow-ups to expect

  1. "Why look for the first decrease from the right?"
  2. "Why swap with the smallest larger element in the suffix?"
  3. "Why reverse the suffix afterwards?"
  4. "How does it handle duplicates?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in