Skip to the code
cf.
+25 XP

#682 Feature Flag Register

medium

Build a small feature-flag store that keeps all flags in one number. Implement the class FlagRegister:

  • new FlagRegister(size) creates size flags, numbered 0 to size - 1, all off.
  • enable(i) and disable(i) turn flag i on or off, and toggle(i) flips it. They return nothing.
  • isOn(i) returns true if flag i is on.
  • count() returns how many flags are on.
  • allOn() returns true if every one of the size flags is on.

Every method should run in O(1) time, apart from count, which may take one step per flag that is on.

Each example lists the calls in order, then each call's arguments. The first call creates the object with new FlagRegister(…); the output lists what each call returns (null for the constructor and for methods that return nothing).

Example 1

Input: ["FlagRegister","enable","enable","isOn","isOn","count","allOn"]
[[3],[0],[2],[2],[1],[],[]]
Output: [null,null,null,true,false,2,false]

Flags 0 and 2 are on and flag 1 is off, so 2 flags are on but not all 3.

Example 2

Input: ["FlagRegister","toggle","toggle","isOn","allOn"]
[[1],[0],[0],[0],[]]
Output: [null,null,null,false,false]

Toggling flag 0 twice turns it on and then off again.

Constraints

  • 1 <= size <= 31
  • 0 <= i < size
  • At most 1000 calls.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).