Blog

Your dream job? Lets Git IT.
Interactive technical interview preparation platform designed for modern developers.

XGitHub

Platform

  • Categories

Resources

  • Blog
  • About the app
  • FAQ
  • Feedback

Legal

  • Privacy Policy
  • Terms of Service

© 2025 LetsGit.IT. All rights reserved.

LetsGit.IT/Categories/Data Structures
Data Structureshard

What is a segment tree and what complexity does it give for range queries and updates?

Tags
#segment-tree#range-query#updates#big-o
Back to categoryPractice quiz

Answer

A segment tree is a binary tree over array segments. It supports range queries (sum/min/max) and point updates in O(log n) after an O(n) build. With lazy propagation it can handle range updates too.

class SegTree {
  private tree: number[];
  private n: number;

  constructor(n: number) {
    this.n = n;
    this.tree = Array(4 * n).fill(0);
  }

  update(node: number, l: number, r: number, idx: number, val: number) {
    if (l === r) {
      this.tree[node] = val;
      return;
    }
    const mid = Math.floor((l + r) / 2);
    if (idx <= mid) this.update(node * 2, l, mid, idx, val);
    else this.update(node * 2 + 1, mid + 1, r, idx, val);
    this.tree[node] = this.tree[node * 2] + this.tree[node * 2 + 1];
  }
}

Related questions

Data Structures
Building a heap from an array: why can it be O(n), not O(n log n)?
#heap#heapify#complexity
Data Structures
Why can a hash table resize cause latency spikes, and how can you mitigate it?
#hash-table#rehash#latency
Data Structures
What is a sparse table and what problems is it good for?
#sparse-table#rmq#preprocessing
Data Structures
What is a segment tree and what is it good for?
#segment-tree#range-query#big-o
Data Structures
What is the heap property in a binary heap?
#heap#binary-heap#priority-queue
Data Structures
What is a skip list and how does it compare to balanced trees?
#skip-list#linked-list#probabilistic