LeetCode 2761: Prime Pairs With Target Sum Solution

Master LeetCode problem 2761 (Prime Pairs With Target Sum), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2761. Prime Pairs With Target Sum

Problem Explanation

Explanation

To solve this problem, we can iterate through all possible pairs of prime numbers less than or equal to n, check if their sum equals n, and add them to the result list if they satisfy the conditions. We can generate a list of prime numbers using the Sieve of Eratosthenes algorithm to optimize the process of finding prime numbers. Time complexity for generating primes using the Sieve of Eratosthenes is O(n*log(log(n))), and the time complexity for finding prime pairs is O(n^2). The space complexity is O(n) for storing the list of prime numbers.

Solution Code

import java.util.*;

class Solution {
    public List<List<Integer>> primePairsWithTargetSum(int n) {
        List<List<Integer>> result = new ArrayList<>();
        boolean[] isPrime = new boolean[n + 1];
        Arrays.fill(isPrime, true);
        
        for (int p = 2; p * p <= n; p++) {
            if (isPrime[p]) {
                for (int i = p * p; i <= n; i += p) {
                    isPrime[i] = false;
                }
            }
        }
        
        List<Integer> primes = new ArrayList<>();
        for (int i = 2; i <= n; i++) {
            if (isPrime[i]) {
                primes.add(i);
            }
        }
        
        for (int i = 0; i < primes.size(); i++) {
            for (int j = i; j < primes.size(); j++) {
                if (primes.get(i) + primes.get(j) == n) {
                    List<Integer> pair = new ArrayList<>();
                    pair.add(primes.get(i));
                    pair.add(primes.get(j));
                    result.add(pair);
                }
            }
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2761 (Prime Pairs With Target Sum)?

This page provides optimized solutions for LeetCode problem 2761 (Prime Pairs With Target Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2761 (Prime Pairs With Target Sum)?

The time complexity for LeetCode 2761 (Prime Pairs With Target Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2761 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2761 in Java, C++, or Python.

Back to LeetCode Solutions