Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 := 0seen := a list whose length is same as nums and initially filled with false-
for each index
iand correspondingninnums, do-
if
seen[i]isfalse, thenseen[i] := Trueans := ans + 1prev := n-
for
jin rangei+1to size ofnums, do-
if
nums[j] > prevandseen[j]isfalse, thenseen[j] := Trueprev := 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.
