Two Sum Problem: Python Solution of Two sum problem of Given List29 Aug 2024 | 5 min read In this tutorial, we will implement the two sum problem using Python code. This is the basic problem of the array, and you can found on this on Leetcode. We will solve it using a different approach using the Python programming language. Let's understand the problem statement. Problem StatementIn this problem, we need to find the pair of the two elements from the given list whose sum is equal to the given target value. We can assume that the array has only one pair of integers that add up to the target sum. Note - A given list or array must be sorted in increasing manner.Example - 1 Output: [1, 5] Example - 2 Output: [2, 3] Let's solve this problem using the Brute Force approach. Approach - 1: Brute Force ApproachThe brute force approach is a commonly used way to solve the problem. In this approach, our primary goal is to solve the problem, not efficiently. We check every possible pair and the number of possible pairs in the array. We will use the two for loop, add the two values, and compare the target value. If it is equal to the target value, return the indices of pairs of the integer. Algorithm -
Let's implement the algorithm using Python code. Implementation of Two Sum ProblemExample - Output: [0, 3] Explanation - In the above program, we have created the TwoSum class and initialized the two variables list1 and target. Then, we declare the solution() method where first we checked the length of the list and applied two for loops. The first for loop is to maintain the first index, and the second for loop is to maintain the second index. We checked the sum of both values; if it is true; we assigned a new list and returned the indices of the elements. Example - 2: Output: [1, 2] Approach -2: Using DictionaryOutput: [1, 0] Explanation - In this approach, we created the TwoSum class, and inside it, we declare the solution() method. In this method, we declared a dictionary to keep track of all the values seen so far in the value to the index. Now, we iterate the given list using the enumerated. Then, we subtract the num value from the target value to search its pair. If the pair is found, return the index of both numbers. Otherwise, add it to our dictionary for a future visit. Time Complexity of Two Number Sums (Brute Force Approach)We need to use the two for loops. The first for loop visits n numbers of elements and second for loop visits n-1. Hence, the check for the possible and total number of pair are: N*(N-1)/2, the time-complexity will be O(N*N) = N2. Space Complexity 0(1): Only constant space for variable is used. Using the dictionary, it takes only one for loop so the time complexity will be the O(N). Approach - 3: Using Two PointersIn this approach, we will use the binary search algorithm where the given list array must be sorted. We need to fix the first index and then the required value to fulfill the target found in the list. We will use the two pointers: left and right; the left denotes the first element, and the right denotes the last element of the list. Then we compare the sum of the pointer's value to the target value; if some of the value and target is equal, return the pointers index pairs. If the sum of value is more than the target, we decrement the right pointer. Otherwise, some of the value is less than the target; we need to increase the left pointer by one and check the same conditions. Let's understand the following example. Example - Output: [2, 3] Time Complexity using Two SumThe time complexity will be O(n) even in the worst case, we visit all the elements in the array only once. Space complexity 0(1): Only constant space for the variable is used. Using the dictionary, it takes only one for loop so that the time complexity will be the O(n). ConclusionIt is a basic and commonly asked programming question in the interview. In this tutorial, we have covered three approaches to solving the two sum problem. We recommend implementing the above approaches independently and practicing such questions to crack coding interviews. |
In this module, we will create a Python code for rotating the screen and put it into use with a GUI. Using some of the functions from the rotatescreen module, a simple Python library for rotating the screen in a system, the display may be changed to...
4 min read
We will learn how to add and use a table in our PyQt5 application in this tutorial. A table is a row-and-column data layout that is often used in data analysis, research, and communication. QTableWidget allows us to add one or more tables to our PyQt...
6 min read
As Data Scientists, we may not stick to data format. PDFs, short for Portable Document Format files, are a good source of data. There are many organizations that release their data in PDFs only. As Artificial Intelligence is expanding, we require more data for prediction and...
3 min read
What is Sentiment Analysis Sentiment analysis, likewise referred to as opinion mining, is a way to deal with natural language processing (NLP) that distinguishes the emotional tone behind a group of text. This is a well-known way for determines to decide and classify opinion about an item,...
5 min read
You might need to locate the first item in a Python iterable, like a list or dictionary, that meets a specific requirement at an indeterminate point in your Python trip. The sole exception is when it is necessary to confirm "that a" specific item is present in...
13 min read
| Balanced Parenthesis Problem in Python In this tutorial, we will learn how to check the balance of the given parentheses in Python. It is a basic interview question where you are asked to find whether a given string (of brackets) is balanced or not. It...
6 min read
? In a classroom full of students, there is a high possibility of at least two students having the same name. How do we refer to those students? We'll use the last name or surname that identifies each person uniquely. In the Python classroom of objects, there...
10 min read
Project ideas for Beginners in Python The greatest approach to learn any programming language or piece of technology is to create projects. Currently, Python is the most well-liked and challenging language. We can put ourselves to the test by creating the code for a specific project. It...
7 min read
In this tutorial, we will learn how we can create shallow copy and deep copy using the Python script. Generally, we use the = (assignment operator) to create a copy of the Python object. Let's understand the full concept related to creating copies in Python. Copy in...
5 min read
One of the most widely used programming languages is Python. We can use Python for anything with its easily understandable syntax, high efficiency, and top-notch open-source libraries. However, we may have noticed that some individuals favor Python 2, whereas others favor Python 3. The difference between the...
2 min read
We request you to subscribe our newsletter for upcoming updates.
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India