Skip to content
Related Articles

Related Articles

Queries to find the minimum index in given array having at least value X
  • Difficulty Level : Medium
  • Last Updated : 24 Feb, 2021

Given an array arr[] of size N and an array Q[] consisting of M integers, each representing a query, the task for each query Q[i] is to find the smallest index of an array element whose value is greater than or equal to Q[i]. If no such index exists, then print -1.

Examples:

Input: arr[] = { 1, 9 }, Q[] = { 7, 10, 0 } 
Output: 1 -1 0 
Explanation: 
The smallest index of arr[] whose value is greater than Q[0] is 1. 
No such index exists in arr[] whose value is greater than Q[1]. 
The smallest index of arr[] whose value is greater than Q[2] is 0. 
Therefore, the required output is 1 -1 0.

Input: arr[] = {2, 3, 4}, Q[] = {2, 3, 4} 
Output: 0 1 2

Approach:The problem can be solved using Binary search and Prefix Sum technque. Follow the steps below to solve the problem:



Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the smallest index
// of an array element whose value is
// less than or equal to Q[i]
void minimumIndex(vector<int>& arr,
                  vector<int>& Q)
{
 
    // Stores size of array
    int N = arr.size();
 
    // Stores coun of queries
    int M = Q.size();
 
    // Store array elements along
    // with the index
    vector<pair<int, int> > storeArrIdx;
 
    // Store smallest index of an array
    // element whose value is greater
    // than or equal to i
    vector<int> minIdx(N);
 
    // Traverse the array
    for (int i = 0; i < N; ++i) {
 
        // Insert {arr[i], i} into
        // storeArrIdx[]
        storeArrIdx.push_back({ arr[i], i });
    }
 
    // Sort the array
    sort(arr.begin(), arr.end());
 
    // Sort the storeArrIdx
    sort(storeArrIdx.begin(),
         storeArrIdx.end());
 
    // Stores index of arr[N - 1] in
    // sorted order
    minIdx[N - 1]
        = storeArrIdx[N - 1].second;
 
    // Traverse the array storeArrIdx[]
    for (int i = N - 2; i >= 0; i--) {
 
        // Update minIdx[i]
        minIdx[i] = min(minIdx[i + 1],
                        storeArrIdx[i].second);
    }
 
    // Traverse the array Q[]
    for (int i = 0; i < M; i++) {
 
        // Store the index of
        // lower_bound of Q[i]
        int pos
            = lower_bound(arr.begin(),
                          arr.end(), Q[i])
              - arr.begin();
 
        // If no index found whose value
        // greater than or equal to arr[i]
        if (pos == N) {
            cout << -1 << " ";
            continue;
        }
 
        // Print smallest index whose value
        // greater than or equal to Q[i]
        cout << minIdx[pos] << " ";
    }
}
 
// Driver Code
int main()
{
 
    vector<int> arr = { 1, 9 };
    vector<int> Q = { 7, 10, 0 };
 
    minimumIndex(arr, Q);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for above approach
import java.util.*;
import java.lang.*;
class pair
{
  int element,index;
  pair(int element, int index)
  {
    this.element = element;
    this.index = index;
  }
}
class GFG
{
 
  // Function to find the smallest index
  // of an array element whose value is
  // less than or equal to Q[i]
  static void minimumIndex(int[] arr,
                           int[] Q)
  {
 
    // Stores size of array
    int N = arr.length;
 
    // Stores coun of queries
    int M = Q.length;
 
    // Store array elements along
    // with the index
    ArrayList<pair> storeArrIdx = new ArrayList<>();
 
    // Store smallest index of an array
    // element whose value is greater
    // than or equal to i
    int[] minIdx = new int[N];
 
    // Traverse the array
    for (int i = 0; i < N; ++i)
    {
 
      // Insert {arr[i], i} into
      // storeArrIdx[]
      storeArrIdx.add(new pair(arr[i], i));
    }
 
    // Sort the array
    Arrays.sort(arr);
 
    // Sort the storeArrIdx
    Collections.sort(storeArrIdx, (a, b)->a.element-b.element);
 
    // Stores index of arr[N - 1] in
    // sorted order
    minIdx[N - 1]
      = storeArrIdx.get(N - 1).index;
 
    // Traverse the array storeArrIdx[]
    for (int i = N - 2; i >= 0; i--) {
 
      // Update minIdx[i]
      minIdx[i] =Math.min(minIdx[i + 1],
                          storeArrIdx.get(i).index);
    }
 
    // Traverse the array Q[]
    for (int i = 0; i < M; i++) {
 
      // Store the index of
      // lower_bound of Q[i]
      int pos
        = lower_bound(arr, Q[i]);
 
      // If no index found whose value
      // greater than or equal to arr[i]
      if (pos == N) {
        System.out.print("-1"+" ");
        continue;
      }
 
      // Print smallest index whose value
      // greater than or equal to Q[i]
      System.out.print(minIdx[pos]+" ");
    }
  }
  static int lower_bound(int[] arr,int element)
  {
    for(int i = 0; i < arr.length; i++)
      if(element <= arr[i])
        return i;
 
    return arr.length; 
  }
 
  // Driver function
  public static void main (String[] args)
  {
    int[] arr = { 1, 9 };
    int[] Q = { 7, 10, 0 };
 
    minimumIndex(arr, Q);
  }
}
 
// This code is contributed by offbeat

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approachf
from bisect import bisect_left
 
# Function to find the smallest index
# of an array element whose value is
# less than or equal to Q[i]
def minimumIndex(arr, Q):
 
    # Stores size of array
    N = len(arr)
 
    # Stores coun of queries
    M = len(Q)
 
    # Store array elements along
    # with the index
    storeArrIdx = []
 
    # Store smallest index of an array
    # element whose value is greater
    # than or equal to i
    minIdx = [0]*(N)
 
    # Traverse the array
    for i in range(N):
       
        # Insert {arr[i], i} into
        # storeArrIdx[]
        storeArrIdx.append([arr[i], i])
 
    # Sort the array
    arr = sorted(arr)
 
    # Sort the storeArrIdx
    storeArrIdx = sorted(storeArrIdx)
 
    # Stores index of arr[N - 1] in
    # sorted order
    minIdx[N - 1] = storeArrIdx[N - 1][1]
 
    # Traverse the array storeArrIdx[]
    for i in range(N - 2, -1, -1):
 
        # Update minIdx[i]
        minIdx[i] = min(minIdx[i + 1], storeArrIdx[i][1])
 
    # Traverse the array Q[]
    for i in range(M):
 
        # Store the index of
        # lower_bound of Q[i]
        pos = bisect_left(arr, Q[i])
 
        # If no index found whose value
        # greater than or equal to arr[i]
        if (pos == N):
            print(-1, end = " ")
            continue
 
        # Prsmallest index whose value
        # greater than or equal to Q[i]
        print(minIdx[pos], end = " ")
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 9]
    Q = [7, 10, 0]
    minimumIndex(arr, Q)
 
    # This code is contributed by mohit kumar 29

chevron_right


Output: 

1 -1 0

 

Time Complexity: O(N * log(N)) 
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :