2121. Intervals Between Identical Elements Medium

@problem@discussion
#Array#Hash Table#Prefix Sum



1/**
2 * [2121] Intervals Between Identical Elements
3 *
4 * You are given a 0-indexed array of n integers arr.
5 * 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|.
6 * 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].
7 * Note: |x| is the absolute value of x.
8 *  
9 * Example 1:
10 * 
11 * Input: arr = [2,1,3,1,2,3,3]
12 * Output: [4,2,7,2,4,4,5]
13 * Explanation:
14 * - Index 0: Another 2 is found at index 4. |0 - 4| = 4
15 * - Index 1: Another 1 is found at index 3. |1 - 3| = 2
16 * - Index 2: Two more 3s are found at indices 5 and 6. |2 - 5| + |2 - 6| = 7
17 * - Index 3: Another 1 is found at index 1. |3 - 1| = 2
18 * - Index 4: Another 2 is found at index 0. |4 - 0| = 4
19 * - Index 5: Two more 3s are found at indices 2 and 6. |5 - 2| + |5 - 6| = 4
20 * - Index 6: Two more 3s are found at indices 2 and 5. |6 - 2| + |6 - 5| = 5
21 * 
22 * Example 2:
23 * 
24 * Input: arr = [10,5,10,10]
25 * Output: [5,0,3,4]
26 * Explanation:
27 * - Index 0: Two more 10s are found at indices 2 and 3. |0 - 2| + |0 - 3| = 5
28 * - Index 1: There is only one 5 in the array, so its sum of intervals to identical elements is 0.
29 * - Index 2: Two more 10s are found at indices 0 and 3. |2 - 0| + |2 - 3| = 3
30 * - Index 3: Two more 10s are found at indices 0 and 2. |3 - 0| + |3 - 2| = 4
31 * 
32 *  
33 * Constraints:
34 * 
35 * 	n == arr.length
36 * 	1 <= n <= 10^5
37 * 	1 <= arr[i] <= 10^5
38 * 
39 */
40pub struct Solution {}
41
42// problem: https://leetcode.com/problems/intervals-between-identical-elements/
43// discuss: https://leetcode.com/problems/intervals-between-identical-elements/discuss/?currentPage=1&orderBy=most_votes&query=
44
45// submission codes start here
46
47impl Solution {
48    pub fn get_distances(arr: Vec<i32>) -> Vec<i64> {
49        
50    }
51}
52
53// submission codes end
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn test_2121() {
61    }
62}
63


Back
© 2025 bowen.ge All Rights Reserved.