0

Can anyone give me some advice on making this long python code using for loops run faster? This is a code to find 3 integers in a list called "nums" that is closest to "target". This code totally works, but I might need a more efficient way.:

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        clse = 2**31-1
        for a in range(len(nums)):
            for b in range(len(nums)):
                for c in range(len(nums)):
                    if a is not b and b is not c and c is not a:
                        if abs(nums[a]+nums[b]+nums[c]-target) < clse:
                            print(a,b,c)
                            clse = abs(nums[a]+nums[b]+nums[c]-target)
                            anum = nums[a]+nums[b]+nums[c]
        return anum
mkrieger1
  • 10,793
  • 4
  • 39
  • 47
Cyh1368
  • 99
  • 7
  • Without changing the algorithm, you can parallelize the outermost loop. – dyz May 23 '19 at 11:57
  • Your code is fundamentally broken due to the use of `is not` (which checks *object identity*) rather than `!=` (which compares equality). – jasonharper May 23 '19 at 12:21

2 Answers2

0

Every result you get you will actually get a few times. you will get (1, 2, 3) and then (1, 3, 2) and (2, 1, 3) and so on. If you will change your loop so that a <= b <= c the complexity will remain O(n^3) but the actual run time will be faster. b should be in range(a, len(nums)) and c in range(b, len(nums))

Tomer Shinar
  • 375
  • 1
  • 8
0

The following algorithm should be more efficient

Make a duplicate sorted list and name it b

Run a loop for each element in list a

Pick an element from start of b and end of b and add all these three elements

Maintain a variable to store the value of sum - target to keep track of closest possible pairs

if the value of sum is greater than target move the variable at start index of b forward else move the variable at end of list b backwards. //This will keep you close to target

Once the start and end variables meet or the value of sum after adding the elements keeps on goes farther from target break the loop and pick another element from list a

Maintain the values of a, b, c and target - sum

This should solve your problem in O(n^2) + O(nlogn) which is effectively O(n^2) and is a great improvement from O(n^3)

Sankalp Jain
  • 21
  • 2
  • 6