#2761

Prime Pairs With Target Sum

Medium
ArrayMathEnumerationNumber TheorySieve of EratosthenesTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log log n)Space O(n)

By using the Sieve of Eratosthenes, we can efficiently find all prime numbers up to n. Then, we can check pairs of primes that sum to n in linear time, significantly improving performance.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use the Sieve of Eratosthenes to generate a list of all prime numbers up to n.
  2. 2Step 2: Store these primes in a set for O(1) lookup time.
  3. 3Step 3: Iterate through the list of primes and for each prime x, check if (n - x) is also prime. If so, add the pair [x, n - x] to the result.
solution.py18 lines
1# Full working Python code
2def sieve_of_eratosthenes(n):
3    is_prime = [True] * (n + 1)
4    is_prime[0], is_prime[1] = False, False
5    for i in range(2, int(n**0.5) + 1):
6        if is_prime[i]:
7            for j in range(i * i, n + 1, i):
8                is_prime[j] = False
9    return [i for i in range(n + 1) if is_prime[i]]
10
11def prime_pairs(n):
12    primes = sieve_of_eratosthenes(n)
13    prime_set = set(primes)
14    result = []
15    for x in primes:
16        if (n - x) in prime_set:
17            result.append([x, n - x])
18    return result

Complexity note: The Sieve of Eratosthenes runs in O(n log log n) time, and we use O(n) space to store the prime numbers.

  • 1Using the Sieve of Eratosthenes allows for efficient prime checking.
  • 2Only check pairs where x <= n/2 to avoid duplicates.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.