# Interview Question – “Two Sum” problem

One of the most popular programming interview questions at Google is the “Two Sum” problem. The problem is simple in theory but requires a well-structured and optimized solution. The question asks for an algorithm that can find two numbers in an array that add up to a target sum.

Problem Statement:

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:

Solution:

The brute-force solution to this problem is to have two nested loops, where the outer loop will iterate through each element of the array, and the inner loop will iterate through the rest of the elements to check if any two numbers add up to the target sum. This solution has a time complexity of O(n^2), which is not very efficient for large inputs.

A more optimized solution is to use a HashMap to store the previously encountered numbers and their indices. We iterate through the array once and for each element, we check if its complement (i.e., the difference between the target and the current element) exists in the HashMap. If it does, we return the current index and the index of the complement from the HashMap. Otherwise, we add the current element and its index to the HashMap.

Here is the implementation of the optimized solution in Java:

The time complexity of this solution is O(n), as we are iterating through the array only once, and the space complexity is O(n), as we are using a HashMap to store the numbers and their indices.

In conclusion, the “Two Sum” problem is a classic interview question that tests a candidate’s problem-solving skills and their ability to write an optimized algorithm. By using a HashMap to store previously encountered numbers, we can find the solution to this problem in linear time complexity, which is an efficient and optimized approach.

Article Rating
Subscribe
Notify of 