CSES Sum of Two Values

Author: Michael Cao

Given an array of nn elements, you are asked to find two values which sum to xx.

Main Idea

Let's start by iterating over the first value in O(n)\mathcal{O}(n) time. Given one value, aa, the other value must be xax - a unless a>xa > x (in which case aa cannot be a valid first value).

So the question reduces to, given some value aa, does some other value xax - a exist?

Using a Map

One idea that comes to mind would be to used a boolean array to store the values. Unfortunately, since ai109a_i \leq 10^9, this approach isn't feasible.

However, we can store the values in an (un)ordered map which maps each value to an index, and use the .count method to check whether a value exists, and return the corresponding index if it does.

To be careful not to count the same index twice, we'll add values to the map as we iterate through it, so at some index ii you only consider values with index j<ij < i.

C++

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
#define pb push_back
#define rsz resize
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
using pi = pair<int,int>;
#define f first

Give Us Feedback on CSES Sum of Two Values!