contains category wise problems(data structures, competitive) of popular platforms.
View the Project on GitHub mayankdutta/category-wise-problems
2121. Intervals Between Identical Elements, medium, prefix sums.
NOTE
prefix sums is structured in index form rather then value form.
you might have seen prefix sum like
for (int i = 1; i < n; i++)
prefix[i] = prefix[i - 1] + arr[i];
whereas this will be
for (int i = 1; i < n; i++)
prefix[arr[i]] = prefix[arr[i - 1]] + something.
notice we are storing values at the value of that array
O(n)
. (can be extended in O(n^2)
).0, 2, 4, 5, 6
.4
from 0, 2
.5
.
0 -- 4 -> 5
.2 -- 4 -> 5
.4 -- 4 -> 5
.4
. means 3 times
.5 - 4
.in generalise form
prefix[current_element] = prefix[previous_element] +
(elements_to_the_left) *
(current_element - previous_element)
We will then prepare a prefix array and suffix array to maintain this value from both sides.