CSES - Sum of Two Values
Authors: Michael Cao, DRGSH, Benjamin Qi
Appears In
Given an array of elements, you are asked to find two values which sum to .
Main Idea
Let's start by iterating over the first value in time. Given one value, , the other value must be unless (in which case cannot be a valid first value).
So the question reduces to, given some value , does some other value exist?
One idea that comes to mind would be to used a boolean array to store the values. Unfortunately, since , this approach isn't feasible.
Python
However, we can store the values in a dictionary which maps each value to an index, and use the __contains__
dunder method to check whether a value exists, and return the corresponding index if it does.
C++
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.
Java
However, we can store the values in a map which maps each value to an index, and use the .containsKey
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 you only consider values with index .
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
Python
import sysn,x = map(int,input().split())a = [int(x) for x in input().split()]val_to_ind = {}for i,val in enumerate(a):if x-val in val_to_ind:# equivalent to val_to_ind.__contains__(x-val)print(i+1,val_to_ind[x-val])sys.exit(0)val_to_ind[val] = i+1print("IMPOSSIBLE")
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!