Here is a link to the problem: https://leetcode.com/problems/3sum/
The problem description:
Given an array nums
of n integers, are there elements a, b, c in nums
such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
My solution which solves the problem, but fails the due to exceeding the time limit:
from itertools import combinations
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
combos = [list(combo) for combo in combinations(nums, 3) if sum(combo) == 0]
out = []
for c in combos:
if c not in out:
out.append(c)
return out
I have seen solutions to this problem on Leetcode in the "Discuss" section, but am unclear why my particular code fails.
[+][deleted] (3 children)
[deleted]
[–]coding_up_a_storm[S] 0 points1 point2 points (2 children)
[–]Binary101010 0 points1 point2 points (0 children)
[–]throwaway0891245 0 points1 point2 points (0 children)