EXISTS to check key existence in Redis - Time & Space Complexity
We want to understand how long it takes to check if a key exists in Redis using the EXISTS command.
How does the time needed change when we check more keys?
Analyze the time complexity of the following code snippet.
# Check if one or more keys exist in Redis
EXISTS key1 key2 key3
# Returns the number of keys that exist
This command checks if each given key exists and returns how many are found.
- Primary operation: Checking each key one by one to see if it exists.
- How many times: Once for each key given in the command.
As you add more keys to check, the time grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 key existence checks |
| 100 | 100 key existence checks |
| 1000 | 1000 key existence checks |
Pattern observation: The time grows linearly as you check more keys.
Time Complexity: O(n)
This means the time to check keys grows directly with the number of keys you ask about.
[X] Wrong: "Checking multiple keys with EXISTS is instant no matter how many keys."
[OK] Correct: Each key must be checked separately, so more keys take more time.
Knowing how EXISTS scales helps you write efficient Redis queries and understand performance when checking many keys.
"What if we checked keys one by one with separate EXISTS commands instead of all at once? How would the time complexity change?"