1454. Active Users

Database

Explanation:

To solve this problem, we need to find the active users among the given users based on their login and logout times. We can achieve this by iterating over the login and logout times, keeping track of the active users at each point in time. Then we can find the maximum number of active users at any given time.

  1. Create a list of events consisting of login and logout times with a flag indicating the type of event (login = 1, logout = -1).
  2. Sort the events based on the timestamp in ascending order. If timestamps are equal, prioritize logout events before login events to ensure accurate counts.
  3. Initialize activeUsers and maxActiveUsers variables to 0.
  4. Iterate over the events:
    • Update activeUsers based on the event type.
    • Update maxActiveUsers with the maximum value between activeUsers and maxActiveUsers.
  5. Return maxActiveUsers as the result.

Time Complexity: O(nlogn) - Sorting the events Space Complexity: O(n) - Storing the events list

:

class Solution {
    public int maxActiveUsers(int[][] events) {
        List<int[]> eventList = new ArrayList<>();
        
        for (int[] event : events) {
            eventList.add(new int[]{event[0], 1});
            eventList.add(new int[]{event[1], -1});
        }
        
        Collections.sort(eventList, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
        
        int activeUsers = 0;
        int maxActiveUsers = 0;
        
        for (int[] event : eventList) {
            activeUsers += event[1];
            maxActiveUsers = Math.max(maxActiveUsers, activeUsers);
        }
        
        return maxActiveUsers;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.