KatInterview

Apply Range Paint Operations and Count Final Colors

Arrays & HashingAuto-graded · 17 test cases
EasyAuto-gradedArrays & Hashingarraysdifference arrayprefix sums

Last 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 ≤ 2000
  • 0 ≤ 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 color 0).
  • 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.