DSA interview question
A teammate wrote a helper swapValues(a, b) to swap two scores in a sorting routine, but after calling it, nothing changes, and the sort never finishes correctly. Separately, a function that "adds a bonus point to every score" works on its own but the caller's list never updates. Both bugs have the same root cause: the functions received copies of the data. Your task: write the swap three ways (by value, by reference, and by pointer), show which ones actually change the caller's variables, and write a helper that returns two results (minimum and maximum) through reference parameters without copying the input.
Example: with a = 3, b = 7, swapByValue(a, b) leaves them as 3, 7, while swapByReference(a, b) makes them 7, 3.
void swapByValue(int a, int b); // receives copies
void swapByReference(int& a, int& b); // receives aliases
void swapByPointer(int* a, int* b); // receives addresses
void minMax(const vector<int>& nums, int& lo, int& hi); // read-only input, two outputs
| Input | Output | Explanation |
|---|---|---|
a = 3, b = 7, call swapByValue(a, b) | a = 3, b = 7 | Only the local copies were swapped |
a = 3, b = 7, call swapByReference(a, b) | a = 7, b = 3 | References refer to the caller's variables |
a = 3, b = 7, call swapByPointer(&a, &b) | a = 7, b = 3 | Writes through the addresses |
minMax({4, -2, 9}, lo, hi) | lo = -2, hi = 9 | Two results returned through references |
minMax({5}, lo, hi) | lo = 5, hi = 5 | Single element |
v = {1, 2}, addBonusByValue(v) then addBonusByReference(v) | v = {2, 3} | Only the by-reference call changes the caller's vector |
(Confirm: nums is non-empty; the caller's variables are inspected after each call.)
swapByValue not work?"vector as const vector<int>&?"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