Segment Trees
Also Known As
segment tree
range query
lazy propagation
TL;DR
A tree data structure for O(log n) range queries and point updates — supporting sum, min, max over arbitrary array ranges.
Explanation
Each node stores an aggregate (sum, min, max) over a range. Leaves represent individual elements. Build: O(n). Range query and point update: O(log n) each. Lazy propagation extends to range updates in O(log n). Compare to prefix sum: prefix sum allows O(1) range queries but O(n) updates; segment tree provides O(log n) for both — choose based on query/update ratio.
Common Misconception
✗ A prefix sum array is always equivalent to a segment tree for range queries — prefix sums allow O(1) range queries but O(n) update; segment tree provides O(log n) for both, making it essential for dynamic data.
Why It Matters
A prefix sum array answers range queries in O(1) but requires O(n) rebuild on updates — segment trees handle both in O(log n), enabling efficient analytics on frequently-changing data.
Common Mistakes
- Not implementing lazy propagation for range updates — naive update is O(n)
- Off-by-one errors in range boundaries
- Using segment tree for static data — prefix sum is simpler
- Not handling out-of-range queries gracefully
Code Examples
✗ Vulnerable
// O(n) range sum — slow for large arrays:
function rangeSum(array $arr, int $l, int $r): int {
return array_sum(array_slice($arr, $l, $r - $l + 1));
}
// 1000 queries on 1M element array: 1 billion operations
✓ Fixed
// Segment tree — O(log n) per query and update:
class SegmentTree {
private array $tree;
public function query(int $l, int $r): int { /* O(log n) */ }
public function update(int $pos, int $val): void { /* O(log n) */ }
}
References
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
16 Mar 2026
Edited
22 Mar 2026
Views
21
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 8
Perplexity 4
Google 2
Unknown AI 2
Ahrefs 2
Also referenced
How they use it
crawler 17
crawler_json 1
Related categories
⚡
DEV INTEL
Tools & Severity
🔵 Info
⚙ Fix effort: High
⚡ Quick Fix
Use a segment tree when you need both range queries (sum, min, max over a range) and point updates efficiently — O(log n) for both vs O(n) for naive array approach
📦 Applies To
any
web
cli
🔗 Prerequisites
🔍 Detection Hints
Loop computing sum/min/max over array range on every query; O(n²) for many range queries with updates; no segment tree for time-series aggregate queries
Auto-detectable:
✗ No
⚠ Related Problems
🤖 AI Agent
Confidence: Low
False Positives: Medium
✗ Manual fix
Fix: High
Context: Function
Tests: Update