Problem

Description

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
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.

Test Cases

twosum([2,7,11,15],9) # Returns [0,1]

Solution

My Solution

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
  • My solution is very time complex (O(n^2), as it requires another iteration over the list for every iteration.
  • Note: Optimal solutions included checking for whether the nums argument was empty prior to any solutions, i.e:
if not nums:
	return None
  • I've covered that part by adding a 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)

Other Solutions

Learning Experiences

  • What the enumerate function does is associate every term in a collection with its index, meaning it can then be unpacked as shown by (index, digit).