Queries to find the minimum index in given array having at least value X
Last Updated :
21 Dec, 2022
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 Code
int main()
{
vector<int> arr = { 1, 9 };
vector<int> Q = { 7, 10, 0 };
minimumIndex(arr, Q);
return 0;
}
Java
// 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 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 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 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 Code
if __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 function
let arr=[1, 9];
let Q=[7, 10, 0 ];
minimumIndex(arr, Q);
// This code is contributed by patel2127
</script>
Time Complexity: O(N * log(N))
Auxiliary Space: O(N)
Similar Reads
How to Find the Minimum Element in a List in C++? In C++, a list is a sequence container provided by the STL library that stores data in non-contiguous memory locations efficiently. In this article, we will learn how to find the minimum element in a list in C++. Example: Input: myList = {30, 10, 20, 50, 40};Output: The minimum element in the list i
2 min read
How to Find the Smallest Number in an Array in C++? In C++, arrays are the data types that store the collection of the elements of other data types such as int, float, etc. In this article, we will learn how to find the smallest number in an array using C++. For Example,Input: myVector = {10, 3, 10, 7, 1, 5, 4} Output: Smallest Number = 1Find the Sma
2 min read
Sum of minimum elements of all possible sub-arrays of an array Given an array arr[], the task is to find the sum of the minimum elements of every possible sub-array of the array. Examples: Input: arr[] = {1, 3, 2} Output: 15 All possible sub-arrays are {1}, {2}, {3}, {1, 3}, {3, 2} and {1, 3, 2} And, the sum of all the minimum elements is 1 + 2 + 3 + 1 + 2 + 1
9 min read
Construct MEX array from the given array Given an array arr[] having N distinct positive elements, the task is to generate another array B[] such that, for every ith index in the array, arr[], B[i] is the minimum positive number missing from arr[] excluding arr[i]. Examples: Input: arr[] = {2, 1, 5, 3}Output: B[] = {2, 1, 4, 3} Explanation
8 min read
Minimum MEX from all subarrays of length K Given an array arr[] consisting of N distinct positive integers and an integer K, the task is to find the minimum MEX from all subarrays of length K. The MEX is the smallest positive integer that is not present in the array. Examples: Input: arr[] = {1, 2, 3}, K = 2Output: 1Explanation:All subarrays
7 min read
valarray min() in C++ The min() function is defined in valarray header file. This function returns the smallest value contained in the valarray. Syntax: T min() const; Returns: This function returns the minimum value in the valarray. Below programs illustrate the above function: Example 1:- CPP // C++ program to demonstr
1 min read
Queries to find the minimum index in a range [L, R] having at least value X with updates Given an array arr[] consisting of N integers and an array Queries[] consisting of Q queries of the type {X, L, R} to perform following operations: If the value of X is 1, then update the array element at Xth index to L.Otherwise, find the minimum index j in the range [L, R] such that arr[j] ? X. If
15+ min read
Queries for the minimum element in an array excluding the given index range Given an array arr[] of N integers and Q queries where each query consists of an index range [L, R]. For each query, the task is to find the minimum element in the array excluding the elements from the given index range. Examples: Input: arr[] = {3, 2, 1, 4, 5}, Q[][] = {{1, 2}, {2, 3}} Output: 3 2
15+ min read
Smallest index in the given array that satisfies the given condition Given an array arr[] of size N and an integer K, the task is to find the smallest index in the array such that: floor(arr[i] / 1) + floor(arr[i + 1] / 2) + floor(arr[i + 2] / 3) + ..... + floor(arr[n - 1] / n - i ) ? K If no such index is found then print -1. Examples: Input: arr[] = {6, 5, 4, 2}, K
6 min read