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.