Efficient Counter Implementation with Bit Arrays and Amortized Analysis

To implement a counter supporting both increment and reset operations in O(n) amortized time, we utilize a bit array along with a pointer tracking the position of the most significant set bit.

The data structure maintains:

  • A binary array bits representing the counter value
  • An index top_bit pointing to the highest-order 1-bit

For the increment operation, we process bits starting from the tracked position:

class BinaryCounter:
    def __init__(self, max_bits=32):
        self.storage = [0] * max_bits
        self.top_bit = -1
    
    def increment(self):
        position = 0
        # Flip all consecutive 1-bits to 0
        while position <= self.top_bit and self.storage[position] == 1:
            self.storage[position] = 0
            position += 1
        
        if position < len(self.storage):
            self.storage[position] = 1
            self.top_bit = max(self.top_bit, position)
    
    def reset_all(self):
        # Clear bits up to current top position
        for idx in range(self.top_bit + 1):
            self.storage[idx] = 0
        self.top_bit = -1

During increment, consecutive trailing 1-bits are flipped to 0 before setting the next bit to 1. The pointer is updated accordingly.

The reset operation clears all bits and resets the pointer:

Each bit flip during increment contributes constant work. Across n operations, each bit position particpiates in at most one flip cycle, resulting in O(n) total work. Maintaining the top-bit pointer adds constant overhead per operation.

Tags: algorithms data-structures amortized-analysis bit-manipulation

Posted on Tue, 14 Jul 2026 16:43:09 +0000 by stangoe