LeetCode 2905: Find Indices With Index and Value Difference II Solution

Master LeetCode problem 2905 (Find Indices With Index and Value Difference II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2905. Find Indices With Index and Value Difference II

Problem 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.

:

Solution Code

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

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2905 (Find Indices With Index and Value Difference II)?

This page provides optimized solutions for LeetCode problem 2905 (Find Indices With Index and Value Difference II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2905 (Find Indices With Index and Value Difference II)?

The time complexity for LeetCode 2905 (Find Indices With Index and Value Difference II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2905 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2905 in Java, C++, or Python.

Back to LeetCode Solutions