DSA interview question
A lighting controller drives a row of n lamps. To avoid overheating, no two adjacent lamps may be on at the same time. The test team wants every allowed on/off pattern listed, written as binary strings of length n, in increasing (lexicographic) order, so they can run through them one by one. Generating all 2ⁿ strings and filtering wastes most of the work. Backtracking builds only valid strings: a 0 can always be appended, and a 1 only when the previous character isn't 1.
Example: n = 3 → 000 001 010 100 101.
vector<string> generateBinaryStrings(int n); // in lexicographic order
Input n | Output | Explanation |
|---|---|---|
3 | 000 001 010 100 101 | 011, 110 and 111 have adjacent 1s |
2 | 00 01 10 | |
1 | 0 1 | |
4 | 0000 0001 0010 0100 0101 1000 1001 1010 | 8 strings |
5 | 13 strings | The counts follow Fibonacci numbers |
(Confirm: 1 ≤ n ≤ about 20; the output must be in lexicographic order.)
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