Skip to content

Commit 11f0449

Browse files
Leetcode 167
1 parent feb1e32 commit 11f0449

1 file changed

Lines changed: 151 additions & 0 deletions

File tree

Leetcode/Leetcode_167.py

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
"""
2+
Problem: Two Sum
3+
---------------------------------
4+
Given an array nums and a target,
5+
return indices of two numbers such that:
6+
7+
nums[i] + nums[j] = target
8+
9+
---------------------------------
10+
This file contains TWO approaches:
11+
12+
1. Two Pointer (only works for SORTED array)
13+
2. HashMap (works for ANY array) ✅ Optimal
14+
15+
---------------------------------
16+
"""
17+
18+
from typing import List
19+
20+
21+
class Solution:
22+
23+
# =========================================================
24+
# 🔹 APPROACH 1: TWO POINTER (SORTED ARRAY ONLY)
25+
# =========================================================
26+
def twoSum_two_pointer(self, nums: List[int], target: int) -> List[int]:
27+
"""
28+
⚠️ IMPORTANT:
29+
This works ONLY if the array is SORTED
30+
31+
Step-by-step:
32+
1. Start with two pointers:
33+
l = 0 (start), r = n-1 (end)
34+
2. Calculate sum
35+
3. If sum == target → return indices
36+
4. If sum < target → move left pointer forward
37+
5. If sum > target → move right pointer backward
38+
"""
39+
40+
l = 0
41+
r = len(nums) - 1
42+
43+
while l < r:
44+
s = nums[l] + nums[r]
45+
46+
if s == target:
47+
return [l, r] # 0-based indexing
48+
49+
elif s < target:
50+
l += 1 # increase sum
51+
52+
else:
53+
r -= 1 # decrease sum
54+
55+
return [-1, -1]
56+
57+
58+
# =========================================================
59+
# 🔹 APPROACH 2: HASHMAP (OPTIMAL)
60+
# =========================================================
61+
def twoSum_hashmap(self, nums: List[int], target: int) -> List[int]:
62+
"""
63+
Step-by-step:
64+
1. Create a hashmap to store value → index
65+
2. For each number:
66+
- Compute complement = target - current number
67+
- Check if complement exists in hashmap
68+
3. If yes → return indices
69+
4. Else → store current number
70+
"""
71+
72+
hashmap = {}
73+
74+
for i, num in enumerate(nums):
75+
76+
complement = target - num
77+
78+
# Check if complement already exists
79+
if complement in hashmap:
80+
return [hashmap[complement], i]
81+
82+
# Store current number
83+
hashmap[num] = i
84+
85+
return [-1, -1]
86+
87+
88+
# =========================================================
89+
# 🧩 DRY RUN
90+
# =========================================================
91+
"""
92+
Example:
93+
nums = [2, 7, 11, 15]
94+
target = 9
95+
96+
HashMap Approach:
97+
-----------------
98+
i = 0 → num = 2 → complement = 7 → not found → store {2:0}
99+
i = 1 → num = 7 → complement = 2 → found → return [0,1]
100+
101+
Two Pointer (sorted):
102+
---------------------
103+
l = 0, r = 3 → 2 + 15 = 17 > 9 → r--
104+
l = 0, r = 2 → 2 + 11 = 13 > 9 → r--
105+
l = 0, r = 1 → 2 + 7 = 9 → return [0,1]
106+
"""
107+
108+
109+
# =========================================================
110+
# ⏱️ TIME & SPACE COMPLEXITY
111+
# =========================================================
112+
"""
113+
1. Two Pointer:
114+
--------------
115+
Time Complexity: O(n)
116+
Space Complexity: O(1)
117+
118+
⚠️ Only works if array is sorted
119+
120+
121+
2. HashMap:
122+
----------
123+
Time Complexity: O(n)
124+
Space Complexity: O(n)
125+
126+
✅ Works for unsorted arrays (BEST choice)
127+
"""
128+
129+
130+
# =========================================================
131+
# 🔥 KEY TAKEAWAYS
132+
# =========================================================
133+
"""
134+
👉 Two Pointer = only for sorted arrays
135+
👉 HashMap = best for general case
136+
👉 Avoid l <= r (use l < r)
137+
👉 Don't return +1 unless problem asks 1-based index
138+
"""
139+
140+
141+
# =========================================================
142+
# ✅ DRIVER CODE
143+
# =========================================================
144+
if __name__ == "__main__":
145+
sol = Solution()
146+
147+
nums = [2, 7, 11, 15]
148+
target = 9
149+
150+
print("Two Pointer:", sol.twoSum_two_pointer(nums, target))
151+
print("HashMap:", sol.twoSum_hashmap(nums, target))

0 commit comments

Comments
 (0)