Untitled

mail@pastecode.io avatar
unknown
python
7 months ago
748 B
42
Indexable
Never
def count_active_caches_optimized(cache, time):
    events = []
    
    for start, ttl in cache:
        events.append((start, 1))
        events.append((start + ttl, -1)) 

    events.sort()

    active_caches = []
    active_count = 0
    for time_point, change in events:
        active_count += change
        active_caches.append((time_point, active_count))

    def binary_search(time):
        left, right = 0, len(active_caches) - 1
        while left <= right:
            mid = left + (right - left) // 2
            if active_caches[mid][0] <= time:
                left = mid + 1
            else:
                right = mid - 1
        return active_caches[right][1] if right >= 0 else 0

    return [binary_search(t) for t in time]
Leave a Comment