Similar Problems
Similar Problems not available
User Activity For The Past 30 Days Ii - Leetcode Solution
Companies:
LeetCode: User Activity For The Past 30 Days Ii Leetcode Solution
Difficulty: Easy
Topics: database
Problem Statement
You are given activity logs for a website for the past 30 days. The logs are represented as an array of strings where each string represents a user's activity on a given day in the following format: "YYYY-MM-DD action", where action can be either "sign_in" or "sign_out".
Write a function to find the number of unique users who have signed in to the website on each day for the past 30 days, sorted in ascending order of the date.
Solution
To solve this problem, we need to iterate over the given activity logs and keep track of the unique users who have signed in to the website on each day for the past 30 days. We can use a hash map to store this information, with the keys being the dates and the values being sets of user IDs.
Algorithm:
- Initialize an empty hash map to store the active users.
- Iterate over the activity logs, and for each log: a. Extract the date and user ID from the log. b. If the action is "sign_in", add the user ID to the set of active users for that date in the hash map. If the action is "sign_out", remove the user ID from the set.
- Sort the hash map by dates in ascending order, and for each date: a. Get the size of the set of active users for that date. b. Add the size to a list of results.
- Return the list of results.
Code:
Here is the Python code for the solution:
def user_activity(activity_logs): active_users = {} for log in activity_logs: date, user_id, action = log.split() if date not in active_users: active_users[date] = set() if action == "sign_in": active_users[date].add(user_id) else: active_users[date].discard(user_id) results = [] for date, users in sorted(active_users.items()): results.append(len(users)) return results
Time Complexity
The time complexity of this solution is O(nlogn), where n is the number of log entries. The sorting step in the final loop takes O(nlogn) time, and the other steps take linear time.
Space Complexity:
The space complexity of this solution is O(n), where n is the number of log entries. We store the active users in a hash map, which can have at most 30 entries (one for each day), and each entry can have at most n/30 users. However, in the worst case, all users appear on all days, which gives us a total of n space complexity.
User Activity For The Past 30 Days Ii Solution Code
1