DSA interview question
A warehouse robot reorganises boxes on a shelf by weight, lightest first. Picking up and moving a box is slow and expensive, while reading a box's label is cheap. Selection sort fits this constraint: on each pass it scans the unsorted part to find the smallest item, then makes a single swap to put it in place. It always needs about n²/2 comparisons, but never more than n − 1 swaps, the fewest moves of any simple sorting algorithm. It's also the easiest algorithm to reason about, which is why it's usually the first one taught.
Example: [4, 1, 3, 9, 7] → [1, 3, 4, 7, 9].
void selectionSort(vector<int>& a); // sorts a in non-decreasing order, in place
Input a | Output | Explanation |
|---|---|---|
[4, 1, 3, 9, 7] | [1, 3, 4, 7, 9] | |
[5, 2, 9, 1, 5, 6] | [1, 2, 5, 5, 6, 9] | Duplicates are fine |
[3, -1, 0, -7] | [-7, -1, 0, 3] | Negative values |
[1, 2, 3] | [1, 2, 3] | Already sorted: still O(n²) comparisons, but no swaps |
[4, 3, 2, 1] | [1, 2, 3, 4] | Reverse order |
[42] | [42] | |
[] | [] |
(Confirm: sort in place in non-decreasing order; the code also cross-checks 1,000 random arrays against std::sort.)
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