Queries to find the minimum index in given array having at least value X

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 technique. Follow the steps below to solve the problem:
- Initialize an array, say storeArrIdx[], of the form { first, second } to store the array elements along with the index.
- Sort the array storeArridx[] in increasing order of the array elements.
- Sort the array arr[] in increasing order.
- Initialize an array, say minIdx[], such that minIdx[i] store the smallest index of an array element whose value is greater than or equal to arr[i].
- Traverse the array storeArrIdx[] in reverse using variable i. For every ith index, update minIdx[i] = min(minIdx[i + 1], storeArrIdx[i].second).
- Traverse the array Q[] using variable i. For every ith query, find the index of lower_bound of Q[i] into arr[] and check if the obtained index is less than N or not. If found to be true, then print minIdx[i].
- Otherwise, print -1.
Below is the implementation of the above approach:
C++
// 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 count 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 Codeint main(){Â
    vector<int> arr = { 1, 9 };    vector<int> Q = { 7, 10, 0 };Â
    minimumIndex(arr, Q);    return 0;} |
Java
// Java program for above approachimport 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 count 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 |
Python3
# Python3 program to implement# the above approachffrom 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 count 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Â
        # Print smallest index whose value        # greater than or equal to Q[i]        print(minIdx[pos], end = " ")Â
# Driver Codeif __name__ == '__main__':Â Â Â Â arr = [1, 9]Â Â Â Â Q = [7, 10, 0]Â Â Â Â minimumIndex(arr, Q)Â
    # This code is contributed by mohit kumar 29 |
C#
// C# program for above approachÂ
using System;using System.Collections.Generic;using System.Linq;Â
class pair{Â Â public int element,index;Â Â public 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 count of queries    int M = Q.Length;Â
    // Store array elements along    // with the index    List<pair> storeArrIdx = new List<pair>();Â
    // 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    Array.Sort(arr);Â
    // Sort the storeArrIdx    storeArrIdx = storeArrIdx.OrderBy(a => a.element).ToList();Â
    // Stores index of arr[N - 1] in    // sorted order    minIdx[N - 1]      = storeArrIdx[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[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) {        Console.Write("-1"+" ");        continue;      }Â
      // Print smallest index whose value      // greater than or equal to Q[i]      Console.Write(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 phasing17 |
Javascript
<script>Â
// JavaScript program for above approachÂ
class pair{Â Â Â Â constructor(element,index)Â Â Â Â {Â Â Â Â Â Â Â Â this.element = element;Â Â Â Â Â Â Â Â this.index = index;Â Â Â Â }}Â
// Function to find the smallest index  // of an array element whose value is  // less than or equal to Q[i]function minimumIndex(arr,Q){    // Stores size of array    let N = arr.length;      // Stores count of queries    let M = Q.length;      // Store array elements along    // with the index    let storeArrIdx = [];      // Store smallest index of an array    // element whose value is greater    // than or equal to i    let minIdx = new Array(N);     for(let i=0;i<N;i++)    {        minIdx[i]=0;    }    // Traverse the array    for (let i = 0; i < N; ++i)    {        // Insert {arr[i], i} into      // storeArrIdx[]      storeArrIdx.push([arr[i], i]);    }      // Sort the array    (arr).sort(function(a,b){return a-b;});      // Sort the storeArrIdx    storeArrIdx.sort(function(a, b){ return a[0]-b[0]});      // Stores index of arr[N - 1] in    // sorted order    minIdx[N - 1]      = storeArrIdx[N - 1][1];      // Traverse the array storeArrIdx[]    for (let i = N - 2; i >= 0; i--) {        // Update minIdx[i]      minIdx[i] =Math.min(minIdx[i + 1],                          storeArrIdx[i][1]);    }      // Traverse the array Q[]    for (let i = 0; i < M; i++) {        // Store the index of      // lower_bound of Q[i]      let pos        = lower_bound(arr, Q[i]);        // If no index found whose value      // greater than or equal to arr[i]      if (pos == N) {        document.write("-1"+" ");        continue;      }        // Print smallest index whose value      // greater than or equal to Q[i]      document.write(minIdx[pos]+" ");    }}Â
function lower_bound(arr,element){Â Â Â Â for(let i = 0; i < arr.length; i++)Â Â Â Â Â Â if(element <= arr[i])Â Â Â Â Â Â Â Â return i;Â Â Â Â Â Â return arr.length; }Â
// Driver functionlet arr=[1, 9];let Q=[7, 10, 0 ];Â
minimumIndex(arr, Q);Â
Â
// This code is contributed by patel2127Â
</script> |
1 -1 0
Â
Time Complexity: O(N * log(N))Â
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



