Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
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:
"12234" are 2, 3, 23, 223, and 1223.Example 2:
Input: s = "111"
Output: 11
Explanation:
"111" is 11.Constraints:
1 <= s.length <= 10s consists of only digits.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Math
"12234"
"111"
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3556: Sum of Largest Prime Substrings
class Solution {
public long sumOfLargestPrimes(String s) {
Set<Long> st = new HashSet<>();
int n = s.length();
for (int i = 0; i < n; i++) {
long x = 0;
for (int j = i; j < n; j++) {
x = x * 10 + (s.charAt(j) - '0');
if (is_prime(x)) {
st.add(x);
}
}
}
List<Long> sorted = new ArrayList<>(st);
Collections.sort(sorted);
long ans = 0;
int start = Math.max(0, sorted.size() - 3);
for (int idx = start; idx < sorted.size(); idx++) {
ans += sorted.get(idx);
}
return ans;
}
private boolean is_prime(long x) {
if (x < 2) return false;
for (long i = 2; i * i <= x; i++) {
if (x % i == 0) return false;
}
return true;
}
}
// Accepted solution for LeetCode #3556: Sum of Largest Prime Substrings
func sumOfLargestPrimes(s string) (ans int64) {
st := make(map[int64]struct{})
n := len(s)
for i := 0; i < n; i++ {
var x int64 = 0
for j := i; j < n; j++ {
x = x*10 + int64(s[j]-'0')
if isPrime(x) {
st[x] = struct{}{}
}
}
}
nums := make([]int64, 0, len(st))
for num := range st {
nums = append(nums, num)
}
sort.Slice(nums, func(i, j int) bool { return nums[i] < nums[j] })
for i := len(nums) - 1; i >= 0 && len(nums)-i <= 3; i-- {
ans += nums[i]
}
return
}
func isPrime(x int64) bool {
if x < 2 {
return false
}
sqrtX := int64(math.Sqrt(float64(x)))
for i := int64(2); i <= sqrtX; i++ {
if x%i == 0 {
return false
}
}
return true
}
# Accepted solution for LeetCode #3556: Sum of Largest Prime Substrings
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(sqrt(x)) + 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:])
// Accepted solution for LeetCode #3556: Sum of Largest Prime Substrings
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3556: Sum of Largest Prime Substrings
// class Solution {
// public long sumOfLargestPrimes(String s) {
// Set<Long> st = new HashSet<>();
// int n = s.length();
//
// for (int i = 0; i < n; i++) {
// long x = 0;
// for (int j = i; j < n; j++) {
// x = x * 10 + (s.charAt(j) - '0');
// if (is_prime(x)) {
// st.add(x);
// }
// }
// }
//
// List<Long> sorted = new ArrayList<>(st);
// Collections.sort(sorted);
//
// long ans = 0;
// int start = Math.max(0, sorted.size() - 3);
// for (int idx = start; idx < sorted.size(); idx++) {
// ans += sorted.get(idx);
// }
// return ans;
// }
//
// private boolean is_prime(long x) {
// if (x < 2) return false;
// for (long i = 2; i * i <= x; i++) {
// if (x % i == 0) return false;
// }
// return true;
// }
// }
// Accepted solution for LeetCode #3556: Sum of Largest Prime Substrings
function sumOfLargestPrimes(s: string): number {
const st = new Set<number>();
const n = s.length;
for (let i = 0; i < n; i++) {
let x = 0;
for (let j = i; j < n; j++) {
x = x * 10 + Number(s[j]);
if (isPrime(x)) {
st.add(x);
}
}
}
const sorted = Array.from(st).sort((a, b) => a - b);
const topThree = sorted.slice(-3);
return topThree.reduce((sum, val) => sum + val, 0);
}
function isPrime(x: number): boolean {
if (x < 2) return false;
for (let i = 2; i * i <= x; i++) {
if (x % i === 0) return false;
}
return true;
}
Use this to step through a reusable interview workflow for this problem.
For each element, scan the rest of the array looking for a match. Two nested loops give n × (n−1)/2 comparisons = O(n²). No extra space since we only use loop indices.
One pass through the input, performing O(1) hash map lookups and insertions at each step. The hash map may store up to n entries in the worst case. This is the classic space-for-time tradeoff: O(n) extra memory eliminates an inner loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Temporary multiplications exceed integer bounds.
Usually fails on: Large inputs wrap around unexpectedly.
Fix: Use wider types, modular arithmetic, or rearranged operations.