简体   繁体   中英

what approach is best to decrease the time complexity of this problem

I want to preface this thread by stating I am still learning the basics of data structures and algorithms I'm not looking for the correct code for this problem but rather what the correct approach is. So that I can learn what situations call for which data structure. That being said I am now going to try and correctly explain this code.

The code below is a solution I had written for a medium-level leetcode problem. Please see the link to read the problem

Correct me if I am wrong, currently the time complexity of this algorithn is O(n)

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]):
        startingStation = 0
        didCircuit = -1
        tank = 0
        i = 0
        while i <= len(gas):
            if startingStation == len(gas):
                return -1
            if startingStation == i:
                didCircuit += 1
            if didCircuit == 1:
                return startingStation
            tank += gas[i] - cost[i]
            if tank >= 0:
                i += 1
            if i == len(gas):
                i = 0
            if tank < 0:
                didCircuit = -1
                startingStation += 1
                i = startingStation
                tank = 0

The code works fine but the time complexity is too slow to iterate through each test case. What I am asking is if this algorithm is O(n) what approach could I have used to make the runtime complexity of this algorithm O(log(n)) or just faster?

side question - I know having a lot of if statements is bad and ugly code but if all of the iterations are O(1) does the amount of if statements have any impact on the performance of this function if scaled to a high iteration count?

"Correct me if I am wrong, currently the time complexity of this algorithn is O(n)"

This algorithm is O(n^2) rather than O(n). In the best case, it will return an answer in only "n" iterations of the while loop, but in the situation where there is no answer, it needs to run the loop (n*(n+1))/2 times.

O() notation tells us to ignore practical values of n and remove terms that become insignificant as n grows very large. So we ignore the +n and the /2 in the iterations, with the most significant component being the n^2.

So it is an O(n^2) algorithm.

"if all of the iterations are O(1) does the amount of if statements have any impact on the performance of this function if scaled to a high iteration count"

No, the O() of the algorithm is not impacted by the number of logic statements, but beware of hidden loops and expensive operations. For example, a logic statement of if x in list can be O(n) on the number of items in the list without data-specific optimizations, so if you have an O(n) loop around it (for the same list) you could have an O(n^2) algorithm. None of your logic statements have this issue, you can ignore them for O() purposes.

Assignments can be treated the same.

"What I am asking is if this algorithm is O(n) what approach could I have used to make the runtime complexity of this algorithm O(log(n)) or just faster?"

Since the algorithm is not O(n), better to ask how you might get there. You can get there by finding a way to not have to loop over the arrays more than once.

You ask about data structures, but you talk about time complexity.

The best algorithm in this case is O(n) in time, and O(1) in additional space. It requires you to store one integer in addition to the two arrays. You can even implement it with three integers of storage if you keep reading the gas and cost values from streams of data.

"I'm not looking for the correct code for this problem but rather what the correct approach is"

They've given you a gift with the statement that any success solution is unique. From this we know that the amount of gas available is no more than the sum of all costs plus the smallest difference between a station's cost and gas. If it were otherwise, then there would two points in the loop where you could start.

That means that as soon as we find an i where the sum of the gas available at stations 0 to i exceeds the cost of travel from 0 to i we have found the unique starting position. If we get to the end of the line and have not found this, we know it is impossible to do so for any starting position.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM