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.