Posts

Showing posts from July, 2024

Invariants

Image
The concept of invariants is very powerful in computer science. Basically, an invariant is something that has certain immutable properties. For example, in the solution to the problem down below, the string current  has the invariant property that it is always a "valid string", ready to be added to the retVal  collection as soon as the length constraint is met. As we progress throughout the code, we need to assume and enforce the invariant property. Hence, since current  is always valid, we can either append a "1" any time (remains valid), or append a "0" only if current  is empty or ends with a "1", because if it ends with a "0" and we append a "0", we will break the invariant property. Code is down below, cheers, ACC. Generate Binary Strings Without Adjacent Zeros - LeetCode 3211. Generate Binary Strings Without Adjacent Zeros Medium 91 10 Add to List Share You are given a positive integer  n . A binary string  x  is  valid

Prefix Sum VI: DP-like solution

Image
You can think of the solution to this problem in two ways: either a prefix sum, or a Dynamic Programming where you're solving the problem for the {r-1, c}, {r, c-1} and {r-1,c-1} and using those solutions to solve the problem for {r,c}. Code is down below, cheers, ACC. Count Submatrices With Equal Frequency of X and Y - LeetCode 3212. Count Submatrices With Equal Frequency of X and Y Medium 89 18 Add to List Share Given a 2D character matrix  grid , where  grid[i][j]  is either  'X' ,  'Y' , or  '.' , return the number of  submatrices  that contains: grid[0][0] an  equal  frequency of  'X'  and  'Y' . at least  one  'X' .   Example 1: Input:   grid = [["X","Y","."],["Y",".","."]] Output:   3 Explanation: Example 2: Input:   grid = [["X","X"],["X","Y"]] Output:   0 Explanation: No submatrix has an equal frequency of  'X'  and  &#