Code Logo

Locker Lookup with HashMap

Published at22 Apr 2026
Collections Framework Easy 0 views
Like0

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

Example 1
Input
records = ["Ayu:12", "Bima:18", "Cici:25"], student = "Bima"
Output
18
Explanation

Bima is mapped to locker 18 in the lookup table.

Example 2
Input
records = ["Lina:7"], student = "Lina"
Output
7
Explanation

A single stored record is still a normal map lookup.

Example 3
Input
records = ["Ayu:12", "Bima:18"], student = "Dodi"
Output
-1
Explanation

A missing student should return -1.

Algorithm Flow

Recommendation Algorithm Flow for Locker Lookup with HashMap
Recommendation Algorithm Flow for Locker Lookup with HashMap

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:

Map<String, Integer> lockers = new HashMap<>();
for (String record : records) {
    String[] parts = record.split(":");
    lockers.put(parts[0], Integer.parseInt(parts[1]));
}
return lockers.getOrDefault(student, -1);

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

java - Approach 1
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;
    }
}