Here's my solution for the Leet Code's Three Sum problem -- would love feedback on (1) code efficiency and (2) style/formatting. This is Python 3.
Problem:
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:
def threeSum(nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def _twoSum(nums_small, target):
'''
INPUT: List of numeric values, int target
OUTPUT: list: pair(s) from nums_small that add up to target and -1*target
'''
nums_dict = {}
return_lst = []
for indx, val in enumerate(nums_small, target):
if target - val in nums_dict:
return_lst.append([val, target - val, -1*target])
nums_dict[val] = indx
return return_lst
return_dict = {}
for indx, val in enumerate(nums):
for solution in _twoSum(nums[:indx] + nums[indx+1:], -1*val):
if sorted(solution) not in return_dict.values():
return_dict[str(indx)+str(solution)] = sorted(solution) # ... hacky way of storing multiple solutions to one index ...
return list(return_dict.values())