Program to find first fit room from a list of rooms in Python

Suppose we have a list of numbers called rooms and another target value t. We have to find the first value in rooms whose value is at least t. If there is no such room, return -1.

So, if the input is like rooms = [20, 15, 35, 55, 30] t = 30, then the output will be 35. Because 35 is the first room that can accommodate the target size of 30.

Algorithm

To solve this, we will follow these steps −

  • for each room in rooms, do

    • if room >= t, then

      • return room

  • return -1

Example

Let us see the following implementation to get better understanding ?

def solve(rooms, t):
    for room in rooms:
        if room >= t:
            return room
    return -1

rooms = [20, 15, 35, 55, 30]
t = 30
print(solve(rooms, t))

The output of the above code is ?

35

How It Works

The function iterates through the list sequentially. When it finds the first room with size greater than or equal to the target, it immediately returns that room size. In our example, rooms 20 and 15 are too small, but 35 is the first room that can fit the target size of 30.

Additional Example

Here's another example where no room fits the requirement ?

def solve(rooms, t):
    for room in rooms:
        if room >= t:
            return room
    return -1

rooms = [10, 15, 20, 25]
t = 30
result = solve(rooms, t)
print(f"Result: {result}")
Result: -1

Conclusion

This first-fit algorithm provides a simple O(n) solution to find the first room that meets the minimum size requirement. It returns -1 when no suitable room is found, making it useful for room allocation problems.

Updated on: 2026-03-26T15:12:07+05:30

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements