LRANGE for reading elements in Redis - Time & Space Complexity
When using Redis to read parts of a list, it's important to know how the time it takes grows as the list gets bigger.
We want to understand how the LRANGE command's work changes with the size of the list and the requested range.
Analyze the time complexity of the following Redis command.
LRANGE mylist 0 99
This command reads the first 100 elements from the list named 'mylist'.
Look at what repeats when LRANGE runs.
- Primary operation: Reading each element in the requested range from the list.
- How many times: Once for each element in the range (here, 100 times).
The time to run LRANGE grows with how many elements you ask for, not the total list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 reads |
| 100 | 100 reads |
| 1000 | 1000 reads |
Pattern observation: The work grows directly with the number of elements requested.
Time Complexity: O(k)
This means the time depends on how many elements you want to read, not the whole list size.
[X] Wrong: "LRANGE always takes time based on the total list size."
[OK] Correct: Actually, LRANGE only reads the elements you ask for, so the time depends on the range size, not the full list.
Understanding how LRANGE scales helps you explain how Redis handles list reads efficiently, a useful skill for real projects and interviews.
What if we changed LRANGE to read the entire list instead of a part? How would the time complexity change?