如何以O(k)时间复杂度统计二进制字符串中的零的数量
Great question! When dealing with sparse zeros in a binary string (where k << N), an O(k) solution is way more efficient than the naive O(N) linear scan. Let's walk through how this works.
Core Idea
Instead of checking every single character (like the linear approach), we can:
- Skip entire blocks of '1's in one go (no need to check each '1' individually)
- Only count and process blocks of '0's, which directly contributes to our total k count
This way, we only perform operations proportional to the number of zeros (k) plus the number of '1' blocks (which is at most k+1, negligible compared to k when k is small).
Implementation Example (Python)
Here's a clean implementation that follows this logic:
def count_zeros_Ok(binary_str): zero_count = 0 str_length = len(binary_str) current_pos = 0 while current_pos < str_length: # Skip all consecutive '1's without checking each one while current_pos < str_length and binary_str[current_pos] == '1': current_pos += 1 # Exit if we've reached the end of the string if current_pos >= str_length: break # Now count all consecutive '0's starting at current_pos zero_block_start = current_pos while current_pos < str_length and binary_str[current_pos] == '0': current_pos += 1 # Add the length of this zero block to our total count zero_count += current_pos - zero_block_start return zero_count
Why This Is O(k)
- We only iterate through each '0' exactly once (the inner loop for counting zeros runs k times total across all blocks)
- The loops that skip '1's move the pointer in bulk—we never process individual '1's, just jump past entire blocks
- In the worst case (all zeros), k = N, so this becomes O(N) (same as the linear method). In the best case (all ones), k=0, this runs in O(1) time (just a few checks to confirm no zeros exist).
Comparison to Linear O(N) Approach
For reference, here's the standard linear scan method:
def count_zeros_On(binary_str): return binary_str.count('0')
While this is concise, it's inefficient when zeros are sparse. For example, if you have a 1e6-length string with only 10 zeros, the O(k) method will run in ~20 operations, while the O(N) method runs 1e6 operations—huge difference!
内容的提问来源于stack exchange,提问作者Abhijeet Gulve

