Skip to content

Commit d817bfa

Browse files
committed
Optimize solution for "Check If a String Contains All Binary Codes of Size K" problem by early exit when all substrings are found
1 parent 5e706e0 commit d817bfa

1 file changed

Lines changed: 5 additions & 3 deletions

File tree

src/main/java/com/github/dkoval/leetcode/challenge/CheckIfStringContainsAllBinaryCodesOfSizeK.java

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,10 +86,12 @@ public boolean hasAllCodes(String s, int k) {
8686
final var substrs = new HashSet<>();
8787
for (var start = 0; start <= n - k; start++) {
8888
substrs.add(s.substring(start, start + k));
89+
// the total number of such substrings must be 2^k
90+
if (substrs.size() == (1 << k)) {
91+
return true;
92+
}
8993
}
90-
91-
// the total number of such substrings should be 2^k
92-
return substrs.size() == (1 << k);
94+
return false;
9395
}
9496
}
9597

0 commit comments

Comments
 (0)