LeetCode 2905: Find Indices With Index and Value Difference II

ArrayTwo Pointers

Problem Description

Explanation:

To solve this problem, we can iterate through the given array nums and store the index and value in a hashmap. While iterating, we check if there exists another index (j) such that abs(i - j) >= indexDifference and abs(nums[i] - nums[j]) >= valueDifference. If such a pair is found, we return the indices i and j.

Time Complexity:

The time complexity of this approach is O(n), where n is the length of the input array nums.

Space Complexity:

The space complexity of this approach is O(n) to store the indices and values in the hashmap.

:

Solutions

import java.util.*;

class Solution {
    public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {
        Map<Integer, Integer> map = new HashMap<>();
        
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(nums[i])) {
                int j = map.get(nums[i]);
                if (Math.abs(i - j) >= indexDifference && Math.abs(nums[i] - nums[j]) >= valueDifference) {
                    return new int[]{i, j};
                }
            }
            map.put(nums[i], i);
        }
        
        return new int[]{-1, -1};
    }
}

Loading editor...