How to solve two sum problem in Java? [Solved]
Tags: java, programming, algorithms, coding
Published: 2021-12-22 07:24:11

---
title: How to solve two sum problem in Java? [Solved]
published: true
description: Two sum problem is an interesting array based coding problem where you need to find two pairs whose sum equals to given number. This article shows multiple ways to solve two sum problem in Java.
tags: java, programming, algorithms, coding
//cover_image: https://direct_url_to_image.jpg
---
*Disclosure: This post includes affiliate links; I may receive compensation if you purchase products or services from the different links provided in this article.*

[![14 Patterns to Ace Any Coding Interview Question](https://miro.medium.com/max/1400/1*nHQAymrct6Z7RGlK53T_oA.png)](https://www.educative.io/courses/grokking-the-coding-interview?affiliate_id=5073518643380224)


Hello Devs, if you have been solving [data structure and algorithms problems](https://medium.com/javarevisited/50-data-structure-and-algorithms-interview-questions-for-programmers-b4b1ac61f5b0) or been through a couple of coding interviews then you might be familiar with the classical **"Two Sum" problem**.

It's one of the classical coding problems of **finding two numbers in a given array whose sum is equal to a given target number**. It's a good problem to learn [how array data structure works](https://www.java67.com/2013/08/ata-structures-in-java-programming-array-linked-list-map-set-stack-queue.html) and programming basics like loops, conditionals, and operators.

It's also good for developing your problem-solving skills and coding sense, which will help you in the long run. This is also a popular leetcode problem and commonly asked on [coding interviews](https://javarevisited.blogspot.com/2020/04/5-essential-skills-to-crack-coding-interviews.html) to both beginners and intermediate programmers.

In this article, I will show you the simplest possible solution to for this problem to kick-start your journey on solving [array-based coding problems](https://medium.com/javarevisited/20-array-coding-problems-and-questions-from-programming-interviews-869b475b9121). Before we talk about the solution, let's revisit the problem statement again:

> **Problem Statement:**
> Given an array of integers, find two numbers such that they add up to a specific target number.

The method `twoSum(int[] input, target) `should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (`both index1 and index2)` are not zero-based.

Note: You may assume that each input would have exactly one solution.

Example
**[12,17,21,25], 29 -> [1,2]**

In order to solve this problem, a basic knowledge of [array data structure](https://www.java67.com/2014/08/what-is-array-data-structure-in-java.html) and algorithms is experienced. You should also be familiar with Big O notation to calculate time and space complexity.

If you are new to Data Structure and need a course to refresh your knowledge, I highly recommend you check out [**Data Structures and Algorithms: Deep Dive Using Java**](https://click.linksynergy.com/fs-bin/click?id=JVFxdTr9V80&subid=0&offerid=323058.1&type=10&tmpid=14538&RD_PARM1=https%3A%2F%2Fwww.udemy.com%2Fdata-structures-and-algorithms-deep-dive-using-java%2F) to build a foundation. This is a good course to learn data structure and algorithms using Java programming language.

------


## How to solve Two Sum Problem in Java
Here is our complete solution of two sum array problem in Java. This is a brute force way to solve the problem where we *start with the first element in the array* and then check all other numbers in the array to find the pairs which add to the target value.

![How to solve Two Sum Problem in Java](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ysjry5snc0s6x2wj4lxp.png)
 

This is not the most efficient way to solve this problem but it works and that should be your first goal in the interview as well as in real-life scenarios.

> **First, solve the problem and then optimize it.**

The time complexity of this solution is **quadratic O(N²)** and if you are asked this problem during the interview then you should also know tricks to reduce time complexity which I have left as an exercise for you.

Good knowledge of data structure, algorithms, and common coding patterns helps you to find alternative solutions and reduce the time complexity. And, that's why I highly recommend every programmer to go through [**Grokking the Coding Interview: Patterns for Coding Questions**](https://www.educative.io/collection/5668639101419520/5671464854355968?affiliate_id=5073518643380224) course on Educative.

[![](https://miro.medium.com/max/700/1*FQ-ViFyF9nQTQzTP4hcsVA.png)](https://www.educative.io/collection/5668639101419520/5671464854355968?affiliate_id=5073518643380224)

This is one of its kind courses that teaches you some common coding patterns like sliding window, merge interval, [fast and slow pointers](https://javarevisited.blogspot.com/2016/07/how-to-find-3rd-element-from-end-in-linked-list-java.html), two points, and many others which can be used to solve hundreds of coding problems. If you are preparing for coding interviews, I highly recommend you to learn these patterns.

You can either buy this course or you can get an [**Educative subscription**](https://www.educative.io/subscription?affiliate_id=5073518643380224) on $18 per month which provides access to many useful courses for coding interviews like [Grokking the System Design Interview](https://www.educative.io/collection/5668639101419520/5649050225344512?affiliate_id=5073518643380224) and [Grokking the Dynamic Programming Patterns](https://www.educative.io/collection/5668639101419520/5633779737559040?affiliate_id=5073518643380224). I highly recommend this subscription to the programmer preparing for job interviews.

By the way, I have also written unit tests to test the logic in our code but I haven't tested for all scenarios. 

You can add more test in given JUnit function and test that if our solution works on boundary conditions like an array with zero elements, array with no pair for a sum, [an array with two pairs of given sum](https://javarevisited.blogspot.com/2014/08/how-to-find-all-pairs-in-array-of-integers-whose-sum-equal-given-number-java.html#axzz6acuPCYTR), and array with exactly one pair of elements for the given sum.

When you run this program it will run fine and doesn't throw any error because the `twoSum()` method will return an array with {1, 2} which matches the expected output in the `assertArrayEquals()` method.

These are actually indices of actual numbers in the input array which adds to the target value.

For example, the target value in our case is 29 and the first and second element (12 + 17) adds to 29. *Since the question asked to return indices that are not zero-based we are adding one into indices and returning them.*

If you want to play just change the array input or expected output and you will start seeing errors as shown below:

[![](https://miro.medium.com/max/633/0*Ywpg0dRMN5h6Qz79.png)](https://click.linksynergy.com/deeplink?id=JVFxdTr9V80&mid=39197&murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fmaster-the-coding-interview-data-structures-algorithms%2F)

That's all about **how to solve two sum problem in Java**.This is the brute force way to solve the problem and the time complexity of this problem is O(n²) because of two loops we have in our code. We are checking each element with every other element in the array to find the matching pair.

Can you find a more clever way to solve the problem and reduce the time complexity to `O(nlogn)` or maybe O(N)?


Other **Coding Interview Questions** you may like
-   5 Essential Skills to Crack Coding Interviews ([skills](https://javarevisited.blogspot.com/2020/04/5-essential-skills-to-crack-coding-interviews.html))
-   How to Print duplicate characters from String? ([solution](http://java67.com/2014/03/how-to-find-duplicate-characters-in-String-Java-program.html))
-   How to Find duplicate characters in a String? ([solution](http://java67.blogspot.sg/2014/03/how-to-find-duplicate-characters-in-String-Java-program.html))
-   50+ Data Structure and Algorithms Interview Questions ([list](https://dev.to/javinpaul/50-data-structure-and-algorithms-problems-from-coding-interviews-4lh2))
-   How to Check if String is Palindrome? ([solution](http://java67.blogspot.com/2015/06/how-to-check-is-string-is-palindrome-in.html))
-   30 array-based coding problems from interviews ([questions](https://javarevisited.blogspot.com/2015/06/top-20-array-interview-questions-and-answers.html))
-   Find the highest occurred character in a String? ([solution](http://www.java67.com/2015/10/java-program-to-find-repeated-words-and-count.html))
-   Check if a String contains only digits? ([solution](http://javarevisited.blogspot.sg/2012/10/regular-expression-example-in-java-to-check-String-number.html))
-   10 Data Structure and Algorithms courses for Interviews ([courses](https://medium.com/hackernoon/10-data-structure-algorithms-and-programming-courses-to-crack-any-coding-interview-e1c50b30b927))
-   How to reverse String in Java using Iteration and Recursion? ([solution](http://javarevisited.blogspot.sg/2012/01/how-to-reverse-string-in-java-using.html))
-   Count the occurrence of a given character in String? ([solution](http://javarevisited.blogspot.sg/2012/12/how-to-count-occurrence-of-character-in-String.html))
-   My favorite free course to learn Data Structure and Algorithms ([courses](https://www.freecodecamp.org/news/these-are-the-best-free-courses-to-learn-data-structures-and-algorithms-in-depth-4d52f0d6b35a/))
-   Convert numeric string to an int? ([solution](http://javarevisited.blogspot.com/2011/08/convert-string-to-integer-to-string.html))
-   Reverse words in a sentence without using a library method? ([solution](http://java67.com/2015/06/how-to-reverse-words-in-string-java.html))
-   Reverse a String in place in Java? ([solution](http://javarevisited.blogspot.sg/2016/03/how-to-reverse-string-in-place-in-java.html))
-   Count the number of vowels and consonants in a String? ([solution](http://java67.blogspot.sg/2013/11/how-to-count-vowels-and-consonants-in-Java-String-word.html))
-   Find the first non-repeated character from String? ([solution](http://javarevisited.blogspot.sg/2014/03/3-ways-to-find-first-non-repeated-character-String-programming-problem.html))
-   7 Best Data Structure and Algorithms Courses ([best courses](https://medium.com/javarevisited/7-best-courses-to-learn-data-structure-and-algorithms-d5379ae2588))

Thanks for reading this article so far. If you like these two sums array-based coding problems then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.

**P. S. --- **If you are preparing for a Programming Job Interview and you need more such questions, you can check the [**Master the Coding Interview: Data Structures + Algorithms**](https://click.linksynergy.com/deeplink?id=JVFxdTr9V80&mid=39197&murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2Fmaster-the-coding-interview-data-structures-algorithms%2F) by Andrei Neagoie on Udemy. This is a great course to build and level up your Data Structure and Algorithms skills and crack the coding interview