DSA interview question
A math-puzzle app shows a string of digits like "123" and a target like 6. The player must insert +, - or * between digits, or nothing, which joins digits into longer numbers, to make an expression equal to the target. The app needs all solutions. Operands can't have leading zeros ("05" is not allowed, but "0" is), and * binds tighter than + and -. The backtracking trick for precedence is to track both the running value and the last operand: to apply *, undo the last operand and add last × current instead.
Example: "123", target 6 → "1*2*3", "1+2+3".
vector<string> addOperators(const string& num, int target); // shown sorted here; any order is fine
Input (num, target) | Output (sorted) | Explanation |
|---|---|---|
("123", 6) | 1*2*3 1+2+3 | |
("232", 8) | 2*3+2 2+3*2 | * binds tighter |
("105", 5) | 1*0+5 10-5 | "05" isn't a valid operand |
("00", 0) | 0*0 0+0 0-0 | |
("3456237490", 9191) | (none) |
(Confirm: operators are +, - and * only, placed between digits; no unary minus; operands have no leading zeros; values can exceed 32 bits, so use 64-bit arithmetic.)
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