Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created February 23, 2026 17:46
Show Gist options
  • Select an option

  • Save tatsuyax25/183d4eef0a943adf038528fb3210e92e to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/183d4eef0a943adf038528fb3210e92e to your computer and use it in GitHub Desktop.
Given a binary string s and an integer k, return true if every binary code of length k is a substring of s. Otherwise, return false.
/**
* @param {string} s
* @param {number} k
* @return {boolean}
*/
var hasAllCodes = function(s, k) {
// Total number of binary codes of length k
const needed = 1 << k; // same as Math.pow(2, k)
// Quick fail: if s is too short to contain all codes
// There are (s.length - k + 1) substrings of length k
if (s.length < k || (s.length - k + 1) < needed) {
return false;
}
// A set to store all unique substrings of length k
const seen = new Set();
// Slide a window of size k across the string
for (let i = 0; i <= s.length - k; i++) {
const sub = s.substring(i, i + k);
seen.add(sub);
// Optimization: if we've already found all possible codes, stop early
if (seen.size === needed) {
return true;
}
}
// After scanning, check if we collected all codes
return seen.size === needed;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment