Apply Range Paint Operations and Count Final Colors
Arrays & HashingAuto-graded · 17 test casesLast updated
Tests ability to use difference arrays to efficiently apply multiple range-update operations and decode the final state.
Apply Range Paint Operations and Count Final Colors
You are given a strip of n cells, each initially unpainted (color 0).
You receive a list of paint operations. Each operation is represented as a list [l, r, c] meaning: paint every cell from index l to index r inclusive with color c (a positive integer).
Operations are applied in order. A later operation overwrites any earlier color on cells it covers.
After all operations have been applied, return a dictionary mapping each color (positive integer) that appears at least once in the final strip to the number of cells that have that color.
Cells that remain unpainted (color 0) are not included in the result.
How to handle overlapping operations
Each cell's final color is determined by the last operation that covers it.
Constraints
1 ≤ n ≤ 20000 ≤ len(operations) ≤ 2000- For each operation
[l, r, c]:0 ≤ l ≤ r ≤ n - 1,1 ≤ c ≤ 1000 - Returns an empty dict
{}if no cells are painted (either no operations or all cells remain at color0). - Dict keys and values are plain Python
int.
Examples
Example 1
Input: count_painted_colors(7, [[0, 3, 1], [2, 5, 2], [4, 6, 3]])
Output: {'1': 2, '2': 2, '3': 3}
Example 2
Input: count_painted_colors(5, [])
Output: {}
Example 3
Input: count_painted_colors(6, [[0, 5, 7], [1, 4, 3], [2, 3, 5]])
Output: {'3': 2, '5': 2, '7': 2}
Hints
Hint 1
Think about applying each operation naively — with n and ops both up to 2000, an O(n × ops) approach is acceptable, but can you do better using a difference-array or similar technique?
Hint 2
For each cell, you only care about the *last* operation that covers it. Consider processing operations in reverse order and tracking which cells have already been assigned a final color.
Hint 3
After determining the final color of every cell (a plain array of length n), a single pass with a hash map is all you need to tally the counts per color.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key insight
Because later operations overwrite earlier ones, each cell's final color is determined by the last operation that covers it. Rather than applying operations left-to-right and overwriting cells repeatedly, we can iterate through operations in reverse order and mark cells as "settled" the first time we assign them a color — that first assignment in reverse order is exactly the last assignment in forward order.
Algorithm
- Maintain a
final[0..n-1]array (all zeros = unpainted) and asettled[0..n-1]boolean array. - Walk through
operationsfrom last to first. For operation[l, r, c], iterate over every indexiin[l, r]; ifsettled[i]isFalse, setfinal[i] = cand mark it settled. - Keep a counter
remainingof unsettled cells; short-circuit once it reaches 0. - Do one final pass over
finalto tally counts per color (skip color 0).
Why it is correct
A cell's color is determined by the last operation covering it. Processing in reverse and skipping already-settled cells ensures each cell gets exactly that last color with no unnecessary work.
Complexity
- Time: O(n + ops × segment_length) in the worst case (no overlaps), which is O(n × ops) at most but O(n + ops) with heavy overlap because each cell is written at most once.
- Space: O(n) for the
finalandsettledarrays.
For the given constraints (n, ops ≤ 2 000) even a straightforward O(n × ops) loop is well within limits.
Difference-array connection
The classic difference array technique allows O(1) range updates and O(n) reconstruction for additive updates. Here, updates are last-write-wins, so a difference array for addition does not apply directly. The reverse-iteration trick is the natural analogue: it achieves O(n + ops) effective work by exploiting the same "one pass to decode" idea — we decode the final state in a single reverse sweep instead of a prefix-sum sweep.
from typing import List
def count_painted_colors(n: int, operations: list) -> dict:
final = [0] * n
settled = [False] * n
remaining = n
for l, r, c in reversed(operations):
if remaining == 0:
break
for i in range(l, r + 1):
if not settled[i]:
final[i] = c
settled[i] = True
remaining -= 1
counts: dict = {}
for color in final:
if color != 0:
counts[color] = counts.get(color, 0) + 1
return counts