tags:
  - code
topic: Sum
difficulty: Easy
link: https://leetcode.com/problems/two-sum/
date: 2023-10-21Problem
Given an array of integers
numsand an integertarget, return indices of the two numbers such that they add up totarget.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
twosum([2,7,11,15],9) # Returns [0,1]
def twosum(nums, target):
	for (index, digit) in enumerate(nums):
		for (index2, digit2) in enumerate(nums):
			if digit + digit2 == target and digit != digit2:
				return [index,index2]
	return None
O(n^2), as it requires another iteration over the list for every iteration. nums argument was empty prior to any solutions, i.e:if not nums:
	return None
return None, the statement of which the function will default too if anything goes wrong with the code. It covers the above case as well as one where there is no solution (even though the problem says assume every input has exactly one solution)(index, digit).