Design Bitset - Problem
A Bitset is a data structure that compactly stores bits.
Implement the Bitset class:
Bitset(int size)Initializes the Bitset withsizebits, all of which are 0.void fix(int idx)Updates the value of the bit at the indexidxto 1. If the value was already 1, no change occurs.void unfix(int idx)Updates the value of the bit at the indexidxto 0. If the value was already 0, no change occurs.void flip()Flips the values of each bit in the Bitset. In other words, all bits with value 0 will now have value 1 and vice versa.boolean all()Checks if the value of each bit in the Bitset is 1. Returns true if it satisfies the condition, false otherwise.boolean one()Checks if there is at least one bit in the Bitset with value 1. Returns true if it satisfies the condition, false otherwise.int count()Returns the total number of bits in the Bitset which have value 1.String toString()Returns the current composition of the Bitset. Note that in the resultant string, the character at the ith index should coincide with the value at the ith bit of the Bitset.
Input & Output
Example 1 — Basic Operations
$
Input:
operations = ["Bitset", "fix", "fix", "flip", "all", "unfix", "flip", "one", "unfix", "count", "toString"], values = [[2], [1], [1], [], [], [0], [], [], [0], [], []]
›
Output:
[null, null, null, null, false, null, null, true, null, 1, "01"]
💡 Note:
Create size 2 bitset "00" → fix(1) → "01" → flip() → "10" → all() false → unfix(0) → "00" → flip() → "11" → one() true → unfix(0) → "01" → count() 1 → toString() "01"
Example 2 — All Bits Set
$
Input:
operations = ["Bitset", "fix", "fix", "all", "one", "count"], values = [[2], [0], [1], [], [], []]
›
Output:
[null, null, null, true, true, 2]
💡 Note:
Create "00" → fix(0) → "10" → fix(1) → "11" → all() true, one() true, count() 2
Example 3 — Empty Bitset
$
Input:
operations = ["Bitset", "all", "one", "count", "toString"], values = [[3], [], [], [], []]
›
Output:
[null, false, false, 0, "000"]
💡 Note:
Create size 3 bitset with all zeros: all() false, one() false, count() 0, toString() "000"
Constraints
- 1 ≤ size ≤ 105
- 0 ≤ idx ≤ size - 1
- At most 105 calls will be made to fix, unfix, flip, all, one, count, and toString
Visualization
Tap to expand
Understanding the Visualization
1
Initialize
Create bitset with size n, all bits set to 0
2
Operations
Fix, unfix, flip bits and query status
3
Output
Return query results and string representation
Key Takeaway
🎯 Key Insight: Use flip flag and count tracking to make operations efficient
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code