LeetCode 603: Consecutive Available Seats Solution
Master LeetCode problem 603 (Consecutive Available Seats), 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.
603. Consecutive Available Seats
Problem Explanation
Explanation:
To solve this problem, we can iterate through the reserved seats and track the available seats between each reserved seat. We can then calculate the maximum number of consecutive available seats in each row.
- Sort the reserved seats by row and seat number.
- For each row, calculate the number of consecutive available seats between reserved seats.
- Update the maximum consecutive available seats seen so far.
Time complexity: O(nlogn) where n is the number of reserved seats. Sorting the reserved seats takes O(nlogn) time. Space complexity: O(n) for storing the reserved seats.
: :
Solution Code
class Solution {
public int maxNumberOfFamilies(int n, int[][] reservedSeats) {
Arrays.sort(reservedSeats, (a, b) -> a[0] - b[0]);
int maxConsecutiveSeats = 2 * n;
HashMap<Integer, Integer> rowMap = new HashMap<>();
for (int[] seat : reservedSeats) {
int row = seat[0];
int seatNum = seat[1];
int mask = (1 << (seatNum - 1));
rowMap.put(row, rowMap.getOrDefault(row, 0) | mask);
}
for (int row : rowMap.keySet()) {
int occupied = rowMap.get(row);
int consecutiveSeats = 0;
if ((occupied & 30) == 0) {
consecutiveSeats = 2;
} else if ((occupied & 120) == 0 || (occupied & 480) == 0 || (occupied & 1920) == 0) {
consecutiveSeats = 1;
}
maxConsecutiveSeats -= consecutiveSeats;
}
return maxConsecutiveSeats;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 603 (Consecutive Available Seats)?
This page provides optimized solutions for LeetCode problem 603 (Consecutive Available Seats) 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 603 (Consecutive Available Seats)?
The time complexity for LeetCode 603 (Consecutive Available Seats) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 603 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 603 in Java, C++, or Python.