Locker Lookup with HashMap
A school hallway uses simple locker records in the form "name:number". A staff member wants to look up one student quickly without scanning the paper list again and again.
Your task is to read the records, build a lookup table, and return the locker number for the requested student. If the student does not appear in the records, return -1.
For example, if the records are ["Ayu:12", "Bima:18", "Cici:25"] and the target student is "Bima", the answer should be 18. If the target is "Dodi", the answer should be -1.
This is a good beginner challenge for HashMap because the main goal is fast lookup by key.
Example Input & Output
Bima is mapped to locker 18 in the lookup table.
A single stored record is still a normal map lookup.
A missing student should return -1.
Algorithm Flow

Solution Approach
A HashMap is designed for key-value storage, so it fits this problem very naturally. Each record contains a student name as the key and a locker number as the value.
The first step is to loop through the list of record strings and split each one at the colon. Then store the name and parsed number inside a map. After that, the final answer becomes a simple lookup.
The pattern looks like this:
This approach is much better than scanning the full list every time a student name is requested. Once the map is built, lookup is fast and direct. The full solution runs in O(n) time to build the map, and the final retrieval is constant on average.
Best Answers
import java.util.List;
import java.util.Map;
import java.util.HashMap;
class Solution {
public static int findLockerNumber(List<String> records, String student) {
Map<String, Integer> lockers = new HashMap<>();
for (String record : records) {
int colon = record.indexOf(':');
String name = record.substring(0, colon);
int number = Integer.parseInt(record.substring(colon + 1));
lockers.put(name, number);
}
return lockers.containsKey(student) ? lockers.get(student) : -1;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
