Given an array of integers arr[] of length N and Q total number of queries. In each query given an integer X. For each query output first integer from the array, which is less than or equal to X. In other words, find the largest integer which is less than or equal to X.
If the answer of the ith query is Yi, then Yi should be present in arr[] and the largest integer from array such that Yi<=Xi.
Else if such integer does not exist output "NO".
Read Also:All Sorting Algorithm In python
Example:
Input:
Output:
Explanation:
Naive Approach:
- In each query Travers, the whole array arr[] and find the largest integer which is less than or equal to X.
- If an answer exists output that else outputs "NO".
Time Complexity: O(N*Q)
Auxiliary Space: O(N+Q)
Optimal Approach:
The lower bound C++ function returns an iterator pointing to an element greater than or equal to a given element.
proceed below steps for Q queries.
Step:
- To use the lower bound function for less than purpose multiply each integer of arr[] multiply by -1. (store opposite values in arr[])
- Sort the array in ascending order.
- Use lower bound function on arr[] with -X argument.
- If function returns arr.end() iterator. output "NO".
- Else output integer with the opposite sign which is pointed by this iterator.
(also we can use the upper bound function for only less than X purpose.)
Here, the Time Complexity of the Lower_bound function on the sorted array is O(logN).
Implementation.cpp
Time Complexity: O(N+Q*logN)
Auxiliary Space: O(N+Q)
Read Also: All Sorting Algorithm In C++
Read Also:Merge Sort Algorithm
0 Comments
If you have any doubt let me know.