DeepRest

Gas Station

Jan 20th, 2022 (edited)
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.29 KB | None | 0 0
  1. '''LOGIC:
  2. WE NEED TO FIND THE START INDEX SUCH THAT WE CAN TRAVEL THE CIRCUIT AND RETURN BACK WITHOUT RUNNING OUT OF GAS IN BETWEEN ANYWHERE.
  3. if sum(gas) < sum(costs), surely there is no solution
  4. Else there is a solution
  5. If we do brute force by considering every index as a starting point then complexity turns out to be quadratic.
  6. Observation: Consider 0th index as the starting point keep on travelling until u run out of gas(say at i index). We see that for all the indexes from 0 to i as starting point we will eventually run out at ith index. So after 0 we consider i+1 as possible next starting point, and so on. For a starting point if we are able to reach up to last index(n-1) then that index is starting point if conditions for solution holds i.e if the spare fuel at station n-1 is greater than or equal to sum of all negative gas cost diffs
  7. '''
  8.  
  9. #1. O(1) space and one pass
  10. #my two acs just differing for -1 check
  11. class Solution:
  12.     def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
  13.         n = len(gas)
  14.         tot = s = 0
  15.         pos = -1
  16.         for i in range(n):
  17.             s += gas[i] - cost[i]
  18.             tot += gas[i] - cost[i]
  19.             if s < 0:
  20.                 pos = i  
  21.                 s = 0
  22. #-1 case: total of all differences negative
  23.         return -1 if tot<0 else (pos+1)%n
  24.  
  25. #2
  26. class Solution:
  27.     def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
  28.         n = len(gas)
  29.         rem = s = 0
  30.         pos = -1
  31.         for i in range(n):
  32.             s += gas[i] - cost[i]
  33.             if s < 0:
  34.                 pos = i  
  35.                 rem -= s
  36.                 s = 0
  37. #-1 check: rem(sum of -ve diffs) > sum(sum of last streak of +ve diffs)
  38.         return -1 if rem>s else (pos+1)%n
  39.  
  40.  
  41. #3. my initial o(n) space and multipass soln
  42. class Solution:
  43.     def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
  44.         if sum(gas)<sum(cost):
  45.             return -1
  46.      
  47.         n = len(gas)
  48.         pf = [0]*n
  49.         for i in range(n):
  50.             pf[i] = gas[i]-cost[i]
  51.             if pf[i-1]>0:
  52.                 pf[i] += pf[i-1]
  53.         pos = n-1
  54.         s = pf[-1]
  55.         for i in range(n-1):
  56.             if pf[i] < 0:
  57.                 pos = i
  58.             s += pf[i]
  59.         return (pos+1)%n
  60.            
Add Comment
Please, Sign In to add comment