Lesson 15 of 19
Queues
Print jobs wait in arrival order. Enqueue puts a job at the back. Dequeue serves the job at the front.
Arrival order survives new arrivals
First in, first out (FIFO) fits shared work such as a printer. Only the front job is eligible to leave. A queue can track the front with an index or a link. Moving that marker lets the remaining jobs stay where they are.
Work through an example
A printer receives Map and Photo. It starts Map, then receives Form. Which job starts next, and what remains after it starts?
Step-by-step solution
- After Map starts, the front moves to Photo.
- Form joins behind Photo. A new arrival leaves the front in place.
- Photo starts next. Moving the front once more leaves Form as the only waiting job.
JavaScript example
const jobs = ["Map", "Photo"];
let front = 0;
front++; // Map starts
jobs.push("Form");
const nextJob = jobs[front++];
[nextJob, jobs.slice(front)]; // ["Photo", ["Form"]]DSA compiler
Try it yourself
Finish the animation to unlock this question.
A and B arrive. A is served, then C arrives. Who is next?
Play Orbit Queue · Related exercise · Queue · See this stage of the beginner path