Two Sum
LeetCode 1 · எளிது · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Store seen values in a map; look up target − num before inserting num.
நான் Two Sum (LeetCode 1) ஐ இப்படித் தீர்த்தேன் — Hashing / Anagram பேட்டர்னின் ஒரு எளிது பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
For each number, the partner you need is target − num. Instead of searching the rest of the array for it, remember every number you've already passed in a hash map (value → index); then checking whether the partner exists is a single lookup.
Approach
- 1
Walk the array once with index and value.
- 2
Compute remaining = target − num.
- 3
If remaining is already in the map, return its index and the current index.
- 4
Otherwise record num → index and continue.
நான் எப்படித் தீர்த்தேன்
One-pass hash mapPythonO(n) time · O(n) space
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
mpp = {}
for index, num in enumerate(nums):
remaining = target - num
if remaining in mpp:
last_index = mpp.get(remaining)
return [index,last_index]
mpp[num]=index
return -1Two Sum — அடிக்கடி கேட்கப்படும் கேள்விகள்
Two Sum பின்னாலுள்ள intuition என்ன?
For each number, the partner you need is target − num. Instead of searching the rest of the array for it, remember every number you've already passed in a hash map (value → index); then checking whether the partner exists is a single lookup.
Two Sum (LeetCode 1) ஐ எப்படித் தீர்ப்பது?
1. Walk the array once with index and value. 2. Compute remaining = target − num. 3. If remaining is already in the map, return its index and the current index. 4. Otherwise record num → index and continue.
Two Sum இன் time மற்றும் space complexity என்ன?
Time: O(n). Space: O(n). (Accepted approach: One-pass hash map.)
Two Sum இல் பொதுவான தவறுகள் என்ன?
Check the map before inserting the current number, so an element is never paired with itself. Duplicates like [3,3] work because the first 3 is stored before the second is checked.