Gridland Metro

  • + 0 comments
    def gridlandMetro(n, m, k, track):
        bins = defaultdict(list)
        # match each track interval to its row
        for t, s, e in track:
            bins[t].append([s, e])
        # initially we have the whole grid available
        ans = m * n
        for b in bins.values():
            # sort the intervals by start time/position
            b.sort()
            gap = 0
            l_bound, r_bound = b[0]
            for i in range(1, len(b)):
                # the intervals overlap - combine them
                if b[i][0] <= r_bound:
                    l_bound = min(l_bound, b[i][0])
                    r_bound = max(r_bound, b[i][1])
                # the intervals don't overlap - we need to remove space from the grid
                else:
                    gap += r_bound - l_bound + 1
                    l_bound, r_bound = b[i]
            # the final interval won't be handled in the loop
            gap += r_bound - l_bound + 1
            ans -= gap
            
        return ans