|
| 1 | +#Difficulty = Easy |
| 2 | +#Submission Speed = 64.69% |
| 3 | +''' |
| 4 | +Solution-1: |
| 5 | +Example: nums = [3,2,1,4] target = 6 |
| 6 | +Step1) Create a dictionary and populate it with elements of nums as the key and their corresponding index as values. |
| 7 | + |
| 8 | + d = { |
| 9 | + 3:0, |
| 10 | + 2:1 |
| 11 | + 1:2 |
| 12 | + 4:3 |
| 13 | + } |
| 14 | +Step2) Traverse the array and check for every element, if complement (target-element) exists in dictionary. Also check, |
| 15 | +the index of (target-element) is not same as that of element (using dictionary as we have saved index as values.) |
| 16 | +Traversing the array: |
| 17 | +# i=0 3,2,1,4 |
| 18 | + ^ |
| 19 | + checking if (6-3) exists in dictionary? |
| 20 | + Yes it exists |
| 21 | + but d[6-3]==i (We are adding the same element to get the target which is invalid according to the question) |
| 22 | +
|
| 23 | +Step3) If we found a valid pair, then we return [i,d[complement]] |
| 24 | +''' |
| 25 | +''' |
| 26 | +Time Complexity = O(N) |
| 27 | +Space Complexity = O(N) |
| 28 | +''' |
| 29 | + |
| 30 | +#Two-pass |
| 31 | +class Solution: |
| 32 | + def twoSum(self, nums: List[int], target: int) -> List[int]: |
| 33 | + d = {v:i for i,v in enumerate(nums)} |
| 34 | + for i in range(len(nums)): |
| 35 | + complement = target - nums[i] |
| 36 | + if complement in d and d[complement]!=i: |
| 37 | + return [i,d[complement]] |
| 38 | + |
| 39 | +''' |
| 40 | +Solution-2: Single Pass: |
| 41 | +Instead of doing double passes (one pass while populating the dictionary and other while checking for complement), |
| 42 | +We do this in Single Pass. that is, checking for complement while populating the dictionary. |
| 43 | +Before inserting the element in dictionary, we check whether the complement already exists, if exists, we return both indexes |
| 44 | +(index of current element and index of its complement) and if not exists, we insert the element in dictionary. |
| 45 | +This way we wont have to check if the index of element and its complement is same or not. |
| 46 | +''' |
| 47 | + |
| 48 | +#Single Pass |
| 49 | +class Solution: |
| 50 | + def twoSum(self, nums: List[int], target: int) -> List[int]: |
| 51 | + d = {} |
| 52 | + for i in range(len(nums)): |
| 53 | + complement = target - nums[i] |
| 54 | + if complement in d: |
| 55 | + return [d[complement],i] |
| 56 | + d[nums[i]]=i |
0 commit comments