#1890
The Latest Login in 2020
EasyDatabaseHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a single pass through the logins, we can efficiently track the latest login for each user in 2020 by utilizing a hash map. This approach reduces the time complexity significantly.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a hash map to store the latest timestamp for each user.
- 2Step 2: Iterate through each login record.
- 3Step 3: For each record, check if the timestamp is from 2020.
- 4Step 4: If it is, update the hash map with the latest timestamp for that user.
- 5Step 5: After processing all records, convert the hash map to the desired output format.
solution.py12 lines
1# Full working Python code
2import pandas as pd
3
4def latest_login(logins):
5 latest = {}
6 for index, row in logins.iterrows():
7 user_id = row['user_id']
8 time_stamp = row['time_stamp']
9 if time_stamp.year == 2020:
10 if user_id not in latest or time_stamp > latest[user_id]:
11 latest[user_id] = time_stamp
12 return pd.DataFrame(latest.items(), columns=['user_id', 'last_stamp'])ℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the logins, and the space complexity is O(n) due to the hash map storing the latest login for each user.
- 1Utilizing a hash map allows for efficient tracking of user logins.
- 2Filtering timestamps by year before processing helps reduce unnecessary comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.