DSA interview question
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].
void nextPermutation(vector<int>& nums); // in place; wraps to the smallest permutation after the largest
Input nums | Output | Explanation |
|---|---|---|
[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.)
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 interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in