Algorithms

Rebinding the photo album

Rebinding the photo album

An album starts empty with room for a fixed number of photos. Adding a photo when there is room is free. Adding one when the album is already full means rebinding it into an album with twice the room, which copies every photo already inside before the new one goes in.

Write cells_copied(appends, capacity), which returns the total number of photos copied while adding appends photos one at a time to an album that started with room for capacity.

Worked example: with appends = 5 and capacity = 1, the first photo goes into the empty album for free. The second finds the album full with 1 photo, so 1 photo is copied and the room becomes 2. The third finds it full with 2, so 2 are copied and the room becomes 4. The fourth is free. The fifth finds it full with 4, so 4 are copied and the room becomes 8. The total is 1 plus 2 plus 4, which is 7.

  • Constraints: appends is between 0 and 1000000, and capacity is between 1 and 1000000.
  • The check is made before the photo is added: a rebinding happens only when the album is exactly full at that moment.
  • Adding no photos copies nothing, and an album that never fills copies nothing.
  • The answer is always less than twice appends, which is the whole point of doubling: a rare expensive step keeps the average cheap.
Code

Run your code to see how it does on the examples. Submit also runs the hidden cases.