Balanced binary prefix
Return the length of the longest prefix with equal counts of 0 and 1 in a binary list. The empty prefix is allowed.
balance = 0
for value in [0, 1, 1, 0]:
balance += 1 if value else -1
print(balance)Reason about the state
Count ones as plus one and zeros as minus one. Every return to balance zero marks a valid prefix. Before writing code, identify what each variable means after one iteration. Walk through the example and explain why the next transition preserves that meaning. Then check the smallest permitted input and a case with repeated values. A correct answer follows the contract for every input, including the boundary cases in the checks. Keep any input mutation within the stated rules; return a fresh result when the task asks for one.
Your task
Return the length of the longest prefix with equal counts of 0 and 1 in a binary list. The empty prefix is allowed.
The explanation opens here once every check passes.