Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Finding Two Numbers That Sum to a Target Value

Tech 2

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

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

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...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

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