A walkthrough of an O(N log N) algorithm to count binary string substrings with more 1s than 0s. The approach converts the problem by mapping 1→+1 and 0→-1, then uses prefix sums so that a valid substring corresponds to a pair where the later prefix sum exceeds the earlier one. Coordinate compression reduces the prefix sum range, and a Fenwick Tree efficiently counts how many previously seen prefix sums are smaller than the current one in O(log N) per query. A dry run, complexity table, and Java implementation are included.

3m read timeFrom csharp.com
Post cover image
Table of contents
ProblemExampleBrute Force ApproachOptimized IdeaStep 1: Convert CharactersStep 2: Prefix SumStep 3: Substring SumWhy Fenwick Tree?Coordinate CompressionCode ExplanationFenwick TreeUpdateQueryBuild Prefix ArrayCoordinate CompressionMain LogicDry RunComplexity AnalysisJava ImplementationKey InsightSummary
446 Impressions