0
0
Redisquery~5 mins

Unique visitor tracking with sets in Redis - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Unique visitor tracking with sets
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Adding a visitor to the set with SADD.
  • How many times: Once per visitor added.
  • Counting operation: SCARD counts unique visitors once.
How Execution Grows With Input

Each new visitor is checked and added if unique. Counting is quick regardless of size.

Input Size (n)Approx. Operations
1010 adds + 1 count
100100 adds + 1 count
10001000 adds + 1 count

Pattern observation: Adding visitors grows linearly; counting stays constant time.

Final Time Complexity

Time Complexity: O(n)

This means the time to add visitors grows directly with the number of visitors.

Common Mistake

[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.

Interview Connect

Understanding how adding unique items scales helps you explain data handling in real apps clearly and confidently.

Self-Check

"What if we used a list instead of a set to track visitors? How would the time complexity change?"