Twitter | Phone screen | k login requests
Anonymous User
1851

Got this question in a phone screen. I could only come up with a O(2n) soln. Was my time complexity + soln correct? I didn't get any feedback at the time

#   given a list of login requests [timestamp, IP] sorted by timestamp in ascending order, detect all IPs with more than k login requests in the window time
from collections import deque
def lc(requests, k, window):
    dicts = {}
    res = set()

    for ts, user_id in requests:
        if user_id in dicts:
            dicts[user_id].append(ts)
        else:
            dicts[user_id] = deque([ts])

        while dicts[user_id] and ts - dicts[user_id][0] > window:
            dicts[user_id].popleft()

        if len(dicts[user_id]) > k:
            res.add(user_id)

    return list(res)

t = [[0, 1], [0, 2], [0, 5], [1, 2], [1, 1], [1, 1], [1, 1], [1, 1], [1, 1], [2, 1], [3, 1], [4, 1]]
lc(t, 5, 3)
Comments (5)