Lintcode. Number of Airplanes in the Sky

Given an interval list which are flying and landing time of the flight. How many airplanes are on the sky at most?

Notice

If landing and flying happens at the same time, we consider landing should happen at first.

 

Java
Time complexity: O(N log N)
Space complexity: O(N)

class Solution {
    /**
     * @param intervals: An interval array
     * @return: Count of airplanes are in the sky.
     */
    public int countOfAirplanes(List<Interval> airplanes) { 
        // write your code here
        if (airplanes == null || airplanes.size() == 0){
            return 0;
        }
        
        int n = airplanes.size();
        int[] start = new int[n];
        int[] land = new int[n];
        
        for (int i = 0; i < n; ++i){
            Interval t = airplanes.get(i);
            start[i] = t.start;
            land[i] = t.end;
        }
        
        Arrays.sort(start);
        Arrays.sort(land);
        
        int maxPlanes = Integer.MIN_VALUE;
        int currPlanes = 0;
        
        int startPtr = 0;
        int landPtr = 0;
        
        while (startPtr < n){
            if (land[landPtr] <= start[startPtr]){
                currPlanes -= 1;
                ++landPtr;
            } else if (start[startPtr] < land[landPtr]){
                currPlanes += 1;
                ++startPtr;    
            } 
            maxPlanes = Math.max(maxPlanes, currPlanes);
        }
        
        return maxPlanes;
        
        
    }
}

Python
Time complexity: O(N log N)
Space complexity: O(N)

class Solution:
    # @param airplanes, a list of Interval
    # @return an integer
    def countOfAirplanes(self, airplanes):
        # write your code here
        if not len(airplanes):
            return 0;
        
        #creates copy of iterable, one may use [].sort() instead   
        start = sorted([plane.start for plane in airplanes])
        land = sorted([plane.end for plane in airplanes])
        
        maxAirplanes = 0
        currAirplanes = 0
        sIdx = 0
        lIdx = 0
        
        while sIdx < len(airplanes):
            if start[sIdx] < land[lIdx]:
                currAirplanes += 1
                sIdx += 1
            else:
                currAirplanes -= 1
                lIdx += 1
                
            maxAirplanes = max(maxAirplanes, currAirplanes)
        
            
        return maxAirplanes;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s