oneby7

Recursion and Backtracking Pick or skip

315. Binary Strings Without Consecutive 1s

Medium

Given an integer n, return every binary string of length n that has no two 1s next to each other. A binary string is made only of the characters 0 and 1.

So 1010 is allowed, and so is 1001. 0110 is not, because its second and third characters are both 1. The first and last characters are not next to each other, so for n = 3 the string 101 is allowed.

Return the strings in increasing order, the order a dictionary uses, with 0 before 1. All the strings have the same length, so this is also the order of the numbers they write in binary. There is exactly one right answer.

Example 1

Input: n = 4

Output: ["0000", "0001", "0010", "0100", "0101", "1000", "1001", "1010"]

Explanation: Of the 16 binary strings of length 4, these 8 have no 11 in them. 1001 has two 1s, but they are not next to each other. 0101 comes before 1000 because its first character is smaller.

Example 2

Input: n = 1

Output: ["0","1"]

Explanation: A single 1 has no neighbour, so both strings of length 1 count.

Example 3

Input: n = 6

Output: ["000000", "000001", "000010", "000100", "000101", "001000", "001001", "001010", "010000", "010001", "010010", "010100", "010101", "100000", "100001", "100010", "100100", "100101", "101000", "101001", "101010"]

Explanation: 21 of the 64 binary strings of length 6 have no two 1s side by side.

Check your understanding

Work out the answer for this input before you write any code.

n = 2

Constraints

  • 1 ≤ n ≤ 25

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.