Skip to content

Commit 160756d

Browse files
authored
Merge pull request #1475 from ivan1016017/december04
adding algo
2 parents 1580139 + 5fdc2e5 commit 160756d

4 files changed

Lines changed: 116 additions & 0 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class Solution:
5+
def productExceptSelf(self, nums: List[int]) -> List[int]:
6+
"""
7+
Calculate product of all elements except self without division.
8+
9+
Strategy: Two-pass with prefix and suffix products
10+
- First pass: Build prefix products (product of all elements to the left)
11+
- Second pass: Build suffix products (product of all elements to the right)
12+
- Result[i] = prefix[i] * suffix[i]
13+
14+
Optimization: Use output array to store prefix, then multiply by suffix in-place
15+
16+
Time: O(n), Space: O(1) excluding output array
17+
"""
18+
19+
n = len(nums)
20+
answer = [1] * n
21+
22+
# First pass: Calculate prefix products
23+
# answer[i] contains product of all elements to the left of i
24+
prefix = 1
25+
for i in range(n):
26+
answer[i] = prefix
27+
prefix *= nums[i]
28+
29+
# Second pass: Calculate suffix products and multiply with prefix
30+
# For each position, multiply existing prefix with product of all elements to the right
31+
suffix = 1
32+
for i in range(n - 1, -1, -1):
33+
answer[i] *= suffix
34+
suffix *= nums[i]
35+
36+
return answer
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class Solution:
5+
def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
6+
"""
7+
Find the starting gas station to complete the circuit.
8+
9+
Key insights:
10+
1. If total gas < total cost, impossible to complete circuit
11+
2. If we can't reach station j from station i, then we can't reach j
12+
from any station between i and j (they all have negative tank balance)
13+
3. If a solution exists, it's guaranteed to be unique
14+
15+
Strategy: Greedy one-pass
16+
- Track total gas surplus/deficit
17+
- Track current tank from potential starting point
18+
- If tank goes negative, reset start to next station
19+
20+
Time: O(n), Space: O(1)
21+
"""
22+
23+
n = len(gas)
24+
total_gas = 0 # Total gas surplus/deficit for entire circuit
25+
current_tank = 0 # Current gas in tank from start_station
26+
start_station = 0 # Potential starting station
27+
28+
for i in range(n):
29+
# Calculate net gas at this station (gain - cost to next)
30+
net_gas = gas[i] - cost[i]
31+
32+
# Add to both total and current tank
33+
total_gas += net_gas
34+
current_tank += net_gas
35+
36+
# If current tank is negative, we can't reach next station from start_station
37+
# All stations from start_station to i are invalid starting points
38+
# Try starting from the next station (i + 1)
39+
if current_tank < 0:
40+
start_station = i + 1 # Reset starting point
41+
current_tank = 0 # Reset tank
42+
43+
# If total gas is negative, impossible to complete circuit
44+
# Otherwise, start_station is the answer
45+
return start_station if total_gas >= 0 else -1
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import unittest
2+
from src.my_project.interviews.top_150_questions_round_22\
3+
.ex_13_product_of_array_except_itself import Solution
4+
5+
class ProductExcetItselfTestCase(unittest.TestCase):
6+
7+
def test_product_first_case(self):
8+
solution = Solution()
9+
output = solution.productExceptSelf(nums = [1,2,3,4])
10+
target = [24,12,8,6]
11+
self.assertEqual(output, target)
12+
13+
def test_product_second_case(self):
14+
solution = Solution()
15+
output = solution.productExceptSelf(nums = [-1,1,0,-3,3])
16+
target = [0,0,9,0,0]
17+
self.assertEqual(output, target)
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import unittest
2+
from src.my_project.interviews.top_150_questions_round_22\
3+
.ex_14_gas_station import Solution
4+
5+
class GasStationTestCase(unittest.TestCase):
6+
7+
def test_gas_station_first_case(self):
8+
solution = Solution()
9+
output = solution.canCompleteCircuit(gas = [1,2,3,4,5],
10+
cost = [3,4,5,1,2])
11+
target = 3
12+
self.assertEqual(output, target)
13+
14+
def test_gas_station_second_case(self):
15+
solution = Solution()
16+
output = solution.canCompleteCircuit(gas = [2,3,4], cost = [3,4,3])
17+
target = -1
18+
self.assertEqual(output, target)

0 commit comments

Comments
 (0)