Painting Cats
Suppose you have a row of N cats, numbered from 0 to N - 1. Initially, all the cats are painted black. You are asked to perform Q operations of the following two types, in random order. 1.Painting Cats: Given a range a to b(inclusive), cats within the range are painted with a new color. Example input:
Type of operation | Start index | End index | Color
1 0 10 blue
No output (void)
2.Query Cat: Given a particular number a, return the color of the cat numbered a. Example input:
Type of operation | number
2 10
Example output:
blue
It is guaranteed that 1 ≤ N ≤ 1,000,000,000 and 1≤Q ≤ 300,000. Create a time and space efficient solution.
I could not answer this question without a hint given by my classmate. Not a difficult question to understand, so feel free to think of a solution if you can, before reading on.
Question Analysis
The difficulty lies in the time and space complexity requirements. Let's ignore them for a while and come up with a naive solution.
Naive approach
One possible way to solve the problem is to simply do as told. Initialize an N sized array and assign every slot to be of the color blue. When handling paint-cat operation, simply loop over the array from the starting index to the end index, updating the existing color to the new color. During query-cat operation, simply index to the slot in the array and output the color in that slot.
There are a few issues with the above naive approach. One being that N could be too large to handle. This means our array will take out substantial space to solve this problem. Besides, the time complexity of the paint-cat operation is O(N) because we touch every cat within range per operation. The upside to this solution is that the query-cat operation is O(1) thanks to the array indexing. In summary:
Space:
- O(N) array setup
Time:
- O(N) per paint-cat, worst case O(QN), Q operations of paint-cat
- O(1) per query-cat, worst case O(Q), Q operations of query-cat
Getting better
Looking at the limiting factors, realize that we cannot represent every single cat, or else we will have trouble making it space-efficient. As for the two operations, we need sublinear time complexity for both. There are a few choices, in terms of data structure, that can achieve sublinear complexity: ADTs: