Search code examples
redissortedsetskip-lists

Redis: Is ZADD better than O(logN) when the inserted element is at the beginning or end?


The redis documentation for ZADD states the operation is O(log N).

However, does anyone know if ZADD is better than O(log N) when the inserted element is at the beginning or end of the sort order?

E.g. for certain implementations this could be O(1).

Specifically, the redis tutorial states that:

Sorted sets are implemented via a dual-ported data structure containing both a skip list and an hash table, so every time we add an element Redis performs an O(log(N)) operation.

It seems plausible to modify a skip list to support O(k) insert at beginning and end, where k is the max level of the skip list.


Solution

  • I had cross-posted this question on the Redis website, and Pieter Noordhuis provided an answer there, which I am cross-posting here:


    That is correct. The sorted set relies on an RNG to determine the number of levels per node (it's a probabilistic data structure). Inserting/deleting an element at the beginning of the skiplist can be O(1), while the theoretical worst case performance is O(N) (with every node having the same level). However, the amortized time complexity is O(log N) when you take in account the distribution of the levels among the nodes.