Sum of Largest Prime Substrings - Solution & Explanation
Problem Statement
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.
Approach Overview
Problem Overview: You are given a numeric string and must examine its substrings to find prime numbers. For each relevant segment, identify the largest prime substring and add those values to a running sum.
Approach 1: Brute Force Substring Enumeration (O(n^3) time, O(1) space)
The direct method generates every possible substring using two nested loops over the string indices. Each substring is converted into an integer and checked for primality using trial division. Prime checking itself costs up to O(sqrt(v)), where v is the substring value, which pushes the total cost close to cubic when many substrings are tested repeatedly. This approach is useful for reasoning about correctness and validating small inputs but becomes slow for larger strings.
Approach 2: Enumeration + Hash Table (O(n^2 * sqrt(v)) time, O(k) space)
The optimized solution still enumerates all substrings using two pointers, but avoids repeated work. A hash table caches results of primality checks so the same numeric substring is never recomputed. During enumeration, build numbers incrementally from left to right to avoid repeated string-to-int conversions. Each candidate is validated with a number theory prime test and compared against the current maximum for that segment. The hash lookup keeps prime validation nearly constant for repeated values, reducing the practical runtime significantly.
String traversal drives the algorithm. The outer loop fixes the start index, and the inner loop expands the substring while updating the numeric value digit by digit. When a prime is found, update the tracked largest value for that region and accumulate it into the final sum. Because substring generation itself is O(n^2), this becomes the dominant cost while the hash table prevents redundant primality checks.
This method balances simplicity and performance. It relies on efficient substring enumeration from the string and constant-time hash lookups to keep the algorithm manageable within typical constraints.
Recommended for interviews: The enumeration + hash table approach is what most interviewers expect. Demonstrating the brute force first shows understanding of substring generation and prime validation. Then improving it with caching and incremental number construction shows awareness of algorithmic bottlenecks and practical optimization.
Solution
We can enumerate all substrings and check whether they are prime numbers. Since the problem requires us to return the sum of the largest 3 distinct primes, we can use a hash table to store all the primes.
After traversing all substrings, we sort the primes in the hash table in ascending order, and then take the largest 3 primes to calculate the sum.
If there are fewer than 3 primes in the hash table, return the sum of all primes.
The time complexity is O(n^2 times \sqrt{M}), and the space complexity is O(n^2), where n is the length of the string and M is the value of the largest substring.
Code
Python
Java
C++
Go
TypeScript
Detailed Complexity Analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Substring Enumeration | O(n^3) | O(1) | Good for understanding the problem or validating small inputs |
| Enumeration + Hash Table (Caching Primes) | O(n^2 * sqrt(v)) | O(k) | General case and typical interview solution |
| Enumeration + Precomputed Prime Sieve | O(n^2 + V log log V) | O(V) | Useful when substring values are bounded and many primality checks are required |
Video Solution
Q1. Sum of Largest Prime Substrings || Biweekly Contest 157 • ExpertFunda • 280 views views
Watch 7 more video solutions →Frequently Asked Questions
Is Sum of Largest Prime Substrings easy or hard?
Sum of Largest Prime Substrings Python/Java solution
How to solve Sum of Largest Prime Substrings in O(n)?
What is the best approach for Sum of Largest Prime Substrings?
Is Sum of Largest Prime Substrings asked at Google/Amazon/Meta?
What data structure is used in Sum of Largest Prime Substrings?
What is the time complexity of Sum of Largest Prime Substrings?
Ready to solve this problem?
Practice Sum of Largest Prime Substrings with our built-in code editor and test cases.
Practice on FleetCode