Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Finding Two Numbers That Sum to a Target Value

Tech Apr 15 45

Given an integer array values and a target integer goal, find the two numbers within the array whose sum equals goal and return their indices.

Example 1:

Input: values = [2,7,11,15], goal = 9
Output: [0,1]
Explanation: values[0] + values[1] == 9.

Example 2:

Input: values = [3,2,4], goal = 6
Output: [1,2]

Example 3:

Input: values = [3,3], goal = 6
Output: [0,1]

Approach 1: Brute Force

Time Complexity: O(n²) Iterate through all possilbe pairs of indices i and j (where j < i) and check if their sum equals the target.

class Solution {
public:
    vector<int> twoSum(vector<int>& values, int goal) {
        vector<int> result;
        for (int i = 0; i < values.size(); ++i) {
            for (int j = 0; j < i; ++j) {
                if (values[i] + values[j] == goal) {
                    result = {j, i};
                    return result;
                }
            }
        }
        return result;
    }
};

Approach 2: Hash Map

Time Complexity: O(n) Utilize a hash map to store each element's value and its index. For each element values[i], check if the complement goal - values[i] already exists in the map.

class Solution {
public:
    vector<int> twoSum(vector<int>& values, int goal) {
        unordered_map<int, int> valueIndexMap;
        for (int i = 0; i < values.size(); ++i) {
            int complement = goal - values[i];
            if (valueIndexMap.find(complement) != valueIndexMap.end()) {
                return {valueIndexMap[complement], i};
            }
            valueIndexMap[values[i]] = i;
        }
        return {};
    }
};
Tags: algorithms

Related Articles

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Comprehensive Guide to Hive SQL Syntax and Operations

This article provides a detailed walkthrough of Hive SQL, categorizing its features and syntax for practical use. Hive SQL is segmented into the following categories: DDL Statements: Operations on...

Leave a Comment

Anonymous

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