Color the Triangle Red — LeetCode 2647 Python Solution

HardLeetCode PremiumArrayMath
Problem
#2647
Reading time
3 min

The problem

You are given an integer n. Consider an equilateral triangle of side length n, broken up into n2 unit equilateral triangles.

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:

Python solution

Python
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

MeasureComplexity
Time(n^2), where n is the parameter given in the problem
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2647. Color the Triangle Red is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2647. Color the Triangle Red?
LeetCode 2647. Color the Triangle Red is rated Hard on LeetCode.
What is the time complexity of LeetCode 2647. Color the Triangle Red?
The Python solution on this page runs in (n^2), where n is the parameter given in the problem.
What is the space complexity of LeetCode 2647. Color the Triangle Red?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2647. Color the Triangle Red cover?
LeetCode 2647. Color the Triangle Red is tagged Array and Math on LeetCode.
Is LeetCode 2647. Color the Triangle Red a premium problem?
Yes. LeetCode 2647. Color the Triangle Red is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview