Parking Lot System
Problem
A parking lot has slots numbered 1 to N (first line). Commands: park CAR (use the smallest free slot and print Slot <number>; print Lot full when there is no free slot; print Error: CAR already parked if the car is inside), leave CAR (print Freed slot <number>, or Error: CAR not found), status (print Free: <number of free slots>).
Constraints
- 1 <= N <= 100
- 1 <= commands <= 1000
Examples
Input
2 park A park B park C leave A park C
Output
Slot 1 Slot 2 Lot full Freed slot 1 Slot 1
Solutions
A small class with clear methods (park, leave, freeSlots) owns the data. The main code only reads commands and calls the methods. Each rule (smallest free slot, no double parking) lives in one place.
/*
* Problem : Process commands line by line.
* Input : Several lines of commands.
* Output : One line for each command.
* Approach: A class that owns the slots.
* Time : O(commands * capacity)
* Space : O(capacity)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: The parking lot class hides its data. The slots are stored in an array of car names. null means: the slot is free.
static class ParkingLot {
private final String[] slots;
ParkingLot(int capacity) {
slots = new String[capacity + 1];
}
String park(String car) {
for (int i = 1; i < slots.length; i++) {
if (car.equals(slots[i])) {
return "Error: " + car + " already parked";
}
}
for (int i = 1; i < slots.length; i++) {
if (slots[i] == null) {
slots[i] = car;
return "Slot " + i;
}
}
return "Lot full";
}
String leave(String car) {
for (int i = 1; i < slots.length; i++) {
if (car.equals(slots[i])) {
slots[i] = null;
return "Freed slot " + i;
}
}
return "Error: " + car + " not found";
}
int freeSlots() {
int free = 0;
for (int i = 1; i < slots.length; i++) {
if (slots[i] == null) {
free++;
}
}
return free;
}
}
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String[] lines) {
ParkingLot lot = new ParkingLot(Integer.parseInt(lines[0]));
String[] output = new String[lines.length - 1];
// Step 2: Run each command on the lot object.
for (int i = 1; i < lines.length; i++) {
String[] parts = lines[i].split(" ");
if (parts[0].equals("park")) {
output[i - 1] = lot.park(parts[1]);
} else if (parts[0].equals("leave")) {
output[i - 1] = lot.leave(parts[1]);
} else {
output[i - 1] = "Free: " + lot.freeSlots();
}
}
return output;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
java.util.List<String> all = new java.util.ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (!line.isEmpty()) {
all.add(line);
}
}
String[] lines = all.toArray(new String[0]);
System.out.println(String.join("\n", solve(lines)));
}
}
Hints (2)
- Which slot gets the next car?
- Where should the rule 'no double parking' be implemented?