Solution 1 - Hashmap
Using a hash map, we can store the numbers in the array as keys and their indices as values. To check if a pair exists, we use the hashmap to quickly look up if any past value plus the current one equals . If so, we output the current index and the one stored in the hashmap.
Implementation
Time Complexity:
Warning!
The below code TLEs on a couple test cases due to anti-hashing test cases on CSES.
n, x = map(int, input().split())nums = list(map(int, input().split()))m = {}for i, a in enumerate(nums):if x - a in m:print(i + 1, m[x - a] + 1)breakm[a] = ielse:print("IMPOSSIBLE")
Solution 2 - Two Pointers
We can sort the array and use a left pointer and right pointer. If the sum is greater than , we decrement right. If the sum is less than , we increment left.
Implementation
Time Complexity:
n, x = map(int, input().split())nums = [(int(val), i) for i, val in enumerate(input().split())]nums.sort()l = 0r = n - 1while l < r:sum = nums[l][0] + nums[r][0]if sum == x:
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!