Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! π»π₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! π
100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney
Problem:
https://www.geeksforgeeks.org/problems/find-number-of-elements-in-range-a-b-for-each-query/1
Elements in range [a, b]
Difficulty: Medium Accuracy: 64.1%
Given an unsorted array arr[] and a 2D array queries[][] of size q, where each query is in the form of [a, b]. For each query, count how many elements in arr[] lie within the range [a, b], i.e., elements satisfying a β€ x β€ b.
Return the results for all queries as a list of integers, where each integer corresponds to the count of elements in the respective query range.
Examples:
Input: arr[] = [1, 4, 2, 8, 5], queries[][] = [[1, 4], [3, 6], [0, 10]]
Output: [3, 2, 5]
Explanation: Query [1, 4]: Elements in range β [1, 4, 2] β Count = 3
Query [3, 6]: Elements in range β [4, 5] β Count = 2
Query [0, 10]: All elements β [1, 4, 2, 8, 5] β Count = 5
Input: arr[] = [10, 20, 30, 40, 50], queries[][] = [[5, 15], [25, 45], [10, 50]]
Output: [1, 2, 5]
Explanation: Query [5, 15]: Elements in range β [10] β Count = 1
Query [25, 45]: Elements in range β [30, 40] β Count = 2
Query [10, 50]: Elements in range β [10, 20, 30, 40, 50] β Count = 5
Constraints:
1 β€ arr.size(), q β€ 105
0 β€ arr[i] β€ 106
0 β€ queries[i][0] β€ queries[i][1] β€ 106
Solution:
from bisect import bisect_left, bisect_right
class Solution:
def cntInRange(self, arr, queries):
arr.sort()
res = []
for a, b in queries:
left = bisect_left(arr, a)
right = bisect_right(arr, b)
res.append(right - left)
return res
Top comments (0)