Skip to content

add two sum problem #4364

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Sep 12, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
improve code
  • Loading branch information
BamaCharanChhandogi committed Sep 10, 2023
commit 231db9977d3932ae8ac801de18f85fc2789b95b5
8 changes: 5 additions & 3 deletions src/main/java/com/thealgorithms/misc/TwoSumProblem.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package com.thealgorithms.misc;

import java.util.*;
import java.util.HashMap;

public class TwoSumProblem {
public final class TwoSumProblem {
private TwoSumProblem() {
}
/**
* The function "twoSum" takes an array of integers and a target integer as input, and returns an
* array of two indices where the corresponding elements in the input array add up to the target.
Expand All @@ -11,7 +13,7 @@ public class TwoSumProblem {
* @return The method `twoSum` returns an array of integers.
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
public static int[] twoSum(int[] arr, int target) {
public static int[] twoSum(final int[] arr, final int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
int rem = target - arr[i];
Expand Down
8 changes: 8 additions & 0 deletions src/test/java/com/thealgorithms/misc/TwoSumProblemTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ void testTwoSumMultipleSolutions() {
int[] result = TwoSumProblem.twoSum(nums, target);
assertArrayEquals(expected, result);
}
@Test
void testTwoSumMultipleSolution() {
int[] nums = {3, 4, 3, 3};
int target = 6;
int[] expected = {0, 2}; // nums[0] + nums[2] = 3 + 3 = 6
int[] result = TwoSumProblem.twoSum(nums, target);
assertArrayEquals(expected, result);
}

@Test
void testTwoSumNegativeNumbers() {
Expand Down