We use cookies to improve your experience. If you continue to use our site, we'll assume that you're happy with it. :)

Two Sum (LeetCode Problem)

Every programmer want to compete with each other and each other means every other coder who is stronger than other.


Beginners do one big mistake, they open any platform like LeetCode, HackerRank or HackerEarth and think that they can become champion is 1 days.
To start these platforms you should have two basic understanding:
One is Knowledge About Any One Programming Language.
Second is you have at least Basic Knowledge of Data Structures.

After the basic knowledge you can start your problem solving journey. This is first blog on problem solving, will come tons of more ahead so you should be able to understand solutions very easily.

First step to this competitive programming is to stick with one platform and have knowledge about basics.
Second step is open problem and try to understand that problem.
Third step is write pseudo code on notebook that how you are going to solve that problem.
Fourth step is Write code and try to figure out each cases.

Now, lets get in to our problem i.e. Two Sum.
Note:- Problem's solution will be in Python.
In this problem you have given an array and a target value, your task is search in your array and find two numbers whose sum will be the target.
So, lets start coding:-
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        size = len(nums)
        for i in range(size):
            for j in range(i+1, size):
                if nums[j] == target - nums[i]:
                    return [i,j]     
This is the solution of this problem let's understand each line, First solution class is
created for this line you have at least basic knowledge of OOPs.
Then twoSum method is created and in that array and target is passed.
After that size of array is calculated and stored in variable named size.
Then a for loop is used in range of size(means it will perform on size of the variable), then inner
loop is created from one size incremented from first to same length of loop.
Then checking if second number is equal to target - first or not, if equal print both numbers.

And Booyah! you get the solution, it was too easy write.

Post a Comment