#2647
Hard Algorithms Color the triangle red
Array Math
59.3% acceptance
Mar 31, 2026
11
19
You are given an integer n. Consider an equilateral triangle of side length n, broken up into n2 unit equilateral triangles. The triangle has n 1-indexed rows where the ith row has 2i - 1 unit equilateral triangles.
The triangles in the ith row are also 1-indexed with coordinates from (i, 1) to (i, 2i - 1). The following image shows a triangle of side length 4 with the indexing of its triangle.
Two triangles are neighbors if they share a side. For example:
Triangles (1,1) and (2,2) are neighbors
Triangles (3,2) and (3,3) are neighbors.
Triangles (2,2) and (3,3) are not neighbors because they do not share any side.
Initially, all the unit triangles are white. You want to choose k triangles and color them red. We will then run the following algorithm:
Choose a white triangle that has at least two red neighbors.
If there is no such triangle, stop the algorithm.
Color that triangle red.
Go to step 1.
Choose the minimum k possible and set k triangles red before running this algorithm such that after the algorithm stops, all unit triangles are colored red.
Return a 2D list of the coordinates of the triangles that you will color red initially. The answer has to be of the smallest size possible. If there are multiple valid solutions, return any.
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn color_red(n: i32) -> Vec<Vec<i32>> {
let n = n as usize;
if n == 1 {
return vec![vec![1, 1]];
}
let target_len = (n * (n + 3) + 3) / 4;
let (base_n, mut result) = match n {
2 => (2, vec![vec![1, 1], vec![2, 1], vec![2, 3]]),
3 => (3, vec![vec![1, 1], vec![2, 1], vec![2, 3], vec![3, 1], vec![3, 5]]),
4 => (
4,
vec![
vec![1, 1],
vec![2, 1],
vec![3, 1],
vec![3, 4],
vec![4, 1],
vec![4, 5],
vec![4, 7],
],
),
_ if n % 4 == 1 => (
5,
vec![
vec![1, 1],
vec![2, 1],
vec![3, 1],
vec![3, 4],
vec![4, 1],
vec![4, 5],
vec![4, 7],
vec![5, 1],
vec![5, 5],
vec![5, 9],
],
),
_ if n % 4 == 2 => (2, vec![vec![1, 1], vec![2, 1], vec![2, 3]]),
_ if n % 4 == 3 => (3, vec![vec![1, 1], vec![2, 1], vec![2, 3], vec![3, 1], vec![3, 5]]),
_ => (
4,
vec![
vec![1, 1],
vec![2, 1],
vec![3, 1],
vec![3, 4],
vec![4, 1],
vec![4, 5],
vec![4, 7],
],
),
};
result.reserve(target_len - result.len());
let mut size = base_n + 4;
while size <= n {
result.push(vec![(size - 3) as i32, 1]);
for col in (3..2 * (size - 2)).step_by(2) {
result.push(vec![(size - 2) as i32, col as i32]);
}
result.push(vec![(size - 1) as i32, 2]);
for col in (1..2 * size).step_by(2) {
result.push(vec![size as i32, col as i32]);
}
size += 4;
}
result
}
}