Generate Binary Strings Without Consecutive 1s
The problem
Given an integer n, return all binary strings of length n that do not contain consecutive 1s. Return the result in lexicographically increasing order.
A binary string is a string consisting only of characters** '0'** and** '1**'.
Input: n = 3 Output: ["000", "001", "010", "100", "101"] **Explanation: **All strings are of length 3 and do not contain consecutive 1s.
Input: n = 2 **Output: **["00", "01", "10"]
Input: n = 1
- 1 <= n <= 20
cpp
class Solution {
public:
vector<string> generateBinaryStrings(int n) {
// Your code goes here
}
};java
class Solution {
public List<String> generateBinaryStrings(int n) {
// Your code goes here
}
}python
class Solution:
def generateBinaryStrings(self, n):
# Your code goes herejavascript
class Solution {
generateBinaryStrings(n) {
// Your code goes here
}
}csharp
public class Solution
{
public List<string> GenerateBinaryStrings(int n)
{
// Your code goes here
}
}go
func generateBinaryStrings(n int) []string {Stuck? Show a way to structure it+
- 01Define output order and n=0 behavior
- 02Recurse with index and previous-bit state
- 03Always branch to 0, conditionally branch to 1
- 04Emit when the built string reaches length n
Reference answer
Then expect these follow-ups
How many such strings exist?
Tests: follow-up reasoning
How would you count rather than generate them?
Tests: follow-up reasoning
Hiring now
Google has 52 open roles right now
landed applies to roles like these for you, on each company’s own site, with answers written for the role.
Small Business Field Sales Representative
Denver, Colorado
Senior Technical Program Manager, Special Projects
Denver, Colorado; Lakewood, Colorado, United States
OSP Engineering Lead, Technical Operations
Denver, Colorado
Next question