Skip to content

Commit

Permalink
Adds medium two pointer exercise
Browse files Browse the repository at this point in the history
  • Loading branch information
joffilyfe committed Jan 17, 2024
1 parent 31c0ef1 commit ac7b4fc
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
35 changes: 35 additions & 0 deletions 167.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from typing import List
import unittest


class Solution:
def twoSum(self, numbers: List[int], target: int) -> List[int]:
i = 0
j = len(numbers) - 1

while i < j:
sum = numbers[i] + numbers[j]

if sum == target:
return [i + 1, j + 1]
elif sum > target:
j -= 1
elif sum < target:
i += 1

return [-1, -1]


class Tests(unittest.TestCase):
def test_one(self):
self.assertEqual(Solution().twoSum(numbers=[2, 7, 11, 15], target=9), [1, 2])

def test_two(self):
self.assertEqual(Solution().twoSum(numbers=[2, 3, 4], target=6), [1, 3])

def test_three(self):
self.assertEqual(Solution().twoSum(numbers=[-1, 0], target=-1), [1, 2])


if __name__ == "__main__":
unittest.main()
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
| -------------- | ---------------------- | ------------------------------------------------------------------------------------ |
| 1.py | Hash table | https://leetcode.com/problems/two-sum/ |
| 35.py | Binary Search | https://leetcode.com/problems/search-insert-position/ |
| 167.py | Two pointers | https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ |
| 888.py | Hash table | https://leetcode.com/problems/fair-candy-swap |
| 977.py | Sorting | https://leetcode.com/problems/squares-of-a-sorted-array/ |
| 1051.py | | |
Expand Down

0 comments on commit ac7b4fc

Please sign in to comment.