Learn
Practice
Interview
Resources
Newsletter
F
Toggle theme
0
F
0
Toggle menu
Animations
← Back to All Animations
Gas Station
Bookmark
Brute Force
Greedy
Input
Example 1
Reset mid-way
Impossible
Start at 0
Single station
Custom
gas
=
[1, 2, 3, 4, 5]
,
cost
=
[3, 4, 5, 1, 2]
gas
1
2
3
4
5
-2
-2
-2
+3
+3
cost
3
4
5
1
2
0
1
2
3
4
gas
1
2
3
4
5
-2
-2
-2
+3
+3
cost
3
4
5
1
2
0
1
2
3
4
tank =
-2
gas
1
2
3
4
5
-2
-2
-2
+3
+3
cost
3
4
5
1
2
0
1
2
3
4
station
i
tank =
0
− 2 =
-2
(gas 1 − cost 3)
tank =
0
gas
1
2
3
4
5
-2
-2
-2
+3
+3
cost
3
4
5
1
2
0
1
2
3
4
i
tank =
-2
gas
1
2
3
4
5
-2
-2
-2
+3
+3
cost
3
4
5
1
2
0
1
2
3
4
station
i
tank =
0
− 2 =
-2
(gas 2 − cost 4)
tank =
0
gas
1
2
3
4
5
-2
-2
-2
+3
+3
cost
3
4
5
1
2
0
1
2
3
4
i
tank =
-2
gas
1
2
3
4
5
-2
-2
-2
+3
+3
cost
3
4
5
1
2
0
1
2
3
4
station
i
tank =
0
− 2 =
-2
below zero, this start fails
tank =
3
gas
1
2
3
4
5
-2
-2
-2
+3
+3
cost
3
4
5
1
2
0
1
2
3
4
station
i
tank =
0
+ 3 =
3
(gas 4 − cost 1)
tank =
6
gas
1
2
3
4
5
-2
-2
-2
+3
+3
cost
3
4
5
1
2
0
1
2
3
4
station
i
tank =
3
+ 3 =
6
(gas 5 − cost 2)
tank =
2
gas
1
2
3
4
5
-2
-2
-2
+3
+3
cost
3
4
5
1
2
0
1
2
3
4
station
i
tank =
4
− 2 =
2
(gas 2 − cost 4)
gas
1
2
3
4
5
-2
-2
-2
+3
+3
cost
3
4
5
1
2
0
1
2
3
4
i
return 3
algo
master
.
io
Step:
Start: Find a starting station to complete the circuit
0 / 16
Input
Example 1
Reset mid-way
Impossible
Start at 0
Single station
Custom
gas
=
[1, 2, 3, 4, 5]
,
cost
=
[3, 4, 5, 1, 2]
0 / 16
algo
master
.
io
Step:
Start: Find a starting station to complete the circuit