category-wise-problems

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

Approach

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.

implementation of the same ```cpp vector getDistances(vector& arr) { map<int, vector> mp; int n = arr.size(); for (int i = 0; i < n; i++) mp[arr[i]].push_back(i); vector prefix(n, 0), suffix(n, 0); for (const auto& [key, value]: mp) { for (int i = 1; i < value.size(); i++) { int diff = value[i] - value[i - 1]; int elements_to_left = i; prefix[value[i]] = prefix[value[i - 1]] + elements_to_left * diff; } for (int i = value.size() - 2; i >= 0; i--) { int diff = value[i + 1] - value[i]; int elements_to_right = (value.size() - i - 1); suffix[value[i]] = suffix[value[i + 1]] + elements_to_right * diff; } } vector ans; for (int i = 0; i < n; i++) ans.push_back(prefix[i] + suffix[i]); return ans; } ``` </details>