Leetcode #2647: Color the Triangle Red
In this guide, we solve Leetcode #2647 Color the Triangle Red in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an integer n. Consider an equilateral triangle of side length n, broken up into n2 unit equilateral triangles.
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Array, Math
Intuition
There is a mathematical invariant or formula that directly leads to the result.
Using math avoids unnecessary loops and reduces complexity.
Approach
Derive the formula or update rule, then compute the answer directly.
Handle edge cases like overflow or zero carefully.
Steps:
- Identify the math relationship.
- Compute the result with a loop or formula.
- Handle edge cases.
Example
Input: n = 3
Output: [[1,1],[2,1],[2,3],[3,1],[3,5]]
Explanation: Initially, we choose the shown 5 triangles to be red. Then, we run the algorithm:
- Choose (2,2) that has three red neighbors and color it red.
- Choose (3,2) that has two red neighbors and color it red.
- Choose (3,4) that has three red neighbors and color it red.
- Choose (3,3) that has three red neighbors and color it red.
It can be shown that choosing any 4 triangles and running the algorithm will not make all triangles red.
Python Solution
class Solution:
def colorRed(self, n: int) -> List[List[int]]:
ans = [[1, 1]]
k = 0
for i in range(n, 1, -1):
if k == 0:
for j in range(1, i << 1, 2):
ans.append([i, j])
elif k == 1:
ans.append([i, 2])
elif k == 2:
for j in range(3, i << 1, 2):
ans.append([i, j])
else:
ans.append([i, 1])
k = (k + 1) % 4
return ans
Complexity
The time complexity is , where is the parameter given in the problem. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.