Generate Binary Strings Without Adjacent Zeros - Enumeration [JS]

Description 

Solution: Enumeration

Use enumeration to generate all strings of length n, level by level from length 1 to length n.
For each round,

  • Keep track of the strings with length i - 1.
  • Go through every string with length i - 1 and generate up to two new strings appending either 0 or 1.
  • Note: We can only append 0 if the last character of the string is not 0, since there can't be two consecutive 0s.

Time Complexity: O(n * 2^n)
Space Complexity: O(2^n)

var validStrings = function(n) {
  let prev = ["0", "1"];
  for (let i = 2; i <= n; i++) {
    let curr = [];
    for (let prevStr of prev) {
      if (prevStr[prevStr.length - 1] !== '0') {
        curr.push(prevStr + '0');
      }
      curr.push(prevStr + '1');
    }
    prev = curr;
  }
  return prev;
};

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]