Category Archives: Python

LeetCode problem 167

Back online after quite some time. Lately I’ve been playing with leetcode, so below is solution to problem 167. This problem is an easy one and no complex structures are needed in order to solve it.

#!/usr/bin/env python

''' LeetCode problem 167 
Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, 
find two numbers such that they add up to a specific target number. 
Let these two numbers be numbers[index1] and numbers[index2] where 1 <= first < second <= numbers.length.
2 <= numbers.length <= 3 * 104
-1000 <= numbers[i] <= 1000
numbers is sorted in non-decreasing order.
-1000 <= target <= 1000
The tests are generated such that there is exactly one solution. '''

def twoSum(numbers, target):
	for i in numbers:
		if (target - i) in numbers[numbers.index(i)+1:]:
			return [numbers.index(i), numbers.index(i) + numbers[numbers.index(i)+1:].index(target - i)+1]


#twoSum([-5, -3, -1, 0, 10], -1)
print(f"{twoSum([-5, -3, -1, 0, 10], -1)}")
#twoSum([2, 7, 11, 15], 9)
print(f"{twoSum([2,7,11,15], 9)}")
#twoSum([2, 3, 4], 6)
print(f"{twoSum([2, 3, 4], 6)}")
#twoSum([5, 25, 75], 100)
print(f"{twoSum([5, 25,75], 100)}")
#twoSum([0, 0, 3, 4], 0)
print(f"{twoSum([0, 0, 3, 4], 0)}")

I'll try to post more often from now on. I'll try to make it at least once a week.