Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi.
You can attend an event i at any day d where startDayi <= d <= endDayi. You can only attend one event at any time d.
Return the maximum number of events you can attend.
Example 1:
Input: events = [[1,2],[2,3],[3,4]] Output: 3 Explanation: You can attend all the three events. One way to attend them all is as shown. Attend the first event on day 1. Attend the second event on day 2. Attend the third event on day 3.
Example 2:
Input: events= [[1,2],[2,3],[3,4],[1,2]] Output: 4
Constraints:
1 <= events.length <= 105events[i].length == 21 <= startDayi <= endDayi <= 105Problem summary: You are given an array of events where events[i] = [startDayi, endDayi]. Every event i starts at startDayi and ends at endDayi. You can attend an event i at any day d where startDayi <= d <= endDayi. You can only attend one event at any time d. Return the maximum number of events you can attend.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Greedy
[[1,2],[2,3],[3,4]]
[[1,2],[2,3],[3,4],[1,2]]
maximum-number-of-events-that-can-be-attended-ii)maximum-earnings-from-taxi)meeting-rooms-iii)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1353: Maximum Number of Events That Can Be Attended
class Solution {
public int maxEvents(int[][] events) {
Map<Integer, List<Integer>> g = new HashMap<>();
int l = Integer.MAX_VALUE, r = 0;
for (int[] event : events) {
int s = event[0], e = event[1];
g.computeIfAbsent(s, k -> new ArrayList<>()).add(e);
l = Math.min(l, s);
r = Math.max(r, e);
}
PriorityQueue<Integer> pq = new PriorityQueue<>();
int ans = 0;
for (int s = l; s <= r; s++) {
while (!pq.isEmpty() && pq.peek() < s) {
pq.poll();
}
for (int e : g.getOrDefault(s, List.of())) {
pq.offer(e);
}
if (!pq.isEmpty()) {
pq.poll();
ans++;
}
}
return ans;
}
}
// Accepted solution for LeetCode #1353: Maximum Number of Events That Can Be Attended
func maxEvents(events [][]int) (ans int) {
g := map[int][]int{}
l, r := math.MaxInt32, 0
for _, event := range events {
s, e := event[0], event[1]
g[s] = append(g[s], e)
l = min(l, s)
r = max(r, e)
}
pq := &hp{}
heap.Init(pq)
for s := l; s <= r; s++ {
for pq.Len() > 0 && pq.IntSlice[0] < s {
heap.Pop(pq)
}
for _, e := range g[s] {
heap.Push(pq, e)
}
if pq.Len() > 0 {
heap.Pop(pq)
ans++
}
}
return
}
type hp struct{ sort.IntSlice }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
n := len(h.IntSlice)
v := h.IntSlice[n-1]
h.IntSlice = h.IntSlice[:n-1]
return v
}
func (h *hp) Less(i, j int) bool { return h.IntSlice[i] < h.IntSlice[j] }
# Accepted solution for LeetCode #1353: Maximum Number of Events That Can Be Attended
class Solution:
def maxEvents(self, events: List[List[int]]) -> int:
g = defaultdict(list)
l, r = inf, 0
for s, e in events:
g[s].append(e)
l = min(l, s)
r = max(r, e)
pq = []
ans = 0
for s in range(l, r + 1):
while pq and pq[0] < s:
heappop(pq)
for e in g[s]:
heappush(pq, e)
if pq:
heappop(pq)
ans += 1
return ans
// Accepted solution for LeetCode #1353: Maximum Number of Events That Can Be Attended
use std::cmp::Reverse;
use std::collections::{BinaryHeap, HashMap};
impl Solution {
pub fn max_events(events: Vec<Vec<i32>>) -> i32 {
let mut g: HashMap<i32, Vec<i32>> = HashMap::new();
let mut l = i32::MAX;
let mut r = 0;
for event in events {
let s = event[0];
let e = event[1];
g.entry(s).or_default().push(e);
l = l.min(s);
r = r.max(e);
}
let mut pq = BinaryHeap::new();
let mut ans = 0;
for s in l..=r {
while let Some(&Reverse(top)) = pq.peek() {
if top < s {
pq.pop();
} else {
break;
}
}
if let Some(ends) = g.get(&s) {
for &e in ends {
pq.push(Reverse(e));
}
}
if pq.pop().is_some() {
ans += 1;
}
}
ans
}
}
// Accepted solution for LeetCode #1353: Maximum Number of Events That Can Be Attended
function maxEvents(events: number[][]): number {
const g: Map<number, number[]> = new Map();
let l = Infinity,
r = 0;
for (const [s, e] of events) {
if (!g.has(s)) g.set(s, []);
g.get(s)!.push(e);
l = Math.min(l, s);
r = Math.max(r, e);
}
const pq = new MinPriorityQueue<number>();
let ans = 0;
for (let s = l; s <= r; s++) {
while (!pq.isEmpty() && pq.front() < s) {
pq.dequeue();
}
for (const e of g.get(s) || []) {
pq.enqueue(e);
}
if (!pq.isEmpty()) {
pq.dequeue();
ans++;
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.