#3556

Sum of Largest Prime Substrings

Medium
Hash TableMathStringSortingNumber TheoryHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

Use a sliding window to generate substrings efficiently and a sieve to precompute primes up to a certain limit.

⚙️

Algorithm

3 steps
  1. 1Step 1: Precompute all primes up to 9999999999 using the Sieve of Eratosthenes.
  2. 2Step 2: Generate unique substrings, convert to integers, and check against the precomputed primes.
  3. 3Step 3: Collect unique primes and return the sum of the three largest.
solution.py17 lines
1def sieve_of_eratosthenes(limit):
2    is_prime = [True] * (limit + 1)
3    for i in range(2, int(limit**0.5) + 1):
4        if is_prime[i]:
5            for j in range(i * i, limit + 1, i):
6                is_prime[j] = False
7    return {i for i in range(2, limit + 1) if is_prime[i]}
8
9def sum_of_largest_primes(s):
10    primes = sieve_of_eratosthenes(9999999999)
11    unique_primes = set()
12    for i in range(len(s)):
13        for j in range(i + 1, len(s) + 1):
14            num = int(s[i:j])
15            if num in primes:
16                unique_primes.add(num)
17    return sum(sorted(unique_primes, reverse=True)[:3])

Complexity note: The complexity is reduced by precomputing primes and efficiently generating substrings.

  • 1Unique substrings can generate multiple primes.
  • 2Primality testing can be optimized with precomputation.

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