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

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how theyโ€™re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Sentry blog image

Identify what makes your TTFB high so you can fix it

In the past few years in the web dev world, weโ€™ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

Read more