Repository navigation
Binary Substrings
codepath-wiki-review[bot] edited this page Nov 20, 2026
·
5 revisions
TIP101 Unit 3 Session 2 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
- What is the input?
- A binary string
smade of0s and1s.
- A binary string
- What counts as a balanced substring?
- A substring made of some number of one character followed immediately by the same number of the other character, such as
"01","10"or"0011".
- A substring made of some number of one character followed immediately by the same number of the other character, such as
- Do repeated substrings count more than once?
- Yes. Each position where a balanced substring occurs is counted separately.
- What if the string has fewer than two characters, or only one kind of character?
- Return
0, because no balanced substring is possible.
- Return
HAPPY CASE
Input: s = "00110011"
Output: 6
Explanation: The runs are 00, 11, 00, 11. Each of the three adjacent pairs of runs contributes min(2, 2) = 2 substrings: "0011", "01", "1100", "10", "0011" and "01".
HAPPY CASE 2
Input: s = "10101"
Output: 4
Explanation: Every run has length 1, so each of the four adjacent pairs of runs contributes 1 substring: "10", "01", "10" and "01".
EDGE CASE
Input: s = "0000"
Output: 0
Explanation: There is only one run, so there is no adjacent run to balance it.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Look for runs of consecutive identical characters; each pair of adjacent runs contributes as many balanced substrings as the length of the shorter run, i.e. min(previous run length, current run length).
1) Previous run length starts at 0
2) Current run length starts at 1
3) Count starts at 0
4) For each character except the first:
a) Does current char match the prev char?
i) If so, current run length goes up by 1
ii) If not, current run is over:
- Set prev run to curr run
- Set curr run to 1
b) Does prev run >= curr run?
i) If so, add 1 to count
5) Return count- Since you need to compare each character to the one before, be careful with your loop. If you start at 0, your code might try to access index "-1" and run into an error.
def binary_substrings_count(s):
prev_run_length = 0
curr_run_length = 1
count = 0
for i in range(1, len(s)):
if s[i] == s[i-1]:
curr_run_length += 1
else:
prev_run_length = curr_run_length
curr_run_length = 1
if prev_run_length >= curr_run_length:
count += 1
return count