Medium interview relevanceRoadmap: Advanced
TimeSearch, insert, delete O(log n) worst case
SpaceO(n)

Why it costs this much

Rotations keep the height at O(log n) after every insert and delete.

Code

import bisect
i = bisect.bisect_left(sorted_list, x)   # O(log n): binary search
sorted_list.insert(i, x)                 # O(n): shifts later items
# A balanced tree makes both steps O(log n) together.

Common pitfalls

More work to implement than a hash table, and lookups are O(log n), not O(1). Python's standard library has no balanced tree; bisect on a list costs O(n) per insert.

Operation by operation

OperationBestAverageWorstSpace
Balanced BST search, insert, deleteO(1)O(log n)O(log n)O(1) extra per operation

Balanced BST search, insert, delete. Height is kept at O(log n) by rotations, as in AVL and red-black trees. Python has no built-in balanced tree. Java TreeMap and C++ std::map are red-black trees.

Keyboard shortcuts

/
Search topics
?
Show this list of shortcuts
r
Open the revision sheet
b
Save or unsave the focused card, or the topic you are reading
l
Mark the focused card, or the topic you are reading, as learned
Space Left arrow Right arrow
In the visualizer: play or pause, step back, step forward
1 to 4 Enter
In the quiz: pick an answer, then go to the next question
Escape
Close this list