Skip to the solution
HardDSA9 min read

What is a segment tree and when do you need one?

631 views

The problem

Question presented to candidate: "What is a segment tree? Explain how it answers a range-sum query and a point update, how big the array needs to be, and how you would support adding a value to a whole range. When would you choose it over prefix sums or a Fenwick tree? Show the core in Python."

What a strong answer should cover:

  • Each node stores an aggregate of one index range; children split the range in half; about logโ‚‚ n levels; any associative merge (sum, min, max, gcd) works.
  • Query with the no / total / partial overlap cases and update along one root-to-leaf path, both O(log n); build is O(n).
  • The implicit array layout (children 2i and 2i + 1) and why 4n slots are enough.
  • Lazy propagation for range updates: tag fully covered nodes and push tags down before visiting children.
  • When to use it versus prefix sums (static array), a Fenwick tree (sums with point updates) and a sparse table (static min/max).
  • Python details: a list of size 4 * n, hi=None instead of a default that uses self, float('inf') as the min identity, and the recursion depth being only about logโ‚‚ n.

Code / implementation expected: Optional โ€” a recursive sum segment tree with update and query in Python; lazy propagation is usually discussed rather than fully coded.

  • dsa
  • segment-tree
  • range-query

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

9 min read ยท 14 sections

Python code

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

PythonSum segment tree: build, query, update, vs brute force
PythonLazy propagation: range add + range min, vs brute force

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 144 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 nextHard

How do you compute the edit distance between two strings?

Continue