ZRANGEBYLEX for lexicographic queries in Redis - Time & Space Complexity
When using Redis to get items in a sorted set by their lexicographic order, it is important to understand how the time taken grows as the set gets bigger.
We want to know how the cost changes when we ask for ranges of elements sorted by their text order.
Analyze the time complexity of the following Redis command usage.
# Get elements in sorted set 'myzset' between 'a' and 'm' lexicographically
ZRANGEBYLEX myzset [a [m
# Optionally limit results
ZRANGEBYLEX myzset [a [m LIMIT 0 10
This command returns elements from a sorted set whose values fall between two given strings in lexicographic order.
Look for repeated steps that affect performance.
- Primary operation: Scanning the sorted set elements between the given lexicographic range.
- How many times: The number of elements in the requested range, up to the LIMIT if used.
The time grows roughly with how many elements fall inside the requested lexicographic range.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 or fewer elements scanned |
| 100 | About 100 or fewer elements scanned |
| 1000 | About 1000 or fewer elements scanned |
Pattern observation: The cost grows linearly with the number of elements in the lexicographic range requested.
Time Complexity: O(m)
This means the time grows in direct proportion to the number of elements returned or scanned in the lexicographic range.
[X] Wrong: "ZRANGEBYLEX always runs in constant time regardless of range size."
[OK] Correct: The command must scan through all elements in the requested range, so if the range is large, it takes more time.
Understanding how Redis commands scale with input size helps you design efficient queries and avoid slowdowns in real applications.
What if we add a LIMIT clause to the ZRANGEBYLEX command? How would the time complexity change?