Skip to content

Advanced Data Structures - Tổng Quan

"Cấu trúc dữ liệu đúng = Performance đúng. Chọn sai = Chậm 1000x." - HPN

The Range Query Problem

Bài toán: Cho array N phần tử, trả lời nhiều queries dạng:

  1. Range query: Tính sum/min/max của đoạn [L, R]
  2. Point update: Thay đổi giá trị tại index i

Naive Approach Analysis

OperationNaive ArrayPrefix Sum
Range QueryO(N)O(1)
Point UpdateO(1)O(N)

❌ THE PROBLEM

  • Array: Query chậm O(N)
  • Prefix Sum: Update chậm O(N)

Với 100K queries trên 100K elements → Timeout!

Advanced Structures

StructureQueryUpdateBest for
Segment TreeO(log N)O(log N)General (sum, min, max, gcd)
Fenwick Tree (BIT)O(log N)O(log N)Sum queries (simpler)
Sparse TableO(1)N/AStatic data (no updates)

When to Use What?

Real-World Applications

DomainUse CaseChi tiết
FinanceStock analysisMin/Max price in time window
GamingLeaderboardDynamic ranking queries
DatabasesOLAPAggregate queries
GraphicsCollision detection2D range queries
NetworkingPacket analysisTraffic in time window

Roadmap Module

  1. Segment Tree - General range queries
  2. Fenwick Tree (BIT) - Simpler sum queries

💡 HPN's Rule

"Sum + Updates → Fenwick Tree (đơn giản hơn). Min/Max hoặc Lazy → Segment Tree."