Algorithmsrange query optimization

Range Query Optimization

TT
Testlaa Team
May 15, 20262 min read

Optimize range queries by picking the right structure: prefix, Fenwick, segment tree, sparse table, or offline Mo’s.

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)

If only sum + point update: Fenwick is shorter. If min/max or non-invertible ops: segment tree. Many queries, no updates: sort + prefix offline.

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

  • Over-engineering segment tree for one query.
  • Missing sqrt decomposition middle ground (O(√n) per op, simpler).

Key takeaways

  • Write operation mix table: (query type, update type) → structure.
  • Mo’s: O((n+q)√n) offline queries on static array.

Tags:

Segment tree & range queriesPythonStudents