31. Powerful Integer
β GFG solution to the Powerful Integer problem: find maximum integer appearing in at least k intervals using sweep line technique with difference array. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given a 2D integer array intervals[][] of length n, where each intervals[i] = [start, end] represents a closed interval (i.e., all integers from start to end, inclusive). You are also given an integer k. An integer is called Powerful if it appears in at least k intervals. Find the maximum Powerful Integer.
Note: If no integer occurs at least k times return -1.
π Examples
Example 1
Input: n = 3, intervals[][] = [[1, 3], [4, 6], [3, 4]], k = 2
Output: 4
Explanation: Integers 3 and 4 appear in 2 intervals. The maximum is 4.Example 2
Input: n = 4, intervals[][] = [[1, 4], [12, 45], [3, 8], [10, 12]], k = 3
Output: -1
Explanation: No integer appears in at least 3 intervals.Example 3
π Constraints
$1 \le n \le 10^5$
$1 \le \text{intervals}[i][0] \le \text{intervals}[i][1] \le 10^9$
$1 \le k \le 10^5$
β
My Approach
The optimal approach uses the Sweep Line technique with Difference Array to efficiently track interval overlaps and find the maximum powerful integer:
Sweep Line + Difference Array
Create Events:
For each interval
[start, end], create two events:+1at positionstart(interval begins)-1at positionend + 1(interval ends)
Process Events in Order:
Use a map to store events and process them in sorted order of positions.
Maintain a running count of active intervals at each position.
Track Powerful Integers:
When processing
+1events, increment count and check if count β₯ k.When processing
-1events, check if previous position had count β₯ k before decrementing.Keep track of the maximum position where count β₯ k.
Handle Edge Cases:
If no position satisfies count β₯ k, return -1.
Properly handle interval boundaries using
end + 1for closing events.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n log n), where n is the number of intervals. We create 2n events and process them in sorted order using a map, which takes O(n log n) time for sorting and O(log n) for each map operation.
Expected Auxiliary Space Complexity: O(n), as we store at most 2n events in the map for processing the sweep line algorithm.
π§βπ» Code (C++)
β Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated