Open In App

Find two indices with different values within specified range

Last Updated : 23 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Java
import java.util.*;

public class Main {

    // Function to solve the problem
    static void solve(int N, int[] arr, int Q, int[][] queries) {
        // Array to store the position of the nearest different
        // element to the left
        int[] p = new int[N];
        Arrays.fill(p, -1);

        // Iterating through the array to fill 'p'
        for (int i = 1; i < N; i++) {
            // Setting the current position as the same as the
            // previous one by default
            p[i] = p[i - 1];
            // If the current element is different from the
            // previous one
            if (arr[i] != arr[i - 1]) {
                // Update 'p' to the position of the nearest
                // different element to the left
                p[i] = i - 1;
            }
        }

        // Loop through each query
        for (int i = 0; i < Q; ++i) {
            int l = queries[i][0];
            int r = queries[i][1];
            // If there exists a pair within the range
            if (p[r] >= l) {
                // Print the pair of indices having different
                // elements
                System.out.println(p[r] + " " + r);
            } else {
                // Print "-1 -1" indicating no such pair exists
                System.out.println("-1 -1");
            }
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int N = 5;
        int[] arr = {1, 1, 2, 1, 1};
        int Q = 3;
        int[][] queries = {{0, 4}, {0, 1}, {0, 2}};
        solve(N, arr, Q, queries);
    }
}
C#
using System;

public class GFG
{
    public static void NearestDifferentElement(int N, int[] arr, int Q, int[][] queries)
    {
        // Array to store the position of nearest different element to left
        int[] p = new int[N];
        Array.Fill(p, -1);

        // Iterate through the array to fill 'p'
        for (int i = 1; i < N; i++)
        {
            p[i] = p[i - 1];
            // If the current element is different from previous one
            if (arr[i] != arr[i - 1])
            {
                p[i] = i - 1;
            }
        }

        // Loop through each query
        for (int i = 0; i < Q; ++i)
        {
            int l = queries[i][0];
            int r = queries[i][1];
            // If there exists a pair within the range
            if (p[r] >= l)
            {
                Console.WriteLine(p[r] + " " + r);
            }
            else
            {
                // Print "-1 -1" indicating no such pair exists
                Console.WriteLine("-1 -1");
            }
        }
        Console.WriteLine();
    }

    public static void Main(string[] args)
    {
        // Sample Input
        int N = 5;
        int[] arr = { 1, 1, 2, 1, 1 };
        int Q = 3;
        int[][] queries = new int[][] { new int[] { 0, 4 }, new int[] { 0, 1 }, new int[] { 0, 2 } };
        NearestDifferentElement(N, arr, Q, queries);
    }
}
Javascript
function GFG(N, arr, Q, queries) {
    // Array to store the position of nearest different
    // element to left
    let p = new Array(N).fill(-1);
    // Iterating through the array to the fill 'p'
    for (let i = 1; i < N; i++) {
        p[i] = p[i - 1];
        // If the current element is different from 
        // previous one
        if (arr[i] !== arr[i - 1]) {
            p[i] = i - 1;
        }
    }
    // Loop through each query
    for (let i = 0; i < Q; ++i) {
        let l = queries[i][0];
        let r = queries[i][1];
        // If there exists a pair within the range
        if (p[r] >= l) {
            console.log(p[r] + " " + r);
        } else {
            // Print "-1 -1" indicating no such pair exists
            console.log("-1 -1");
        }
    }
    console.log();
}
// Sample Input
const N = 5;
const arr = [1, 1, 2, 1, 1];
const Q = 3;
const queries = [[0, 4], [0, 1], [0, 2]];
GFG(N, arr, Q, queries);
C++14
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007

// Function to solve the problem
void solve(int N, vector<int>& arr, int Q,
        vector<pair<int, int> >& queries)
{
    // Vector to store the position of the nearest different
    // element to the left
    vector<int> p(N, -1);
    // Iterating through the array to fill 'p'
    for (int i = 1; i < N; i++) {
        // Setting the current position as the same as the
        // previous one by default
        p[i] = p[i - 1];
        // If the current element is different from the
        // previous one
        if (arr[i] != arr[i - 1]) {
            // Update 'p' to the position of the nearest
            // different element to the left
            p[i] = i - 1;
        }
    }

    // Loop through each query
    for (int i = 0; i < Q; ++i) {
        int l = queries[i].first;
        int r = queries[i].second;
        // If there exists a pair within the range
        if (p[r] >= l) {
            // Print the pair of indices having different
            // elements
            cout << p[r] << " " << r << "\n";
        }
        else {
            // Print "-1 -1" indicating no such pair exists
            cout << "-1 -1\n";
        }
    }
    cout << endl;
}

int main()
{
    int N = 5;
    vector<int> arr = { 1, 1, 2, 1, 1 };
    int Q = 3;
    vector<pair<int, int> > queries{ { 0, 4 },
                                    { 0, 1 },
                                    { 0, 2 } };
    solve(N, arr, Q, queries);
}
Python3
# Function to solve the problem
def solve(N, arr, Q, queries):
    # List to store the position of the nearest different
    # element to the left
    p = [-1] * N

    # Iterating through the array to fill 'p'
    for i in range(1, N):
        # Setting the current position as the same as the
        # previous one by default
        p[i] = p[i - 1]
        # If the current element is different from the
        # previous one
        if arr[i] != arr[i - 1]:
            # Update 'p' to the position of the nearest
            # different element to the left
            p[i] = i - 1

    # Loop through each query
    for query in queries:
        l, r = query
        # If there exists a pair within the range
        if p[r] >= l:
            # Print the pair of indices having different
            # elements
            print(p[r], r)
        else:
            # Print "-1 -1" indicating no such pair exists
            print("-1 -1")

# Main function
def main():
    # Given inputs
    N = 5
    arr = [1, 1, 2, 1, 1]
    Q = 3
    queries = [(0, 4), (0, 1), (0, 2)]
    # Calling the solve function
    solve(N, arr, Q, queries)

# Calling the main function
if __name__ == "__main__":
    main()

Output
2 4
-1 -1
1 2





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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads