I am seeking a data structure that maintains an array of N numbers and supports the following two operations:
- Double the first i numbers
- Subtract the first i numbers of a previous version from the current version.
It always starts with an array filled with 1s, and we only need to know the final array (after all operations have been applied). The algorithm doesn't have to be online. Assume overflow won't happen.
Is it possible to solve this in close to linear running time (e.g., Q log N or Q sqrt N where Q is the number of operations)? I invented this problem for a programming contest and I'm wondering how efficiently this can be done.
Here is an example:
We start with the array
[1,1,1,1] (version 1)
Double the first 3 numbers to get
[2,2,2,1] (version 2)
Double the first 1 numbers to get
[4,2,2,1] (version 3)
Subtract the first 3 numbers of version 1 to get
[3,1,1,1] (version 4)
Subtract the first 1 numbers of version 2 to get
[2,1,1,1] (version 5)
Then the program would output the final version: