I have a problem in which a boy has n cards (2 faces one black one white <=> 0/1). Initially the cards are all white faced up.
I need to be able to do two operations on the row of n cards.
- flip(i,j) flips the cards between rows i and j indexes
- state(i) returns the colour of the card at i index position
What i need to find is a method to keep the sum of these two operations under O(n).
Any ideas of a good data structure to solve this?
You could create a balanced tree where the cards are leaves and have flip indicator at each node.
To flip the cards, flip the nodes closest to the root that cover the interval. This is O(log n).
To get the state of a card, go though the root to the corresponding leaf and xor the flip indicators from all nodes in the path. This is also O(log n).
For example, if you had tree like this:
And wanted to flip the interval [1, 3], you would flip nodes B and 3. To get the state of 2, you would xor values in A, B and 2 and find out that the node is flipped.