Bunk Allocation by Preferred Room Size
Data Structure DesignAuto-graded · 20 test casesLast updated
Match students to rooms by hard size preference in input order, respecting capacity, keeping partially filled rooms, and reporting students who could not be placed.
Bunk Allocation by Preferred Room Size
A residence hall needs to place students into rooms. Every room has a capacity of either 2 or 4 beds. Every student asks for exactly one room size, either 2 or 4. A preference is a hard requirement: a student may only be placed in a room whose capacity equals their preference.
Write a function that performs a single batch allocation and returns the result.
Input
students: a list of dictionaries, each with"id": a unique string identifying the student"preference": the integer2or4
rooms: a list of dictionaries, each with"id": a unique string identifying the room"capacity": the integer2or4
Allocation rules
- Process rooms in the order they appear in
rooms. - Students who want a given room size form a waiting line, ordered by their position in
students. - For each room, take students from the front of the waiting line for that room's capacity, one at a time, until the room has
capacityoccupants or the line is empty. - Rooms may end up partially filled or empty. Every room still appears in the output.
- A student is placed in at most one room and is never placed in a room of a different size than they asked for.
- Students who are not placed in any room are reported as unassigned.
Output
Return a dictionary with two keys:
"assignments": a list with one entry per room, in the same order asrooms. Each entry is a dictionary{"room_id": <room id>, "student_ids": <list of student ids in the room>}. The ids insidestudent_idsappear in the order they were placed, which is the input order of the students."unassigned": a list of ids of students not placed in any room, in the same order as they appear instudents.
Constraints
- Student ids are unique; room ids are unique.
- Each
preferenceand eachcapacityis either2or4. studentsandroomsmay each be empty.- Input sizes are at most a few thousand entries.
- Demand may exceed or fall short of supply; this must never overfill a room or raise an error.
Examples
Example 1
Input: allocate_rooms([{'id': 's1', 'preference': 2}, {'id': 's2', 'preference': 4}, {'id': 's3', 'preference': 2}], [{'id': 'r1', 'capacity': 2}, {'id': 'r2', 'capacity': 4}])
Output: {'assignments': [{'room_id': 'r1', 'student_ids': ['s1', 's3']}, {'room_id': 'r2', 'student_ids': ['s2']}], 'unassigned': []}
Example 2
Input: allocate_rooms([{'id': 'alice', 'preference': 4}, {'id': 'bob', 'preference': 4}, {'id': 'cara', 'preference': 4}, {'id': 'dan', 'preference': 4}, {'id': 'erin', 'preference': 4}], [{'id': 'north', 'capacity': 4}])
Output: {'assignments': [{'room_id': 'north', 'student_ids': ['alice', 'bob', 'cara', 'dan']}], 'unassigned': ['erin']}
Example 3
Input: allocate_rooms([{'id': 's1', 'preference': 2}, {'id': 's2', 'preference': 4}, {'id': 's3', 'preference': 2}], [{'id': 'r4', 'capacity': 4}, {'id': 'r2', 'capacity': 2}, {'id': 'r3', 'capacity': 2}])
Output: {'assignments': [{'room_id': 'r4', 'student_ids': ['s2']}, {'room_id': 'r2', 'student_ids': ['s1', 's3']}, {'room_id': 'r3', 'student_ids': []}], 'unassigned': []}
Hints
Hint 1
Group the students by requested room size into two first-in-first-out lines so that input order is preserved within each size.
Hint 2
Walk through the rooms in order. For each room, repeatedly take a student from the line matching its capacity, stopping when the room is full or the line is empty.
Hint 3
Record every room in the output even if it received nobody. At the end, scan the original student list and collect those who were never placed, which keeps their input order.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key observation is that the two room sizes never interact. Students who want a 2-bed room can only ever go to 2-bed rooms, and likewise for 4. So we split the students into two first-in-first-out lines, one per size, preserving input order.
Then we walk through the rooms in their given order. For each room we pop students from the line that matches its capacity until the room is full or the line runs out. Whatever was popped becomes that room's occupant list. Every room is recorded, even if it ends up empty.
Finally, we scan the original student list and collect every id that was never placed. Scanning in input order gives the required ordering of the unassigned list.
Why it is correct
- Capacity is respected: the loop for a room stops once it holds
capacitystudents. - Preferences are respected: a room only draws from the line for its own capacity.
- No duplicates: a student sits in exactly one line and is removed when popped.
- Deterministic order: lines preserve input order and rooms are processed in input order, so the result matches the specified tie-breaking exactly.
- Maximal placement: for each size, the number placed is the minimum of demand and total beds of that size, so no valid allocation under hard preferences places more students.
Complexity
- Time: O(S + R), where S is the number of students and R the number of rooms. Each student is enqueued and dequeued at most once, and each room does constant work beyond its pops.
- Space: O(S + R) for the lines, the placed set, and the output.
Reference solution
from collections import deque
from typing import List, Dict
def allocate_rooms(students: List[Dict[str, object]], rooms: List[Dict[str, object]]) -> Dict[str, object]:
"""Allocate students to rooms using hard room-size preferences."""
lines = {2: deque(), 4: deque()}
for student in students:
lines[student["preference"]].append(student["id"])
assignments = []
placed = set()
for room in rooms:
capacity = room["capacity"]
occupants = []
while len(occupants) < capacity and lines[capacity]:
sid = lines[capacity].popleft()
occupants.append(sid)
placed.add(sid)
assignments.append({"room_id": room["id"], "student_ids": occupants})
unassigned = [s["id"] for s in students if s["id"] not in placed]
return {"assignments": assignments, "unassigned": unassigned}