Let's make this one less mysterious. For 1411. Number of Ways to Paint N × 3 Grid, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
The notes already sitting in the source point us in the right direction:
- https://www.geeksforgeeks.org/ways-color-3n-board-using-4-colors/
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are solve, numOfWays.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//https://www.geeksforgeeks.org/ways-color-3n-board-using-4-colors/
02//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Number of Ways to Paint N × 3 Grid.
03//Memory Usage: 5.9 MB, less than 100.00% of C++ online submissions for Number of Ways to Paint N × 3 Grid.
04class Solution {
05public:
06 int solve(int A) {
07 // When we to fill single column
08 long int color3 = 6; //P 3 takes 3
09 long int color2 = 6; //(C 3 takes 2) * (2 possible position)
10 long int temp = 0;
11
12 for (int i = 2; i <= A; i++)
13 {
14 temp = color3; //previous color3
15 /*
16 when current row is of three color
17 next row could have 2 possible two color comb and
18 2 possible three color comb
19
20 when current row is of two color
21 next row could have 3 possible two color comb and
22 2 possible three color comb
23 */
24 color3 = (2 * color3 + 2 *
25 color2 ) % 1000000007;
26
27 color2 = ( 2 * temp + 3 *
28 color2 ) % 1000000007;
29 }
30
31 long num = (color3 + color2)
32 % 1000000007;
33
34 return (int)num;
35 }
36
37
38 int numOfWays(int n) {
39 return solve(n);
40 }
41};
Cost