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++
#include <bits/stdc++.h>
using namespace std;
void minimumIndex(vector< int >& arr,
vector< int >& Q)
{
int N = arr.size();
int M = Q.size();
vector<pair< int , int > > storeArrIdx;
vector< int > minIdx(N);
for ( int i = 0; i < N; ++i) {
storeArrIdx.push_back({ arr[i], i });
}
sort(arr.begin(), arr.end());
sort(storeArrIdx.begin(),
storeArrIdx.end());
minIdx[N - 1]
= storeArrIdx[N - 1].second;
for ( int i = N - 2; i >= 0; i--) {
minIdx[i] = min(minIdx[i + 1],
storeArrIdx[i].second);
}
for ( int i = 0; i < M; i++) {
int pos
= lower_bound(arr.begin(),
arr.end(), Q[i])
- arr.begin();
if (pos == N) {
cout << -1 << " " ;
continue ;
}
cout << minIdx[pos] << " " ;
}
}
int main()
{
vector< int > arr = { 1, 9 };
vector< int > Q = { 7, 10, 0 };
minimumIndex(arr, Q);
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
class pair
{
int element,index;
pair( int element, int index)
{
this .element = element;
this .index = index;
}
}
class GFG
{
static void minimumIndex( int [] arr,
int [] Q)
{
int N = arr.length;
int M = Q.length;
ArrayList<pair> storeArrIdx = new ArrayList<>();
int [] minIdx = new int [N];
for ( int i = 0 ; i < N; ++i)
{
storeArrIdx.add( new pair(arr[i], i));
}
Arrays.sort(arr);
Collections.sort(storeArrIdx, (a, b)->a.element-b.element);
minIdx[N - 1 ]
= storeArrIdx.get(N - 1 ).index;
for ( int i = N - 2 ; i >= 0 ; i--) {
minIdx[i] =Math.min(minIdx[i + 1 ],
storeArrIdx.get(i).index);
}
for ( int i = 0 ; i < M; i++) {
int pos
= lower_bound(arr, Q[i]);
if (pos == N) {
System.out.print( "-1" + " " );
continue ;
}
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;
}
public static void main (String[] args)
{
int [] arr = { 1 , 9 };
int [] Q = { 7 , 10 , 0 };
minimumIndex(arr, Q);
}
}
|
Python3
from bisect import bisect_left
def minimumIndex(arr, Q):
N = len (arr)
M = len (Q)
storeArrIdx = []
minIdx = [ 0 ] * (N)
for i in range (N):
storeArrIdx.append([arr[i], i])
arr = sorted (arr)
storeArrIdx = sorted (storeArrIdx)
minIdx[N - 1 ] = storeArrIdx[N - 1 ][ 1 ]
for i in range (N - 2 , - 1 , - 1 ):
minIdx[i] = min (minIdx[i + 1 ], storeArrIdx[i][ 1 ])
for i in range (M):
pos = bisect_left(arr, Q[i])
if (pos = = N):
print ( - 1 , end = " " )
continue
print (minIdx[pos], end = " " )
if __name__ = = '__main__' :
arr = [ 1 , 9 ]
Q = [ 7 , 10 , 0 ]
minimumIndex(arr, Q)
|
C#
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
{
static void minimumIndex( int [] arr,
int [] Q)
{
int N = arr.Length;
int M = Q.Length;
List<pair> storeArrIdx = new List<pair>();
int [] minIdx = new int [N];
for ( int i = 0; i < N; ++i)
{
storeArrIdx.Add( new pair(arr[i], i));
}
Array.Sort(arr);
storeArrIdx = storeArrIdx.OrderBy(a => a.element).ToList();
minIdx[N - 1]
= storeArrIdx[N - 1].index;
for ( int i = N - 2; i >= 0; i--) {
minIdx[i] =Math.Min(minIdx[i + 1],
storeArrIdx[i].index);
}
for ( int i = 0; i < M; i++) {
int pos
= lower_bound(arr, Q[i]);
if (pos == N) {
Console.Write( "-1" + " " );
continue ;
}
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;
}
public static void Main ( string [] args)
{
int [] arr = { 1, 9 };
int [] Q = { 7, 10, 0 };
minimumIndex(arr, Q);
}
}
|
Javascript
<script>
class pair
{
constructor(element,index)
{
this .element = element;
this .index = index;
}
}
function minimumIndex(arr,Q)
{
let N = arr.length;
let M = Q.length;
let storeArrIdx = [];
let minIdx = new Array(N);
for (let i=0;i<N;i++)
{
minIdx[i]=0;
}
for (let i = 0; i < N; ++i)
{
storeArrIdx.push([arr[i], i]);
}
(arr).sort( function (a,b){ return a-b;});
storeArrIdx.sort( function (a, b){ return a[0]-b[0]});
minIdx[N - 1]
= storeArrIdx[N - 1][1];
for (let i = N - 2; i >= 0; i--) {
minIdx[i] =Math.min(minIdx[i + 1],
storeArrIdx[i][1]);
}
for (let i = 0; i < M; i++) {
let pos
= lower_bound(arr, Q[i]);
if (pos == N) {
document.write( "-1" + " " );
continue ;
}
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;
}
let arr=[1, 9];
let Q=[7, 10, 0 ];
minimumIndex(arr, Q);
</script>
|
Time Complexity: O(N * log(N))
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
21 Dec, 2022
Like Article
Save Article