Challenge: Ticket Counter
Completed
Simulate a ticket queue. Read n commands: join <name> adds a person to the back; serve serves the person at the front and prints Served <name> (or Nobody waiting). At the end print Waiting: <count>.
Input
First n, then n commands.
Output
A line for each serve, then the waiting count.
Example
Input
5 join Asha join Ravi serve join Meera serve
Output
Served Asha Served Ravi Waiting: 1
Editor
Java
Hints
A Queue gives people back in the order they joined.
Only read a name after the word join.
Solution explanation
offer adds at the back and poll removes from the front: first in, first out.
Show solution
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Queue<String> q = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
String cmd = sc.next();
if (cmd.equals("join")) {
q.offer(sc.next());
} else if (q.isEmpty()) {
System.out.println("Nobody waiting");
} else {
System.out.println("Served " + q.poll());
}
}
System.out.println("Waiting: " + q.size());
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module