Here's the MO's algorithm structure:
function moAlgorithm(arr, queries)
B := floor(sqrt(n))
sort queries by (floor(l / B), r)
currentL := 0
currentR := -1
currentAnswer := initial value
for each query (l, r, queryIndex)
// Expand/shrink to reach [l, r]
while currentR < r
currentR := currentR + 1
add(arr[currentR])
while currentL > l
currentL := currentL - 1
add(arr[currentL])
while currentR > r
remove(arr[currentR])
currentR := currentR - 1
while currentL < l
remove(arr[currentL])
currentL := currentL + 1
answers[queryIndex] := currentAnswer
return answers
You implement and based on what you're computing.