An algorithm to solve a simple? array problem
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
Array problems are a staple in algorithm and data structure coursework due to their versatility and importance in computational efficiency. They provide a rich ground for developing fundamental skills like indexing, iterating, and manipulating data structures. In this article, we will delve into an elegant algorithm for addressing a basic array challenge: finding all unique pairs in an array whose elements sum up to a target value. This problem encapsulates essential concepts in array manipulation and algorithm design, and its solution showcases effective time-complexity management.
Problem Definition
Given an integer array `A` and an integer `target`, find all unique pairs `(i, j)` such that `A[i] + A[j] = target`, with `i < j`. This constraint ensures each pair is only encountered once and simplifies the problem by guaranteeing order.
Input
- An integer array `A` of size `n`.
- An integer `target`.
Output
A list of tuples, each representing the indices of the array elements that form the required sum.
Algorithm Description
To solve this problem efficiently, we want to avoid the naive time complexity solution that involves checking all possible pairs. Instead, we can utilize a hash table to achieve an solution.
Steps
- Initialize a `Hash` Table (Complement): Use a dictionary to store elements as keys and their indices as values. This will help us determine if the complement of `A[i]` (i.e., `target - A[i]`) exists in the array quickly.
- Iteration Over the Array: Iterate through each element while calculating its complement: • For each element `A[i]`, compute the complement as `complement = target - A[i]`. • Check if `complement` exists in the hash table and if its index precedes `i`. • If both conditions hold, store the indices as a valid pair and update the hash table. • If not, add `A[i]` to the hash table.
- Return the Result: After processing, return all collected index pairs.
Example
Let's walkthrough the algorithm with an example:
• Initialize: `complement_map = {}` • Step 1: (i=0) `complement = 6 - 2 = 4` • Update: `complement_map = {2: 0}` • Step 2: (i=1) `complement = 6 - 4 = 2` • Find 2 in `complement_map` at index 0, append (0, 1) • Update: `complement_map = {2: 0, 4: 1}` • Step 3: (i=2) `complement = 6 - 3 = 3` • Update: `complement_map = {2: 0, 4: 1, 3: 2}` • Step 4: (i=3) `complement = 6 - 7 = -1` • Update: `complement_map = {2: 0, 4: 1, 3: 2, 7: 3}` • Step 5: (i=4) `complement = 6 - 5 = 1` • Update: `complement_map = {2: 0, 4: 1, 3: 2, 7: 3, 5: 4}` • Step 6: (i=5) `complement = 6 - 1 = 5` • Find 5 in `complement_map` at index 4, append (4, 5) • Time Complexity: The algorithm processes each element exactly once, leading to a linear time complexity of . • Space Complexity: The space complexity is because of the additional storage needed for the hash table. In the worst case, each element is stored. • K-sum Problems: For larger , like 3SUM, the problem becomes significantly more challenging and usually requires a nested loop with two-level hash tables or additional space-time trade-offs. • Handling Negative Numbers: Although simple summation problems work with any integers, real applications might require adjustments when dealing with mixed sign datasets. • Edge Cases: Consider empty arrays or arrays with fewer than two elements where the problem limits cannot be satisfied. • Integrity Checks: Ensure the input array and target are valid (e.g., non-null, containing valid integers).
Related reading
- An algorithm to space out overlapping rectangles?
- An efficient compression algorithm for short text strings
- An efficient sorting algorithm for almost sorted list containing time data?
- An efficient way to compute mathematical constant e
- An efficient way to Base64 encode a byte array?
- An elegant way to consume all bytes of a BinaryReader?
- An implementation of Sharir's or Aurenhammer's deterministic algorithm for calculating the intersection/union of 'N' circles
- An interesting Google interview algorithm I found online that requires linear time

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.