VOOZH about

URL: https://www.geeksforgeeks.org/dsa/powerful-integers/

⇱ Powerful Integers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Powerful Integers

Last Updated : 5 Jul, 2025

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 4

Input: intervals[][] = [[1,4], [12,45], [3,8], [10,12]], k = 3
Output: -1
Explanation: No integer appears in at least 3 intervals

[Naive Approach] Frequency Counting with Full Range Traversal

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.


Output
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

[Expected Approach] Using Sweep Line - O(n log(n)) Time and O(n) Space

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 below k). This allows us to find the maximum powerful integer in an optimized way.


Output
4
Comment
Article Tags:
Article Tags: