Amrita has placed N white drawing sheets (represented as rectangles) on a table in her garden. Some sheets lay on top of others, but none of the sheet borders intersect (meaning they are either completely disjoint or strictly nested).
Her brother fires M paintballs of various colors at the sheets. Due to the force of the gun, once a paintball hits a sheet, the color spreads to all of the sheets beneath it.
Given the coordinates of the sheets and the paintballs, write a program to output N lines, where the ith line contains the number of unique colors spread on the ith sheet.
Input Format:
Example Summary:
If a sheet is placed from (1, 1) to (4, 5) and a paintball of color 1 hits at (3, 2), the sheet receives color 1. If another sheet is placed underneath it, the color spreads to that nested parent sheet as well.
Problem 1 Paint Ball Solution
Topics Involved / Prerequisites
2D Geometry (Coordinate checking)
Hash Sets
Overview
Approach
1. The Geometric Intersection
This is a fantastic logic puzzle that tests your ability to simplify physical rules into code! Since a paintball's force causes the color to bleed through to all sheets beneath the impact point, we don't actually need to build a complex 3D or nested tree structure. Any sheet that contains the (X, Y) coordinate of the paintball within its rectangular bounds is guaranteed to be hit by that paintball.
2. Counting Unique Colors
We can create an array of Hash Sets, one for each of the $N$ sheets. We loop through every paintball, and for each paintball, we loop through every sheet. If the paintball's (X, Y) coordinates are $\ge$ the bottom-left corner and $\le$ the top-right corner of a sheet, we add the paintball's color to that sheet's Hash Set. Because Hash Sets inherently reject duplicate values, the final size of each set will perfectly equal the number of unique colors on that sheet.
Code Implementation (Pseudocode)
Time Complexity
Time: O(N*M) - We compare every single paintball against the boundaries of every single sheet.
Space: O(N* C) - Where C is the maximum number of unique colors a single sheet can receive, stored in the hash sets.