![]() |
VOOZH | about |
You are given a 2D integer array intervals[][] of length n and integer k, where each intervals[i] = [start, end] represents a closed interval (i.e., all integers from start to end, inclusive). An integer is called Powerful if it appears in at least k intervals. Find the maximum Powerful Integer. If no such integer exists, return -1.
Examples:
Input: intervals[][] = [[1,3], [4,6], [3,4]], k = 2
Output: 4
Explanation: Integers 3 and 4 appear in 2 intervals. The maximum is 4Input: intervals[][] = [[1,4], [12,45], [3,8], [10,12]], k = 3
Output: -1
Explanation: No integer appears in at least 3 intervals
Table of Content
The idea is to use a frequency array to count how many times each integer appears across all intervals. For every interval [start, end], each number in that range is incremented in the array. After processing all intervals, the frequency array is scanned to find the maximum integer that appears at least `k` times. If no such integer exists, -1 is returned.
This brute-force approach ensures correctness but is not efficient for large ranges due to its high time and space complexity.
4
Time Complexity: O(n * m ), where m is maximum endpoint among all intervals
Auxiliary Space: O(m), where m is the maximum endpoint among all intervals
The idea is to use the sweep line or difference array technique to efficiently count how many intervals cover each integer, without iterating through every number in every interval. For each interval, we increment the count at the start point and decrement the count just after the end point. Then, we traverse the sorted map keys while maintaining a running sum (prefix sum) of the interval overlaps. If this running count is at least
k, we update the answer to the current integer (or one less if the count drops belowk). This allows us to find the maximum powerful integer in an optimized way.
4