CARVIEW |
Select Language
HTTP/2 200
date: Mon, 13 Oct 2025 03:46:11 GMT
content-type: text/html; charset=utf-8
content-encoding: gzip
cache-control: public, max-age=86400
referrer-policy: strict-origin-when-cross-origin
x-app-version: v251008-h-251010-1202
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
x-robots-tag: all
etag: W/"5g98dytdicl2ip"
x-cloud-trace-context: dabeaab608156436464f1b788a02bc7e
via: 1.1 google
vary: Accept-Encoding
alt-svc: h3=":443"; ma=86400
cf-cache-status: MISS
set-cookie: __cf_bm=PEQeDcXlfNhCebFc0bW7_rPYQu2gxaW7oa5cK2Pbt54-1760327171-1.0.1.1-jbyi8Iv9u4TOqFVuup6ZOY0ztDStCsKB4Y6yXpRop1R6JjFU4T0oW5qEPUUV538hQgHkdxVuOh629B7GyhnxBWVNvbBCqOMyy6MlVZlsFH8; path=/; expires=Mon, 13-Oct-25 04:16:11 GMT; domain=.educative.io; HttpOnly; Secure; SameSite=None
strict-transport-security: max-age=31536000; includeSubDomains; preload
server: cloudflare
cf-ray: 98dbd90fcd833e92-BLR
Sum of Two Values
![editor-page-cover]()

Sum of Two Values
Problem Statement
Given an array of integers and a value, determine if there are any two integers in the array whose sum is equal to the given value. Return true if the sum exists and return false if it does not.
Consider this array and the target sums:
Hints
- Use hashing
- Use comparison between elements
Try it yourself
bool find_sum_of_two(vector<int>& A, int val) {//TODO: Write - Your - Codereturn false;}
Solution
bool find_sum_of_two(vector<int>& A, int val) {unordered_set<int> found_values;for (int& a : A) {if (found_values.find(val - a) != found_values.end()) {return true;}found_values.insert(a);}return false;}int main() {vector<int> v = {5, 7, 1, 2, 8, 4, 3};vector<int> test = {3, 20, 1, 2, 7};for(int i=0; i<test.size(); i++){bool output = find_sum_of_two(v, test[i]);cout << "find_sum_of_two(v, " << test[i] << ") = " << (output ? "true" : "false") << endl;}return 0;}
Solution Explanation
Runtime Complexity
The runtime complexity of this solution is linear, O(n).
Memory Complexity
The memory complexity of this solution is linear, O(n).
Solution Breakdown
In this solution, you can use the following algorithm to find a pair that add up to the target (say val
).
- Scan the whole array once and store visited elements in a hash set.
- During scan, for every element
e
in the array, we check ifval
-e
is present in the hash set i.e.val
-e
is already visited.- If
val
-e
is found in the hash set, it means there is a pair (e
,val
-e
) in array whose sum is equal to the givenval
. - If we have exhausted all elements in the array and didn’t find any such pair, the function will return
false
.
- If
Practice problems like this and many more by checking out our Grokking the Coding Interview: Patterns for Coding Questions course!
TRENDING TOPICS
LEGAL
Cookie Settings