LeetCode 2905: Find Indices With Index and Value Difference II

ArrayTwo Pointers

LeetCode 2905 Solution Explanation

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.

:

LeetCode 2905 Solutions in Java, C++, Python

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};
    }
}

Interactive Code Editor for LeetCode 2905

Improve Your LeetCode 2905 Solution

Use the editor below to refine the provided solution for LeetCode 2905. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems