Two Sum : Leetcode

Yasir
2 min readJun 15, 2020

--

With Explanation of Problem and Codes 😁 and some Snapshots

Explanation of Two Sum Problem

Here is the problem , which says that I will provide you a list having some elements and I will give a target integer also . All you have to do is , just find the pair of index of that elements 🤔 , on adding them sum should be target value .

For example , suppose this is a list nums = [2,6,3,2] and I am giving you the target value as 9 . So first you will find those two element , on adding them result becomes 9 which is target value . And in output will show the index of those two elements .

LeetCode Problems Snapshot

Concepts in Problem (Basics)

Return type Function , Argument in Function , Loops , If conditions .

Solving the Two Sum Problem

Now think about it , how you could solve it . If you start adding every possible pairs of the list then you could find those pair 😯 .

Let’s us code this problem in Python 😎

Solution in Python

Here we are making two loops , i and j . In line 3 we starts a loop which is holding the first element at first iteration and in line 4 j holds the 2nd element of the list at first iteration and in line 5 we store the sum of ith and jth . And in next line we check weather those sum are equal to target value or not . If yes then we return the index of that element and break the loop . Otherwise if condition get false again loop will go .

--

--

Yasir
Yasir

Written by Yasir

Exploring Swift, SwiftUI, and Apple Universe.

No responses yet