← Questions
Set over a bounded range of integers
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's technical phone screen, last asked Apr 2026. It tests design, arrays and bitsets.
Implement a set of integers when every value is known to lie in [0, limit). It supports add, remove and contains, each in worst-case O(1) time. Explain why the known range changes which data structure you pick.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
BoundedSet(limit: int)— starts empty. -
add(value: int) -> bool—Trueif the value was absent and is now in the set. -
remove(value: int) -> bool—Trueif the value was present and is now gone. contains(value: int) -> bool
Example
s = BoundedSet(5)
s.add(2) -> True
s.add(2) -> False # already present
s.contains(2) -> True
s.remove(2) -> True
s.contains(2) -> False
s.remove(2) -> False
Constraints
-
1 <= limit <= 10^6; every value is in[0, limit). - Up to 2 × 10^5 operations.
Clarifying questions
- How large is the range, and is it known up front?
- What should
addof a present value orremoveof an absent one return? - Do we also need iteration in sorted order, or the size?
What a strong answer covers
- Direct addressing: a boolean array (or a bitset,
limit / 8bytes) indexed by value; O(1) worst case with no hashing. - The one-time O(limit) initialization cost, and the sparse-set trick that avoids it.
- Keeping a count for O(1) size.
- When the universe is huge or unknown: a hash set (O(1) expected), or a balanced tree if you need sorted order.
Follow-ups
-
next(x): the smallest member at leastx, fast (a bitset with word scans, or a van Emde Boas tree). - The range is 10^12 but only 10^5 values are ever added.
- Many threads update the set at once.
Where it's asked
- Amazon · Technical phone screen · Last asked Apr 202660 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
