Balancing X and Y in Submatrices with Equal Frequency

Day 78: Balancing X and Y (The Grid Grind) ⚖️ Problem 3212: Count Submatrices With Equal Frequency of X and Y Yesterday’s logic was so good I had to run it back. The mission: count all submatrices starting from (0,0) that have at least one 'X' and an equal number of 'X's and 'Y's. The Strategy: • Net Balance Trick: Assigned 'X' as 1 and 'Y' as -1. If the prefix sum of a submatrix is 0, the frequencies are equal. Simple math, big brain energy. 🧠 • 2D Prefix Sums: Used the inclusion-exclusion principle to keep the count updated in a single pass. • The "At Least One X" Check: Maintained a separate prefix matrix just to track if an 'X' had even shown up yet. No 'X', no entry. It might not be the most "optimized" code in the world yet, but it passes the tests and the logic is solid. In a world of complex algorithms, sometimes the O(M⋅N) "it just works" approach is the real MVP. 🚀 #LeetCode #Java #DataStructures #Algorithms #DailyCode

  • text

To view or add a comment, sign in

Explore content categories