DEV Community

Cover image for Python challenge_21πŸβš”οΈ
Mahmoud EL-kariouny
Mahmoud EL-kariouny

Posted on

2

Python challenge_21πŸβš”οΈ

Two Sum

  • 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]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Task URL: https://leetcode.com/problems/two-sum

My Solution:

def towSum(nums, target):
    pre_map = {}

    for i, n in enumerate(nums):
        diff = target - n

        if diff in pre_map:
            return [pre_map[diff], i]

        pre_map[n] = i

print(towSum([2, 10, 7, 11, 15], 9))

Enter fullscreen mode Exit fullscreen mode
Learn Python

πŸŽ₯

Connect with Me 😊

πŸ”— Links

linkedin

twitter

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay