Algorithmsrange queries

Range Queries (Interval Questions on Arrays)

TT
Testlaa Team
May 15, 20262 min read

Range queries ask for an aggregate on a[l..r] repeatedly—segment trees, Fenwick trees, and sparse tables are the main tools depending on updates.

Why this shows up in the real world

Time-series dashboards, game leaderboards, and competitive programming interval problems all need fast answers on changing arrays.

Core idea (explained for students)

Classify the problem: static vs point update vs range update; sum vs min vs count. That choice picks the structure before you code.

Try this in Python

class SegTreeSum:
    def __init__(self, arr: list[int]) -> None:
        self.n = len(arr)
        self.size = 1
        while self.size < self.n:
            self.size *= 2
        self.t = [0] * (2 * self.size)
        for i, x in enumerate(arr):
            self.t[self.size + i] = x
        for i in range(self.size - 1, 0, -1):
            self.t[i] = self.t[2 * i] + self.t[2 * i + 1]

    def update(self, i: int, val: int) -> None:
        i += self.size
        self.t[i] = val
        while i > 1:
            i //= 2
            self.t[i] = self.t[2 * i] + self.t[2 * i + 1]

    def query(self, l: int, r: int) -> int:
        l += self.size
        r += self.size
        s = 0
        while l <= r:
            if l % 2 == 1:
                s += self.t[l]
                l += 1
            if r % 2 == 0:
                s += self.t[r]
                r -= 1
            l //= 2
            r //= 2
        return s


st = SegTreeSum([1, 3, 5, 7, 9, 11])
print(st.query(1, 4))
st.update(2, 10)
print(st.query(1, 4))

Common mistakes

  • Using O(n) scan per query when q is large (TLE).
  • Picking Fenwick when you need range min (wrong tool).

Key takeaways

  • Write constraints n,q on paper first.
  • Prefix sum handles sum-only static; segment tree when updates exist.

Tags:

Segment tree & range queriesPythonStudents