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 n tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the ith task will be available to process at enqueueTimei and will take processingTimei to finish processing.
You have a single-threaded CPU that can process at most one task at a time and will act in the following way:
Return the order in which the CPU will process the tasks.
Example 1:
Input: tasks = [[1,2],[2,4],[3,2],[4,1]]
Output: [0,2,3,1]
Explanation: The events go as follows:
- At time = 1, task 0 is available to process. Available tasks = {0}.
- Also at time = 1, the idle CPU starts processing task 0. Available tasks = {}.
- At time = 2, task 1 is available to process. Available tasks = {1}.
- At time = 3, task 2 is available to process. Available tasks = {1, 2}.
- Also at time = 3, the CPU finishes task 0 and starts processing task 2 as it is the shortest. Available tasks = {1}.
- At time = 4, task 3 is available to process. Available tasks = {1, 3}.
- At time = 5, the CPU finishes task 2 and starts processing task 3 as it is the shortest. Available tasks = {1}.
- At time = 6, the CPU finishes task 3 and starts processing task 1. Available tasks = {}.
- At time = 10, the CPU finishes task 1 and becomes idle.
Example 2:
Input: tasks = [[7,10],[7,12],[7,5],[7,4],[7,2]]
Output: [4,3,2,0,1]
Explanation: The events go as follows:
- At time = 7, all the tasks become available. Available tasks = {0,1,2,3,4}.
- Also at time = 7, the idle CPU starts processing task 4. Available tasks = {0,1,2,3}.
- At time = 9, the CPU finishes task 4 and starts processing task 3. Available tasks = {0,1,2}.
- At time = 13, the CPU finishes task 3 and starts processing task 2. Available tasks = {0,1}.
- At time = 18, the CPU finishes task 2 and starts processing task 0. Available tasks = {1}.
- At time = 28, the CPU finishes task 0 and starts processing task 1. Available tasks = {}.
- At time = 40, the CPU finishes task 1 and becomes idle.
Constraints:
tasks.length == n1 <= n <= 1051 <= enqueueTimei, processingTimei <= 109Problem summary: You are given n tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the ith task will be available to process at enqueueTimei and will take processingTimei to finish processing. You have a single-threaded CPU that can process at most one task at a time and will act in the following way: If the CPU is idle and there are no available tasks to process, the CPU remains idle. If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index. Once a task is started, the CPU will process the entire task without stopping. The CPU can finish a task then start a new one instantly. Return the order in which the CPU will process the tasks.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[[1,2],[2,4],[3,2],[4,1]]
[[7,10],[7,12],[7,5],[7,4],[7,2]]
parallel-courses-iii)minimum-time-to-complete-all-tasks)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1834: Single-Threaded CPU
class Solution {
public int[] getOrder(int[][] tasks) {
int n = tasks.length;
int[][] ts = new int[n][3];
for (int i = 0; i < n; ++i) {
ts[i] = new int[] {tasks[i][0], tasks[i][1], i};
}
Arrays.sort(ts, (a, b) -> a[0] - b[0]);
int[] ans = new int[n];
PriorityQueue<int[]> q
= new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
int i = 0, t = 0, k = 0;
while (!q.isEmpty() || i < n) {
if (q.isEmpty()) {
t = Math.max(t, ts[i][0]);
}
while (i < n && ts[i][0] <= t) {
q.offer(new int[] {ts[i][1], ts[i][2]});
++i;
}
var p = q.poll();
ans[k++] = p[1];
t += p[0];
}
return ans;
}
}
// Accepted solution for LeetCode #1834: Single-Threaded CPU
func getOrder(tasks [][]int) (ans []int) {
for i := range tasks {
tasks[i] = append(tasks[i], i)
}
sort.Slice(tasks, func(i, j int) bool { return tasks[i][0] < tasks[j][0] })
q := hp{}
i, t, n := 0, 0, len(tasks)
for len(q) > 0 || i < n {
if len(q) == 0 {
t = max(t, tasks[i][0])
}
for i < n && tasks[i][0] <= t {
heap.Push(&q, pair{tasks[i][1], tasks[i][2]})
i++
}
p := heap.Pop(&q).(pair)
ans = append(ans, p.i)
t += p.t
}
return
}
type pair struct{ t, i int }
type hp []pair
func (h hp) Len() int { return len(h) }
func (h hp) Less(i, j int) bool { return h[i].t < h[j].t || (h[i].t == h[j].t && h[i].i < h[j].i) }
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func (h *hp) Push(v any) { *h = append(*h, v.(pair)) }
func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
# Accepted solution for LeetCode #1834: Single-Threaded CPU
class Solution:
def getOrder(self, tasks: List[List[int]]) -> List[int]:
for i, task in enumerate(tasks):
task.append(i)
tasks.sort()
ans = []
q = []
n = len(tasks)
i = t = 0
while q or i < n:
if not q:
t = max(t, tasks[i][0])
while i < n and tasks[i][0] <= t:
heappush(q, (tasks[i][1], tasks[i][2]))
i += 1
pt, j = heappop(q)
ans.append(j)
t += pt
return ans
// Accepted solution for LeetCode #1834: Single-Threaded CPU
use std::cmp::Reverse;
use std::collections::BinaryHeap;
impl Solution {
pub fn get_order(tasks: Vec<Vec<i32>>) -> Vec<i32> {
let mut tasks = tasks;
for (i, t) in tasks.iter_mut().enumerate() {
t.push(i as i32);
}
tasks.sort_by(|a, b| a[0].cmp(&b[0]));
let mut res = vec![];
let mut min_heap = BinaryHeap::new();
let (mut i, mut time) = (0, tasks[0][0]);
while !min_heap.is_empty() || i < tasks.len() {
while i < tasks.len() && time >= tasks[i][0] {
min_heap.push(Reverse(vec![tasks[i][1], tasks[i][2]]));
i += 1;
}
if min_heap.is_empty() {
time = tasks[i][0];
} else {
let pair = min_heap.pop().unwrap();
let process_time = pair.0[0];
let index = pair.0[1];
time += process_time;
res.push(index);
}
}
res
}
}
// Accepted solution for LeetCode #1834: Single-Threaded CPU
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1834: Single-Threaded CPU
// class Solution {
// public int[] getOrder(int[][] tasks) {
// int n = tasks.length;
// int[][] ts = new int[n][3];
// for (int i = 0; i < n; ++i) {
// ts[i] = new int[] {tasks[i][0], tasks[i][1], i};
// }
// Arrays.sort(ts, (a, b) -> a[0] - b[0]);
// int[] ans = new int[n];
// PriorityQueue<int[]> q
// = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]);
// int i = 0, t = 0, k = 0;
// while (!q.isEmpty() || i < n) {
// if (q.isEmpty()) {
// t = Math.max(t, ts[i][0]);
// }
// while (i < n && ts[i][0] <= t) {
// q.offer(new int[] {ts[i][1], ts[i][2]});
// ++i;
// }
// var p = q.poll();
// ans[k++] = p[1];
// t += p[0];
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
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.