LeetCode 1454: Active Users Solution

Master LeetCode problem 1454 (Active Users), a medium 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.

1454. Active Users

Medium

Problem Explanation

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

:

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1454 (Active Users)?

This page provides optimized solutions for LeetCode problem 1454 (Active Users) 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 1454 (Active Users)?

The time complexity for LeetCode 1454 (Active Users) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1454 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1454 in Java, C++, or Python.

Back to LeetCode Solutions