Перейти к содержанию

Two Sum

🇷🇺 Название: Две суммы
LeetCode: two-sum
Временная сложность: O(n)
Пространственная сложность: O(n)

Решение

from typing import List


class Solution:  
    def twoSum(self, nums: List[int], target: int) -> List[int]:  
        pair = {}  

        for i, num in enumerate(nums):  
            if target - num in pair:  
                return[i, pair[target - num]]  
            pair[num] = i  
        return []

🇺🇸 Условие

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

🇷🇺 Условие

Примеры

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

{
  "examples": [
    {
      "input": {
        "nums": [2,7,11,15],
        "target": 9
      },
      "output": [0,1]
    },
    {
      "input": {
        "nums": [3,2,4],
        "target": 6
      },
      "output": [1,2]
    },
    {
      "input": {
        "nums": [3,3],
        "target": 6
      },
      "output": [0,1]
    }
  ]
}

Ограничения

  • \(2 \leq nums.length \leq 10^4\)
  • \(-10^9 \leq nums[i] \leq 10^9\)
  • \(-10^9 \leq target \leq 10^9\)
  • Only one valid answer exists.

Потребление ресурсов

⏱ Time complexity: O(n)

  • Один проход по списку nums (длина n)
  • Каждая операция со словарём (поиск in, вставка) — O(1)

Итог: O(n)

🧠 Space complexity: O(n)

  • В худшем случае в pair сохраняются все n чисел (если решение в конце или отсутствует)
  • Дополнительная память зависит от размера nums

Итог: O(n)

easy array hash-table


Metadata

  • title_rus: Две суммы
  • difficulty: Easy
  • leetcode_url: https://leetcode.com/problems/two-sum/
  • topics: ['Array', 'Hash Table']
  • time: O(n)
  • space: O(n)
  • grind75: True
  • tags: ['Array', 'Easy', 'Hash Table', 'problem']
  • git_revision_date_localized: 5 июля 2025 г.
  • git_revision_date_localized_hash: f6ac458ea7f3485fe36c4b8c8f7c610ae2d995e7
  • git_revision_date_localized_tag:
  • git_revision_date_localized_raw_date: 5 июля 2025 г.
  • git_revision_date_localized_raw_datetime: 5 июля 2025 г. 19:32:08
  • git_revision_date_localized_raw_datetime-timezone: 5 июля 2025 г. 19:32:08 UTC
  • git_revision_date_localized_raw_iso_date: 2025-07-05
  • git_revision_date_localized_raw_iso_datetime: 2025-07-05 19:32:08
  • git_revision_date_localized_raw_timeago:
  • git_revision_date_localized_raw_custom: 05. июля 2025
  • git_site_revision_date_localized_hash: f6ac458ea7f3485fe36c4b8c8f7c610ae2d995e7
  • git_site_revision_date_localized_tag:
  • git_site_revision_date_localized: 5 июля 2025 г.
  • git_site_revision_date_localized_raw_date: 5 июля 2025 г.
  • git_site_revision_date_localized_raw_datetime: 5 июля 2025 г. 19:32:08
  • git_site_revision_date_localized_raw_datetime-timezone: 5 июля 2025 г. 19:32:08 UTC
  • git_site_revision_date_localized_raw_iso_date: 2025-07-05
  • git_site_revision_date_localized_raw_iso_datetime: 2025-07-05 19:32:08
  • git_site_revision_date_localized_raw_timeago:
  • git_site_revision_date_localized_raw_custom: 05. июля 2025