DSA interview question
A stadium sells N tickets numbered 1 to N. At the end of the day the scanner log has N entries, but one ticket number was scanned twice (someone shared a ticket) and consequently one number never appears. Security wants both numbers. Counting with a hash map or a boolean array is O(n) space. The O(1)-space answer uses maths: the log's sum and sum of squares differ from those of 1..N by amounts that depend only on the repeating number x and the missing number y, which gives two equations in two unknowns.
Example: [3, 1, 3] → repeating 3, missing 2.
pair<int, int> findRepeatingAndMissing(const vector<int>& a); // {repeating, missing}; a has N values from 1..N
Input a | Output | Explanation |
|---|---|---|
[3, 1, 3] | {3, 2} | |
[4, 3, 6, 2, 1, 1] | {1, 5} | |
[1, 1] | {1, 2} | |
[2, 2] | {2, 1} | |
[1, 2, 2, 4] | {2, 3} |
(Confirm: exactly one value in 1..N appears twice and exactly one is missing; O(1) extra space is the goal.)
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