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.