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.