Skip to content

Commit 7d99dac

Browse files
author
Karthikeyan Sadayamuthu
committed
adding two sum to python
1 parent 4609b80 commit 7d99dac

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

python/array/1_two_sum.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
3+
4+
You may assume that each input would have exactly one solution, and you may not use the same element twice.
5+
6+
You can return the answer in any order.
7+
8+
Example 1:
9+
10+
Input: nums = [2,7,11,15], target = 9
11+
Output: [0,1]
12+
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
13+
Example 2:
14+
15+
Input: nums = [3,2,4], target = 6
16+
Output: [1,2]
17+
Example 3:
18+
19+
Input: nums = [3,3], target = 6
20+
Output: [0,1]
21+
22+
Constraints:
23+
2 <= nums.length <= 104
24+
-109 <= nums[i] <= 109
25+
-109 <= target <= 109
26+
Only one valid answer exists.
27+
Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?
28+
29+
"""
30+
31+
class Solution:
32+
def twoSum(self, nums: list[int], target: int) -> list[int]:
33+
# 2,7,11,15 target 9
34+
lookup = {}
35+
for count, num in enumerate(nums):
36+
if target - num in lookup:
37+
return lookup[target-num], count
38+
lookup[num]=count
39+
40+
41+
if __name__ == "__manin__":
42+
solution = Solution()
43+
print(solution.twoSum([2,7,11,15], 9))

0 commit comments

Comments
 (0)