LeetCode 1126: Active Businesses Solution
Master LeetCode problem 1126 (Active Businesses), 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.
1126. Active Businesses
Problem Explanation
Explanation:
Given a list of closed intervals businesses, find the number of active businesses at each time point. The active businesses are defined as the number of intervals that contain the current time point.
To solve this problem, we can use a sweep line algorithm. We iterate through all the time points, maintaining a count of active businesses using a map. We update the count of active businesses based on the start and end times of each interval.
- Initialize a map to store the count of active businesses at each time point.
- Iterate through all intervals in the input list:
- Increment the count in the map at the start time of the interval.
- Decrement the count in the map at the end time of the interval.
- Iterate through the map and update the count of active businesses for each time point based on the accumulated sum.
- Return the list of active businesses at each time point.
Time complexity: O(n log n) where n is the number of intervals. The sorting of intervals takes O(n log n) time complexity. Space complexity: O(n) for the map to store active businesses.
:
Solution Code
class Solution {
public List<Integer> activeBusinesses(int[][] businesses) {
List<Integer> result = new ArrayList<>();
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int[] business : businesses) {
map.put(business[0], map.getOrDefault(business[0], 0) + 1);
map.put(business[1], map.getOrDefault(business[1], 0) - 1);
}
int activeCount = 0;
for (int count : map.values()) {
activeCount += count;
result.add(activeCount);
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1126 (Active Businesses)?
This page provides optimized solutions for LeetCode problem 1126 (Active Businesses) 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 1126 (Active Businesses)?
The time complexity for LeetCode 1126 (Active Businesses) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1126 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1126 in Java, C++, or Python.