Program to find minimum number of busses are required to pass through all stops in Python

Suppose we have a list of numbers called nums representing bus stops on a line where nums[i] shows the time a bus must arrive at station i. Since buses can only move forward in time, we need to find the minimum number of buses required to pass through all stops.

So, if the input is like nums = [1, 2, 7, 9, 3, 4], then the output will be 2, as one bus can take stops [1, 2, 3, 4] and another can handle [7, 9].

Algorithm

To solve this, we will follow these steps ?

  • ans := 0

  • seen := a list whose length is same as nums and initially filled with false

  • for each index i and corresponding n in nums, do

    • if seen[i] is false, then

      • seen[i] := True

      • ans := ans + 1

      • prev := n

      • for j in range i+1 to size of nums, do

        • if nums[j] > prev and seen[j] is false, then

          • seen[j] := True

          • prev := nums[j]

  • return ans

Example

Let us see the following implementation to get better understanding ?

class Solution:
    def solve(self, nums):
        ans = 0
        seen = [False] * len(nums)
        
        for i, n in enumerate(nums):
            if not seen[i]:
                seen[i] = True
                ans += 1
                prev = n
                
                for j in range(i+1, len(nums)):
                    if nums[j] > prev and not seen[j]:
                        seen[j] = True
                        prev = nums[j]
        
        return ans

# Test the solution
ob = Solution()
nums = [1, 2, 7, 9, 3, 4]
print(ob.solve(nums))
2

How It Works

The algorithm uses a greedy approach. For each unvisited stop, it starts a new bus and tries to cover as many subsequent stops as possible in increasing time order. The seen array tracks which stops have already been assigned to a bus.

For the example [1, 2, 7, 9, 3, 4]:

  • Bus 1 starts at index 0 (time 1), then visits index 1 (time 2), index 4 (time 3), and index 5 (time 4)

  • Bus 2 starts at index 2 (time 7), then visits index 3 (time 9)

Conclusion

This greedy algorithm efficiently finds the minimum number of buses by ensuring each bus covers the maximum possible stops in chronological order. The time complexity is O(n²) where n is the number of stops.

Updated on: 2026-03-25T10:42:26+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements