Lecture 13
Lecture 13
CSE 4303
Data Structures
Asaduzzaman Herok
Lecturer | CSE | IUT
[email protected]
Problem Scenario
Think of a university of 10 thousand ex-students. Their results and other informations are sorted by their
student IDs. Now it is very frequent that authority want to know from roll x to roll y what is the maximum
CGPA.
What to do?
● Linear Search?
● Binary Search?
● Sorting the data based on CGPA?
Is there a way to get the result without changing the relative order of the data?
Generalised Way
Given array of n elements A = { a1, a2, … … }, in each query (l, r) it is asked to give the
F({al,al+1,al+2, … … , ar-2,ar-1,ar}).
What to do then?
● Sparse Table
● Fenwick Tree
● Segment Tree
● Square Root Decomposition
● Square Root Tree
● Mo’s Algorithm
Pros:
● Building time complexity O(n log n).
● Space complexity O(n log n)
● Supported query function:
○ Element in the array supports the associative property i.e x o (y o z) = (x o y) o z.
[Here o is a operator]
○ F(a, b, c, d) = F(a,b) o F(c,d), from the non-overlapping segments. Time
complexity O(log n)
○ F(a, b, c, d) = F(a,b,c) o F(b,c,d), from the overlapping segments. Time
complexity O(1) i.e constant time.
Cons:
● Can’t work with update i.e data sequence must be immutable
● Update operation would cause O(n log n) time complexity to rebuild.
Idea:
● Pre-compute all the answers of range with length equal to some powers of 2
● While querying break the query segments into some segments of powers of 2 and use their value
to compute for the query segment.
The most common application of Fenwick tree is calculating the sum of a range.
F({al,al+1, … … , ar-1, ar}) = al + al+1 + … … + ar-1 + ar
F should support both F(a, b, c, d) = F(a,b) o F(c,d) and F(c,d) = F(a, b, c, d) o F(a, b),
o denotes some kind of operators.
Example:Sum(a, b, c, d)=Sum(a, b)+Sum(c, d) and Sum(c, d)=Sum(a, b, c, d)-Sum(a, b)
Xor(a, b, c, d)=Xor(a, b) xor Xor(c, d) and Xor(c, d)=Xor(a, b, c, d) xor Xor(a, b)