Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Solving the Two Sum Problem in Java

Notes May 13 1

Given an array of integers nums and an integer target, return the indices of two numbers that add up to the target value.

Example:

Input: nums = [3, 4, 2], target = 6
Output: [1, 2]
Explanation: nums[1] + nums[2] equals 6

Approaches

  1. Brute Force Method:

    • Iterate through each element and check every other element for a matching sum
    • Time complexity: O(n²)
  2. Hash Map Optimization:

    • Use a hash map to store values and indices as we iterate
    • Check if the complement (target - current value) exists in the map
    • Time complexity: O(n)

Java Implementations

Brute Force Solution:

public int[] findTwoSum(int[] numbers, int sumTarget) {
    for (int first = 0; first < numbers.length; first++) {
        for (int second = first + 1; second < numbers.length; second++) {
            if (numbers[first] + numbers[second] == sumTarget) {
                return new int[]{first, second};
            }
        }
    }
    return new int[0];
}

Optimized Hash Map Solution:

import java.util.HashMap;

public int[] optimizedTwoSum(int[] numbers, int sumTarget) {
    HashMap<Integer, Integer> valueIndexMap = new HashMap<>();
    for (int current = 0; current < numbers.length; current++) {
        int complement = sumTarget - numbers[current];
        if (valueIndexMap.containsKey(complement)) {
            return new int[]{valueIndexMap.get(complement), current};
        }
        valueIndexMap.put(numbers[current], current);
    }
    return new int[0];
}

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.