Similar Problems

Similar Problems not available

Number Of Calls Between Two Persons - Leetcode Solution

Companies:

LeetCode:  Number Of Calls Between Two Persons Leetcode Solution

Difficulty: Medium

Topics: database  

Problem:

You are given a list of logs representing timestamps and the duration of calls between two persons. Each log is a string of the form "start: time duration" where start can be "A" or "B" representing the persons and time and duration are integers. You have to find the total number of calls and the total duration of calls between the two persons.

Example:

Input: logs = ["A:1:2", "B:3:3", "A:5:4", "B:7:2"] Output: [2, 7]

Explanation: There are two calls between A and B. The first call has a duration of 3+2=5 and the second call has a duration of 2. So the total duration of calls between A and B is 7.

Solution:

The solution to this problem can be obtained by iterating over each log in the list and keeping two counters: one to count the number of calls and one to sum the duration of calls. For every log, we need to check if it is a call between the two persons and if so, we need to update the counters accordingly.

To check if a log represents a call between the two persons, we can split the string into three parts using the colon as the delimiter: the first part represents the person who initiated the call ("A" or "B"), the second part represents the start time of the call and the third part represents the duration of the call. We can then use conditional statements to check if the call was between the desired two persons.

The following is the Python code to implement this algorithm:

def count_calls(logs): num_calls = 0 total_duration = 0 for log in logs: parts = log.split(":") if parts[0] == "A" and parts[1] != "B": continue if parts[0] == "B" and parts[1] != "A": continue num_calls += 1 total_duration += int(parts[2]) return [num_calls, total_duration]

The above code first initializes two variables num_calls and total_duration to zero. Then it iterates over each log in the list and splits the log into three parts using the colon as the delimiter. It then checks if the log represents a call between the two persons "A" and "B". If it is not, then it continues to the next log. Otherwise, it increments the num_calls counter by one and adds the duration of the call to total_duration.

Finally, it returns a list containing the number of calls and total duration of calls between the two persons.

The time complexity of this algorithm is O(n), where n is the length of the logs list, as we are iterating over each log once. The space complexity is also O(1), as we are only storing two integer counters.

Number Of Calls Between Two Persons Solution Code

1