What is a segment tree?
Why Interviewers Ask This
This question targets practical, hands-on experience with Data Structures & Algorithms. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
A segment tree is a binary tree where each node stores information about a range of the array. Useful for answering range queries (sum, min, max) and supporting point updates efficiently. Structure: leaf nodes represent individual elements; internal nodes represent the aggregate (sum/min/max) of their children's ranges; root represents the entire array range [0, n-1]. Build: O(n). Operations: Range query: O(log n) — traverse only relevant segments; Point update: O(log n) — update leaf and propagate up. Implementation: array-based (similar to heap), node at index i has children at 2i and 2i+1. Space: O(n) (typically 4n array). Lazy propagation: for range updates (add 5 to all elements in [l, r]), push updates lazily — only propagate when the segment is queried. Enables O(log n) range updates. Applications: (1) Range sum queries with updates; (2) Range minimum/maximum queries; (3) Count inversions; (4) Computational geometry; (5) Interval scheduling. Fenwick Tree (Binary Indexed Tree) is simpler to implement and uses less memory for range sum queries but doesn't generalize to all segment tree use cases. Segment trees are powerful for competitive programming and database index structures.
Common Mistake
Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your Data Structures & Algorithms experience.
Previous
What is the longest increasing subsequence (LIS)?
Next
What is a Fenwick tree (Binary Indexed Tree)?