VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-two-indices-with-different-values-within-specified-range/

⇱ Find two indices with different values within specified range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find two indices with different values within specified range

Last Updated : 23 Jul, 2025

You have an array arr[] of size N and Q queries where in each query, we need to find two distinct indices within the specified range in the array such that the values at those indices are different. If such indices exist, you should return them. Otherwise, return (-1, -1).

Examples:

Input: N = 5, Q = 3, arr[] = {1, 1, 2, 1, 1} queries[][] = {{0, 4}, {0, 1}, {0, 2}}
Output:
1 2
-1 -1
1 2
Explanation: We can select index 1 and 2 in the range 0 to 4 such that the values at these indexes are different, for range (0, 1) we cannot find any such pair of indices which have different values, and for range (0, 2) we can find index 1 and 2 which have different values.

Input: N = 4, Q = 2, arr[] = {1, 1, 1, 2}, queries[][] = {{0, 3}, {0, 2}}
Output:
2 3
-1 -1
Explanation: We can select index 2 and 3 in the range 0 to 3 such that the values at these indexes are different and for range (0, 2) we cannot find any such pair of indices which have different values.

Approach: To solve the problem, follow the below idea:

The key idea behind the approach is to precompute the array to find the nearest index to the left with a different value for each element. Then, for each query, it efficiently checks whether such a pair exists within the specified range using the precomputed information. The use of prefix preprocessing helps achieve an efficient solution to the problem.

Step-by-step algorithm:

  • Create a vector p of size N filled with -1. It tracks the position of the nearest different element to the left for each element.
  • Traverse the array vec from index 1 to N - 1:
  • If the current element is different from the previous one, update p[i] to i - 1 to show the nearest different element's position to the left.
  • Otherwise, keep p[i] the same as p[i-1].
  • For each query:
  • Check if p[r] (nearest different element's position to the left of r) is greater than or equal to l:
  • If it is, print p[r] + 1 and r + 1 (1-indexed) as indices with different values.
  • If not, print "-1 -1" indicating no such pair exists.

Below is the implementation of above approach:


Output
2 4
-1 -1
1 2

Time Complexity: O(N), where N is the size of input array arr[].
Auxiliary Space: O(Q)

Comment
Article Tags: