Sum of Largest Prime Substrings - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: s = "1237"
Output: 67
💡 Note: Substrings: 1, 12, 123, 1237, 2, 23, 237, 3, 37, 7. Prime numbers: 2, 3, 7, 23, 37. Top 3 largest: 37, 23, 7. Sum: 37 + 23 + 7 = 67
Example 2 — With Leading Zeros
$ Input: s = "0023"
Output: 28
💡 Note: Substrings after converting (ignoring leading zeros): 0, 2, 23, 3. Prime numbers: 2, 3, 23. Top 3: 23 + 3 + 2 = 28
Example 3 — No Primes
$ Input: s = "4689"
Output: 0
💡 Note: All possible substrings result in composite numbers or 1. No prime numbers can be formed, so return 0

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of digits only ('0'-'9')

Visualization

Tap to expand
Sum of Largest Prime Substrings INPUT String s = "1237" 1 2 3 7 0 1 2 3 All Substrings: "1", "2", "3", "7" "12", "23", "37" "123", "237" "1237" Convert to integers: 1,2,3,7,12,23,37,123,237,1237 ALGORITHM STEPS 1 Generate Substrings Extract all possible substrings 2 Filter Primes Check each number for primality Prime Check Results: 1 - NOT prime 2 - PRIME 3 - PRIME 7 - PRIME 12 - NOT prime 23 - PRIME 37 - PRIME 123,237,1237 - NOT 3 Sort Descending Unique primes: 37, 23, 7, 3, 2 4 Sum Top 3 Take 3 largest: 37 + 23 + 7 37 + 23 + 7 = 47 (Largest 3 unique primes) FINAL RESULT All Unique Primes Found: 37 #1 23 #2 7 #3 3,2 others Sum of Top 3 Largest: 37 + 23 + 7 = 47 OUTPUT 47 OK - Verified Key Insight: Use a Set to store unique primes, avoiding duplicates from overlapping substrings. Optimized prime checking: only test divisors up to sqrt(n). For small numbers, trial division is efficient. Time Complexity: O(n^2 * sqrt(max_val)) where n is string length. Space: O(n^2) for substrings. TutorialsPoint - Sum of Largest Prime Substrings | Optimized Prime Generation
Asked in
Google 15 Microsoft 12 Amazon 8
5.7K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen