You are given a 0-indexed array of n
integers arr
.
The interval between two elements in arr
is defined as the absolute difference between their indices. More formally, the interval between arr[i]
and arr[j]
is |i - j|
.
Return an array intervals
of length n
where intervals[i]
is the sum of intervals between arr[i]
and each element in arr
with the same value as arr[i]
.
Note: |x|
is the absolute value of x
.
Example 1:
Input: arr = [2,1,3,1,2,3,3] Output: [4,2,7,2,4,4,5] Explanation: - Index 0: Another 2 is found at index 4. |0 - 4| = 4 - Index 1: Another 1 is found at index 3. |1 - 3| = 2 - Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7 - Index 3: Another 1 is found at index 1. |3 - 1| = 2 - Index 4: Another 2 is found at index 0. |4 - 0| = 4 - Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4 - Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5
Example 2:
Input: arr = [10,5,10,10] Output: [5,0,3,4] Explanation: - Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5 - Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0. - Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3 - Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4
Constraints:
n == arr.length
1 <= n <= 105
1 <= arr[i] <= 105
Solution: Math / Hashtable + Prefix Sum
For each arr[i], suppose it occurs in the array of total c times, among which k of them are in front of it and c – k – 1 of them are after it. Then the total sum intervals:
(i – j1) + (i – j2) + … + (i – jk) + (jk+1-i) + (jk+2-i) + … + (jc-i)
<=> k * i – sum(j1~jk) + sum(jk+1~jc) – (c – k – 1) * i
Use a hashtable to store the indies of each unique number in the array and compute the prefix sum for fast range sum query.
Time complexity: O(n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Author: Huahua class Solution { public: vector<long long> getDistances(vector<int>& arr) { const int n = arr.size(); unordered_map<int, vector<long long>> m; vector<int> pos(n); for (int i = 0; i < n; ++i) { m[arr[i]].push_back(i); pos[i] = m[arr[i]].size() - 1; } for (auto& [k, idx] : m) partial_sum(begin(idx), end(idx), begin(idx)); vector<long long> ans(n); for (int i = 0; i < n; ++i) { const auto& sums = m[arr[i]]; const long long k = pos[i]; const long long c = sums.size(); if (k > 0) ans[i] += k * i - sums[k - 1]; if (k + 1 < c) ans[i] += (sums[c - 1] - sums[k]) - (c - k - 1) * i; } return ans; } }; |