Unique visitor tracking with sets in Redis - Time & Space Complexity
When tracking unique visitors, we want to know how the work grows as more visitors come in.
We ask: How much time does it take to add and count unique visitors as the list grows?
Analyze the time complexity of the following code snippet.
SADD unique_visitors user1
SADD unique_visitors user2
SADD unique_visitors user3
SCARD unique_visitors
This code adds visitors to a set and then counts how many unique visitors there are.
- Primary operation: Adding a visitor to the set with
SADD. - How many times: Once per visitor added.
- Counting operation:
SCARDcounts unique visitors once.
Each new visitor is checked and added if unique. Counting is quick regardless of size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 adds + 1 count |
| 100 | 100 adds + 1 count |
| 1000 | 1000 adds + 1 count |
Pattern observation: Adding visitors grows linearly; counting stays constant time.
Time Complexity: O(n)
This means the time to add visitors grows directly with the number of visitors.
[X] Wrong: "The total time to track n unique visitors is O(1)."
[OK] Correct: Although each SADD is O(1), performing n additions requires O(n) time total.
Understanding how adding unique items scales helps you explain data handling in real apps clearly and confidently.
"What if we used a list instead of a set to track visitors? How would the time complexity change?"