#2166

Design Bitset

Medium
ArrayHash TableStringDesignArrayHash Map
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses an additional variable to track the number of flips and the state of the bits. This allows for efficient operations without needing to traverse the entire list for every operation.

⚙️

Algorithm

8 steps
  1. 1Step 1: Initialize a list of size 'size' with all elements set to 0 and a flip counter.
  2. 2Step 2: For 'fix(idx)', set the bit at index 'idx' to 1 if it is currently 0, and increment the flip counter if it was flipped.
  3. 3Step 3: For 'unfix(idx)', set the bit at index 'idx' to 0 if it is currently 1, and increment the flip counter if it was flipped.
  4. 4Step 4: For 'flip()', toggle the flip counter and the state of the bits.
  5. 5Step 5: For 'all()', check if the count of bits is equal to the size considering the flip state.
  6. 6Step 6: For 'one()', check if the count of bits is greater than 0 considering the flip state.
  7. 7Step 7: For 'count()', return the count of bits adjusted by the flip state.
  8. 8Step 8: For 'toString()', construct the string based on the current flip state.
solution.py28 lines
1class Bitset:
2    def __init__(self, size: int):
3        self.bits = [0] * size
4        self.flip_count = 0
5        self.size = size
6    
7    def fix(self, idx: int):
8        if self.bits[idx] == self.flip_count % 2:
9            self.bits[idx] = 1 - self.flip_count % 2
10    
11    def unfix(self, idx: int):
12        if self.bits[idx] != self.flip_count % 2:
13            self.bits[idx] = self.flip_count % 2
14    
15    def flip(self):
16        self.flip_count += 1
17    
18    def all(self) -> bool:
19        return self.count() == self.size
20    
21    def one(self) -> bool:
22        return self.count() > 0
23    
24    def count(self) -> int:
25        return sum(1 for b in self.bits if b == (self.flip_count % 2))
26    
27    def toString(self) -> str:
28        return ''.join(str(1 - (b ^ (self.flip_count % 2))) for b in self.bits)

Complexity note: The time complexity is O(n) for the count and toString operations, while all other operations are O(1) due to the use of the flip counter.

  • 1Using a flip counter allows us to efficiently manage the state of bits without needing to traverse the entire array for every operation.
  • 2Understanding how to manipulate bits and their states can lead to more efficient algorithms.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.