LINDEX for position access in Redis - Time & Space Complexity
When using Redis to get an item from a list by its position, it's important to know how the time to get that item changes as the list grows.
We want to understand how fast or slow the LINDEX command is when the list gets bigger.
Analyze the time complexity of the following Redis command.
# Get the element at position 5 from the list 'mylist'
LINDEX mylist 5
# Get the element at position 100 from the list 'mylist'
LINDEX mylist 100
# Get the element at position -1 (last element) from the list 'mylist'
LINDEX mylist -1
This command fetches an element at a given index from a Redis list.
Look at what Redis does internally to find the element.
- Primary operation: Redis traverses the list from the start or end to reach the requested position.
- How many times: It moves through each element one by one until it reaches the target index.
The time to get an element grows as the position number grows because Redis must walk through the list to that spot.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps to reach the element |
| 100 | About 100 steps to reach the element |
| 1000 | About 1000 steps to reach the element |
Pattern observation: The number of steps grows roughly in direct proportion to the position requested.
Time Complexity: O(n)
This means the time to get an element grows linearly with the position you want in the list.
[X] Wrong: "LINDEX gets any element instantly, no matter the list size."
[OK] Correct: Redis must walk through the list to find the element, so bigger positions take more time.
Understanding how Redis commands scale helps you write better code and explain your choices clearly in real projects or interviews.
"What if we changed the list to a Redis data type that supports direct access, like a hash? How would the time complexity change?"