Problem Link

Description


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.

A prime number is a natural number greater than 1 with only two factors, 1 and itself.

A substring is a contiguous sequence of characters within a string.

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 <= 10
  • s consists of only digits.

Solution


Python3

def is_prime(n: int) -> bool:
    if n <= 1:
        return False
    if n <= 3:
        return True
    if n % 2 == 0 or n % 3 == 0:
        return False
 
    # check for factors from 5 to sqrt(n), skipping even multiples
    for i in range(5, int(math.isqrt(n)) + 1, 6):
        if n % i == 0 or n % (i + 2) == 0:
            return False
 
    return True
 
class Solution:
    def sumOfLargestPrimes(self, s: str) -> int:
        digits = list(map(int, s))
        N = len(digits)
        pq = []
        
        for i in range(N):
            curr = 0
            for j in range(i, N):
                curr = curr * 10 + digits[j]
                if is_prime(curr):
                    if curr in pq: continue
                        
                    if len(pq) == 3:
                        heappushpop(pq, curr)
                    else:
                        heappush(pq, curr)
 
        return sum(pq)