Skip to content

Added gas_station.py #11822

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions data_structures/arrays/gas_station.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
class Solution:
def can_omplete_circuit(self, gas: list[int], cost: list[int]) -> int:
"""
Determines the starting gas station index from which you can complete the circuit,

Check failure on line 4 in data_structures/arrays/gas_station.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

data_structures/arrays/gas_station.py:4:89: E501 Line too long (90 > 88)
or returns -1 if it's not possible.

Check failure on line 6 in data_structures/arrays/gas_station.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/arrays/gas_station.py:6:1: W293 Blank line contains whitespace
Args:
gas (List[int]): List of gas available at each station.
cost (List[int]): List of gas costs to travel to the next station.

Returns:
int: The index of the starting station, or -1 if no solution exists.

Examples:
>>> solution = Solution()
>>> solution.can_omplete_circuit([1, 2, 3, 4, 5], [3, 4, 5, 1, 2])
3
>>> solution.can_omplete_circuit([2, 3, 4], [3, 4, 3])
-1
>>> solution.can_omplete_circuit([5, 1, 2, 3, 4], [4, 4, 1, 5, 1])
4
"""
total_gas = 0
current_gas = 0
start_station = 0

Check failure on line 26 in data_structures/arrays/gas_station.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/arrays/gas_station.py:26:1: W293 Blank line contains whitespace
for i in range(len(gas)):
total_gas += gas[i] - cost[i]
current_gas += gas[i] - cost[i]

Check failure on line 30 in data_structures/arrays/gas_station.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

data_structures/arrays/gas_station.py:30:1: W293 Blank line contains whitespace
if current_gas < 0:
start_station = i + 1
current_gas = 0

if total_gas < 0:
return -1
else:
return start_station

# Example usage with doctests
if __name__ == "__main__":
import doctest
doctest.testmod()
Loading