LeetCode 1142: User Activity for the Past 30 Days II Solution
Master LeetCode problem 1142 (User Activity for the Past 30 Days II), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1142. User Activity for the Past 30 Days II
Problem Explanation
Explanation
To solve this problem, we need to calculate the average number of sessions per user for the past 30 days. We are given a list of user sessions with timestamps and userIds. We need to find the total number of sessions per user and then calculate the average.
The steps to solve this problem are as follows:
- Create a HashMap to store the userId as the key and the total number of sessions as the value.
- Iterate through the list of user sessions and update the total number of sessions for each user.
- Calculate the sum of all sessions and divide it by the number of unique users to get the average sessions per user.
The time complexity of this solution is O(n) where n is the number of user sessions, and the space complexity is O(n) to store the total sessions per user.
Solution Code
class Solution {
public double averageSessions(int[][] sessions) {
Map<Integer, Integer> sessionCounts = new HashMap<>();
int totalSessions = 0;
for (int[] session : sessions) {
int userId = session[0];
sessionCounts.put(userId, sessionCounts.getOrDefault(userId, 0) + 1);
totalSessions++;
}
return (double) totalSessions / sessionCounts.size();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1142 (User Activity for the Past 30 Days II)?
This page provides optimized solutions for LeetCode problem 1142 (User Activity for the Past 30 Days II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1142 (User Activity for the Past 30 Days II)?
The time complexity for LeetCode 1142 (User Activity for the Past 30 Days II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1142 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1142 in Java, C++, or Python.