Similar Problems

Similar Problems not available

Number Of Recent Calls - Leetcode Solution

Companies:

LeetCode:  Number Of Recent Calls Leetcode Solution

Difficulty: Easy

Topics: design  

Problem Statement:

You are given a list of recent calls made. Each call is represented as a string of length 14 containing the phone number that was called and the timestamp in the format "hh:mm:ss". You need to count the number of calls made in the last 5 minutes.

Solution:

To solve this problem, we can make use of the sliding window technique. We can maintain a window of size 5 minutes and slide this window over the list of calls. For every call that falls within this window, we can increment our count.

We can start by converting the timestamps into seconds. We can then maintain two pointers, i and j, that will point to the start and end of our window. We will initialize both pointers to 0 to start with.

We can then use a while loop to slide the window over the list of calls. We will move j forward by 1 and check if the difference between the timestamp at j and the timestamp at i is greater than 300 seconds (5 minutes). If it is, we will move i forward by 1 and decrement our count accordingly. If the difference is less than or equal to 300 seconds, we will increment our count.

We will continue to do this until j reaches the end of the list of calls. At this point, we will return our count.

Implementation:

Here's the Python code for the solution:

def numberOfRecentCalls(calls):
    calls = [int(c[-5:-3])*3600 + int(c[-2:])*60 + int(c[-4:-2]) for c in calls]
    i, j, count = 0, 0, 0
    while j < len(calls):
        if calls[j] - calls[i] <= 300:
            count += 1
        else:
            while calls[j] - calls[i] > 300:
                i += 1
                count -= 1
        j += 1
    return count

The time complexity of this solution is O(n), where n is the number of calls. The space complexity is also O(n), as we are storing the integer representations of the timestamps in a list.

Number Of Recent Calls Solution Code

1