0
0
Redisquery~5 mins

SET and GET commands in Redis - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: SET and GET commands
O(1)
Understanding Time Complexity

When using Redis commands like SET and GET, it's helpful to know how the time to run these commands changes as data grows.

We want to understand how fast these commands work when storing or retrieving data.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


SET user:1000 "Alice"
GET user:1000
SET user:1001 "Bob"
GET user:1001
SET user:1002 "Carol"
GET user:1002
    

This code stores and retrieves simple string values by key in Redis.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Each SET or GET command accesses a key in the database.
  • How many times: Each command runs once per key, no loops or recursion involved.
How Execution Grows With Input

Each command works directly with one key, so the time to run one command stays about the same no matter how many keys exist.

Input Size (n)Approx. Operations
10About 1 operation per command
100About 1 operation per command
1000About 1 operation per command

Pattern observation: The time to run each command stays steady even as the number of keys grows.

Final Time Complexity

Time Complexity: O(1)

This means each SET or GET command takes about the same time regardless of how many keys are stored.

Common Mistake

[X] Wrong: "The GET command takes longer if there are more keys stored in Redis."

[OK] Correct: Redis uses a fast way to find keys, so GET runs in constant time no matter how many keys exist.

Interview Connect

Knowing that SET and GET run quickly helps you explain how Redis can handle many requests fast, a useful skill in real projects and interviews.

Self-Check

"What if we changed the keys to very long strings? How would the time complexity change?"