Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
📋
Problem
Imagine you are managing a carpool service where multiple groups of passengers get on and off at different locations along a route. You need to ensure the car's capacity is never exceeded at any point.
You are driving a vehicle that can hold a fixed number of passengers (capacity). Given a list of trips, where each trip is represented as [num_passengers, start_location, end_location], determine if it is possible to pick up and drop off all passengers for all the given trips without exceeding the vehicle's capacity at any point. The vehicle only moves in one direction along a route from location 0 to location 1000.
Edge cases: Single trip with passengers equal to capacity → should return trueTrips with no overlapping intervals → should return trueTrips where passengers get off exactly when others get on → should return true
</>
IDE
def carPooling(trips: list[list[int]], capacity: int) -> bool:public boolean carPooling(int[][] trips, int capacity)bool carPooling(vector<vector<int>>& trips, int capacity)function carPooling(trips, capacity)
def carPooling(trips, capacity):
# Write your solution here
pass
class Solution {
public boolean carPooling(int[][] trips, int capacity) {
// Write your solution here
return false;
}
}
#include <vector>
using namespace std;
bool carPooling(vector<vector<int>>& trips, int capacity) {
// Write your solution here
return false;
}
function carPooling(trips, capacity) {
// Write your solution here
}
Coming soon
0/9
Common Bugs to Avoid
Wrong: trueIgnoring overlapping intervals and summing passengers incorrectly, causing capacity overflow to be missed.✅ Implement event sorting and sweep line to accumulate passenger counts at each location and compare with capacity.
Wrong: falseOff-by-one error in interval handling, counting passengers at end location incorrectly.✅ Process drop-offs before pickups at the same location to avoid overcounting passengers.
Wrong: trueTreating trips as unbounded or reusing passengers multiple times (0/1 vs unbounded confusion).✅ Count passengers only once per trip interval; do not reuse or multiply counts.
Wrong: falseIncorrect handling of empty trips input, returning false or error instead of true.✅ Return true immediately if trips list is empty.
Wrong: TLEBrute force simulation of all locations for large inputs causing time limit exceeded.✅ Use event sorting and sweep line approach with O(n log n) complexity.
✓
Test Cases
Try testing your solution on empty and minimal inputs to ensure base cases are handled.
Consider tricky cases where trips overlap or passengers get off and on at the same location.
Focus on algorithmic complexity; brute force will time out on large inputs.
t1_01basic
Input{"trips":[[2,1,5],[3,3,7]],"capacity":4}
Expectedfalse
⏱ Performance - must finish in 2000ms
Between locations 3 and 5, total passengers would be 2 + 3 = 5, which exceeds capacity 4.
💡 Consider tracking passenger count changes at each location.
💡 Use a sweep line or event processing to accumulate passengers on and off.
💡 Check if at any point the cumulative passengers exceed capacity.
Why it failed: Returned true despite exceeding capacity between locations 3 and 5. Fix by correctly accumulating passengers and checking capacity at each location.
✓ Correctly detects capacity exceeded in overlapping intervals.
t1_02basic
Input{"trips":[[2,1,5],[3,3,7]],"capacity":5}
Expectedtrue
⏱ Performance - must finish in 2000ms
Capacity 5 is sufficient for overlapping passengers 2 + 3 = 5 between locations 3 and 5.
💡 Track passenger changes at start and end locations.
💡 Sum passengers incrementally to verify capacity constraints.
💡 Ensure no location exceeds capacity after processing all events.
Why it failed: Returned false even though capacity is sufficient. Fix by correctly summing passengers and comparing with capacity.
✓ Correctly allows trips when capacity is sufficient.
t2_01edge
Input{"trips":[],"capacity":10}
Expectedtrue
⏱ Performance - must finish in 2000ms
No trips means no passengers, so capacity is never exceeded.
💡 Check behavior when trips list is empty.
💡 Ensure function returns true when no passengers are present.
💡 Handle empty input gracefully without errors.
Why it failed: Returned false or error on empty trips input. Fix by returning true when no trips exist.
✓ Correctly handles empty trips input.
t2_02edge
Input{"trips":[[5,0,10]],"capacity":5}
Expectedtrue
⏱ Performance - must finish in 2000ms
Single trip with passengers equal to capacity should return true.
💡 Test single trip exactly matching capacity.
💡 Verify no off-by-one errors in interval handling.
💡 Ensure capacity comparison uses <= not <.
Why it failed: Returned false for single trip equal to capacity. Fix by using <= comparison when checking capacity.
✓ Correctly handles single trip equal to capacity.
t2_03edge
Input{"trips":[[2,1,3],[3,3,5]],"capacity":3}
Expectedtrue
⏱ Performance - must finish in 2000ms
Passengers get off exactly when others get on; capacity never exceeded.
💡 Check handling of passengers getting off and on at the same location.
💡 Process drop-offs before pickups at the same location.
Greedy approach picking earliest trips first fails; total passengers exceed capacity between locations 4 and 5.
💡 Beware of greedy approaches that pick trips without considering overlaps.
💡 Use event sorting and sweep line to track cumulative passengers.
💡 Check all intervals cumulatively rather than individually.
Why it failed: Returned true due to greedy selection ignoring overlapping passenger sums. Fix by using sweep line to sum all passengers at each location.
✓ Correctly detects capacity overflow in overlapping intervals.
n=2 trips with max passengers and max location range; O(n log n) sweep line approach must complete within 2s.
💡 Use event sorting and sweep line for O(n log n) complexity.
💡 Avoid simulating each location individually (O(n*L)).
💡 Process start and end events efficiently to track capacity.
Why it failed: TLE due to brute force simulation of all locations. Fix by implementing event sorting and sweep line approach with O(n log n) complexity.
✓ Efficient O(n log n) approach confirmed to run within time limits.
Practice
(1/5)
1. Consider the following Python code that determines if a person can attend all meetings given a list of intervals. What is the return value when the input is [[7,10],[2,4]]?
from typing import List
def can_attend_meetings(intervals: List[List[int]]) -> bool:
intervals.sort(key=lambda x: x[0])
end = float('-inf')
for interval in intervals:
if interval[0] < end:
return False
end = interval[1]
return True
print(can_attend_meetings([[7,10],[2,4]]))
easy
A. None
B. False
C. Raises an exception
D. True
Solution
Step 1: Sort intervals by start time
Input [[7,10],[2,4]] becomes [[2,4],[7,10]].
Step 2: Iterate and check overlaps
Initialize end = -inf. First interval start=2 > -inf, update end=4. Second interval start=7 > 4, update end=10. No overlaps found, return True.
Final Answer:
Option D -> Option D
Quick Check:
Intervals sorted and no overlaps detected [OK]
Hint: Sort then check if current start < previous end [OK]
Common Mistakes:
Confusing return value due to unsorted intervals
2. Consider the following Python code that merges intervals in-place after sorting. Given the input intervals = [[1,4],[2,5],[7,9]], what is the returned list after the function completes?
easy
A. [[1,5],[7,9]]
B. [[1,4],[2,5],[7,9]]
C. [[1,5],[2,5],[7,9]]
D. [[1,4],[7,9]]
Solution
Step 1: Sort intervals by start time.
Input is already sorted: [[1,4],[2,5],[7,9]].
Step 2: Merge intervals in one pass.
Compare [2,5] with [1,4]: overlap since 2 <= 4, merge to [1,5]. Then compare [7,9] with [1,5]: no overlap, move index forward and assign [7,9]. Final intervals: [[1,5],[7,9]].
Hint: Check if current start ≤ last merged end to merge [OK]
Common Mistakes:
Returning original intervals without merging
Off-by-one slicing errors
3. What is the time complexity of the addNum operation in the optimal balanced tree approach for maintaining disjoint intervals, assuming there are n intervals stored?
medium
A. O(n) because intervals need to be scanned linearly for merging
B. O(log n) due to binary search and limited merging operations
C. O(n log n) because each insertion requires sorting intervals
D. O(1) since insertion is always at the end or start
Solution
Step 1: Identify main operations in addNum
addNum uses binary search (bisect_left) to find insertion index in O(log n).
Step 2: Analyze merging cost
Merging involves at most constant number of interval merges (left, right, or both), so O(1) extra work.
Final Answer:
Option B -> Option B
Quick Check:
Binary search dominates, merges are constant time [OK]
4. What is the time complexity of the optimal algorithm that determines if a person can attend all meetings given n intervals, where the algorithm sorts intervals by start time and then checks for overlaps in a single pass?
medium
A. O(n) because we only scan the intervals once after sorting
B. O(n^2) because each interval is compared with all others for overlaps
C. O(n log n) due to sorting the intervals by start time
D. O(log n) because sorting can be done in logarithmic time
Solution
Step 1: Identify sorting cost
Sorting n intervals by start time takes O(n log n) time.
Step 2: Identify overlap check cost
Single pass to check overlaps is O(n), which is dominated by sorting.
5. The following code attempts to find the maximum number of non-overlapping intervals. Which line contains a subtle bug that can cause incorrect results on some inputs?
def max_non_overlapping_intervals(intervals):
intervals.sort(key=lambda x: x[0])
removals = 0
last_end = intervals[0][1]
for i in range(1, len(intervals)):
if intervals[i][0] <= last_end:
removals += 1
last_end = min(last_end, intervals[i][1])
else:
last_end = intervals[i][1]
return len(intervals) - removals
medium
A. Line 9: Updating last_end to intervals[i][1] when no overlap
B. Line 2: Sorting intervals by start time instead of end time
C. Line 7: Updating last_end to min(last_end, intervals[i][1]) inside overlap condition
D. Line 5: Using '<=' instead of '<' in the overlap condition
Solution
Step 1: Understand overlap condition
Intervals that start exactly at last_end do not overlap and should be allowed.
Step 2: Identify incorrect operator
Using '<=' causes intervals starting exactly at last_end to be considered overlapping, reducing count incorrectly.
Final Answer:
Option D -> Option D
Quick Check:
Change '<=' to '<' fixes the bug [OK]
Hint: Overlap check must use strict less than, not less or equal [OK]
Common Mistakes:
Confusing inclusive vs exclusive overlap conditions