LeetCode 2367: Number of Arithmetic Triplets

Problem Description

Explanation:

To solve this problem, we can use a hashmap to keep track of the count of potential triplets as we iterate through the array. For each element num in the array, we check if num - diff exists in the map (i.e., a potential j) and num - 2*diff exists in the map (i.e., a potential i). If both exist, we increment the count of triplets by the value at num - diff. This is because we have found a valid triplet (i, j, k) where j is the current element, i is num - diff, and k is num.

Time Complexity:

The time complexity of this approach is O(N), where N is the number of elements in the array.

Space Complexity:

The space complexity is also O(N) due to the hashmap storing potential triplets.

:

Solutions

class Solution {
    public int numberOfArithmeticSlices(int[] nums, int diff) {
        int count = 0;
        Map<Integer, Integer> map = new HashMap<>();
        
        for (int num : nums) {
            int prevCount = map.getOrDefault(num - diff, 0);
            count += prevCount;
            
            map.put(num, map.getOrDefault(num, 0) + prevCount);
        }
        
        return count;
    }
}

Loading editor...