Tensorum
YouTubeশেখা শুরু করুন
LeetCode 1 · Hashing / Anagram

Two Sum

LeetCode 1 · সহজ · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

Store seen values in a map; look up target − num before inserting num.

সহজArrayHash Table
LeetCode-এ খুলুন ↗

আমি 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. 1

    Walk the array once with index and value.

  2. 2

    Compute remaining = target − num.

  3. 3

    If remaining is already in the map, return its index and the current index.

  4. 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 -1
স্টেপ-থ্রু লোড হচ্ছে…

Two 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.