Problem
A Bitset is a data structure that compactly stores bits.
Implement the Bitset
class:
Bitset(int size)
Initializes the Bitset withsize
bits, all of which are0
.void fix(int idx)
Updates the value of the bit at the indexidx
to1
. If the value was already1
, no change occurs.void unfix(int idx)
Updates the value of the bit at the indexidx
to0
. If the value was already0
, no change occurs.void flip()
Flips the values of each bit in the Bitset. In other words, all bits with value0
will now have value1
and vice versa.boolean all()
Checks if the value of each bit in the Bitset is1
. Returnstrue
if it satisfies the condition,false
otherwise.boolean one()
Checks if there is at least one bit in the Bitset with value1
. Returnstrue
if it satisfies the condition,false
otherwise.int count()
Returns the total number of bits in the Bitset which have value1
.String toString()
Returns the current composition of the Bitset. Note that in the resultant string, the character at theith
index should coincide with the value at theith
bit of the Bitset.
Examples
Example 1
|
|
Constraints
1 <= size <= 10^5
0 <= idx <= size - 1
- At most
105
calls will be made in total tofix
,unfix
,flip
,all
,one
,count
, andtoString
. - At least one call will be made to
all
,one
,count
, ortoString
. - At most
5
calls will be made totoString
.
Solution
Method 1 – Lazy Flip with Count Tracking
Intuition
To efficiently support fix, unfix, flip, and query operations, we use a lazy flip approach. Instead of flipping all bits, we maintain a flip flag and invert the meaning of 0 and 1 when the flag is set. We also track the count of 1s for fast queries.
Approach
- Use an array
bits
to store the current state of each bit (0 or 1). - Maintain a
flip_flag
to indicate if the bits are flipped. - Track the count of 1s (
ones_count
). - For
fix(idx)
, set the bit atidx
to 1 (considering flip), updateones_count
if changed. - For
unfix(idx)
, set the bit atidx
to 0 (considering flip), updateones_count
if changed. - For
flip()
, toggle theflip_flag
and updateones_count
tosize - ones_count
. - For
all()
, check ifones_count == size
. - For
one()
, check ifones_count > 0
. - For
count()
, returnones_count
. - For
toString()
, build the string considering the flip flag.
Code
|
|
|
|