Similar Problems

Similar Problems not available

First And Last Call On The Same Day - Leetcode Solution

Companies:

LeetCode:  First And Last Call On The Same Day Leetcode Solution

Difficulty: Hard

Topics: database  

Problem statement: Given a list of user session logs, find the users who made their first and last call on the same day.

Solution:

To solve this problem, we need to perform the following steps:

  1. Parse the input user session logs and convert them into a dictionary format. Each dictionary contains information about a single session including the user_id, start_time, end_time and date.

  2. Create two dictionaries, ‘first_call’ and ‘last_call’ to keep track of the first and last call of each user. The keys of these dictionaries will be the user_ids and the values will be a list containing the start_time and the date of the call.

  3. Iterate through the session logs again and check if the user made their first and last call on the same day. For this, we can compare the dates of the first and last call for each user.

  4. If the user made their first and last call on the same day, then append their user_id to the list of users.

  5. Finally, return the list of users who made their first and last call on the same day.

Here is the Python code for the solution:

def first_and_last_call_on_same_day(session_logs):
    # Step 1
    sessions = {}
    for log in session_logs:
        user_id, start_time, end_time = log.split(',')
        date, start_hour = start_time.split()
        _, end_hour = end_time.split()
        if user_id not in sessions:
            sessions[user_id] = []
        sessions[user_id].append({'date': date, 'start': start_hour, 'end': end_hour})

    # Step 2
    first_call, last_call = {}, {}
    for user_id in sessions:
        sorted_sessions = sorted(sessions[user_id], key=lambda x: x['start'])
        first_call[user_id] = [sorted_sessions[0]['start'], sorted_sessions[0]['date']]
        last_call[user_id] = [sorted_sessions[-1]['end'], sorted_sessions[-1]['date']]

    # Step 3
    users = []
    for user_id in first_call:
        if first_call[user_id][1] == last_call[user_id][1]:
            users.append(user_id)

    # Step 4
    return users

Complexity: The time complexity of this algorithm is O(NlogN), where N is the number of sessions. This is because we have to sort the sessions for each user in Step 2. The space complexity is also O(N), to store the session and call dictionaries.

First And Last Call On The Same Day Solution Code

1