Skip to the solution
EasyDSA17 min read

What is the time complexity of common operations on arrays, hash maps, and balanced trees?

753 views

The problem

Question presented to candidate: "You will be coding in Python. Before we start, tell me the time complexity of the basic operations โ€” access, search, insert and delete โ€” on an array, a hash map and a balanced binary search tree, and which Python types you would use for each."

What a strong answer should cover:

  • Dynamic array: O(1) index access, O(1) amortized append, O(n) insert or delete at the front or middle (elements shift), O(n) search, O(log n) search if sorted.
  • Hash map: O(1) average insert, lookup and delete; O(n) worst case under collisions; no ordering of keys.
  • Balanced BST: O(log n) insert, delete and lookup because the height stays about log n; also min, max, floor, ceiling and ordered iteration; an unbalanced BST degrades to O(n).
  • Choosing: hash map for pure lookups, tree for ordered or range queries, array for index access and fast iteration.
  • Python mapping: list is a dynamic array, dict/set are hash tables, and there is no built-in balanced tree (bisect on a sorted list has O(n) inserts).

Code / implementation expected: Optional โ€” use list, dict and bisect correctly and state the cost of each call.

  • complexity

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

17 min read ยท 13 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonCount shifts and comparisons: array inserts, linear vs binary search, hash buckets
PythonBalanced vs unbalanced binary search tree: height and lookup cost
PythonThe standard-library structures and what each call costs

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 16 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextEasy

How do you find the longest common prefix of an array of strings?

Continue