Sum of Largest Prime Substrings Problem
Description
LeetCode Problem 3556.
Given a string s, find the sum of the 3 largest unique prime numbers that can be formed using any of its substrings.
Return the sum of the three largest unique prime numbers that can be formed. If fewer than three exist, return the sum of all available primes. If no prime numbers can be formed, return 0.
Note: Each prime number should be counted only once, even if it appears in multiple substrings. Additionally, when converting a substring to an integer, any leading zeros are ignored.
Example 1:
Input: s = "12234"
Output: 1469
Explanation:
- The unique prime numbers formed from the substrings of "12234" are 2, 3, 23, 223, and 1223.
- The 3 largest primes are 1223, 223, and 23. Their sum is 1469.
Example 2:
Input: s = "111"
Output: 11
Explanation:
- The unique prime number formed from the substrings of "111" is 11.
- Since there is only one prime number, the sum is 11.
Constraints:
1 <= s.length <= 10sconsists of only digits.
Solution
Approach: Enumerate Substrings
The string has at most 10 digits, so there are at most 55 substrings and each is below 1010. Build the value of every substring, test it for primality by trial division up to its square root, and put the primes in a set so that equal values are counted once. Leading zeros are fine: "07" is the number 7.
Sort the distinct primes and add up the largest three, or all of them if there are fewer than three (zero if there are none).
Complexity: O(n2 * sqrt(M)) time, where M is the largest substring value, and O(n2) extra space.
class Solution:
def sumOfLargestPrimes(self, s: str) -> int:
def is_prime(x: int) -> bool:
if x < 2:
return False
return all(x % i for i in range(2, int(x ** 0.5) + 1))
st = set()
n = len(s)
for i in range(n):
x = 0
for j in range(i, n):
x = x * 10 + int(s[j])
if is_prime(x):
st.add(x)
return sum(sorted(st)[-3:])