![]() |
VOOZH | about |
Given an unsorted array of integers and a set of m queries, where each query consists of two integers x and y, the task is to determine the number of elements in the array that lie within the range [x, y] (inclusive) for each query.
Examples:
Input: arr = [1, 3, 4, 9, 10, 3], queries = [[1, 4], [9, 12]]
Output: 4 2
Explanation:
The numbers are: 1 3 3 4 for first query
The numbers are: 9 10 for second queryInput: arr = [5, 5, 8, 10, 12], queries = [[5, 10], [1, 3]]
Output: 4 0
Explanation:
For the query[5, 10], the numbers are:5, 5, 8, 10
For the query[1, 3], there are no numbers in the range
The idea is to traverse the entire array for each query and count the number of elements that lie within the given range
[x, y]. For every query, iterate through all elements of the array, check if the current element satisfies the conditionx ≤ element ≤ y, and increment the count if it does.
4 2
A segment tree is a binary tree where each node represents a segment of the array. The leaves of the tree represent the individual elements of the array, and the parent nodes represent the union of their children.
To answer a query [i, j], we traverse the segment tree from the root to the leaves, keeping track of the segments that contain i and j. At each node, we use the precomputed values to compute the number of elements in the segment that are less than or equal to x. We merge the values for the left and right child nodes and return the final result.
4 2
Time Complexity: O((n + m) * log n)
Auxiliary Space: O(n)
The idea is to sort the array and then use binary search to find the lower and upper bounds of the range
[x, y]for each query. The count of elements in the range is then calculated asright - left + 1.
Step by step approach:
[x, y], check if the range is outside array bounds; if so, set count to 0.x) and upper bound (last element <= y).max(0, right - left + 1) and store the result.4 2
Time Complexity:O((m + n) * log n). O(n* log n) time is used to sort the array and for m queries, (log n) time is used to find the lower and upper bound.
Auxiliary Space: O(1)