Taro Logo

Sum of Largest Prime Substrings

Medium
Asked by:
Netcracker Technology
0 views
Topics:
StringsRecursion

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

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the input string s, and should we be concerned about very large prime values exceeding standard integer limits?
  2. How should we handle the case where fewer than two distinct prime substrings can be formed from the string?
  3. Does "distinct prime values" mean we only consider unique prime numbers mathematically (e.g., if "11" appears twice, it counts as one distinct value), or do we consider substrings by their start and end indices?
  4. Can substrings have leading zeros, and if so, are they considered valid prime numbers (e.g., "07" evaluated as 7)?
  5. If two identical prime values are formed from different parts of the string, are they treated as the same distinct prime value for the purpose of finding the two largest?

Brute Force Solution

Approach

The brute force approach to solving this problem involves examining every single possible section of the given number sequence to see which ones are valid prime numbers. By testing every combination and keeping track of the largest ones we find, we can eventually determine the correct sum of the largest prime substrings.

Here's how the algorithm would work step-by-step:

  1. Look at the entire string of numbers as a whole.
  2. Identify every possible smaller chunk of numbers you can make by cutting the sequence at any starting and ending point.
  3. Check each of these individual chunks to see if it qualifies as a prime number.
  4. Keep a running list or memory of the prime numbers you discover during this process.
  5. Review your collection of discovered prime numbers to find the largest ones.
  6. Add up these largest prime numbers to arrive at your final answer.

Code Implementation

def sum_of_largest_prime_substrings(number_sequence):
    # Extract every possible substring chunk to evaluate all potential prime number candidates
    prime_candidates = set()
    string_length = len(number_sequence)
    for start_index in range(string_length):
        for end_index in range(start_index + 1, string_length + 1):
            substring_chunk = number_sequence[start_index:end_index]
            prime_candidates.add(int(substring_chunk))

    # Filter numeric candidates to retain only true primes by checking divisibility up to their square root
    verified_primes = []
    for candidate_value in prime_candidates:
        if candidate_value < 2:
            continue
        is_prime_number = True
        divisor = 2
        while divisor * divisor <= candidate_value:
            if candidate_value % divisor == 0:
                is_prime_number = False
                break
            divisor += 1
        if is_prime_number:
            verified_primes.append(candidate_value)

    # Sort identified primes in descending order to easily isolate the largest discovered values
    verified_primes.sort(reverse=True)

    # Aggregate the top unique prime values to produce the final summation requested by the problem
    top_prime_count = min(3, len(verified_primes))
    final_sum_result = sum(verified_primes[:top_prime_count])

    return final_sum_result

Big(O) Analysis

Time Complexity
O(n³) – Generating every possible substring from a string of length n requires two nested loops for the start and end indices, which creates n squared substrings. Checking each of these substrings for primality takes up to proportional to the square root of the substring value, or in the worst case, proportional to n steps since the substring can have up to n digits. Multiplying the n squared substrings by the cost of the primality check results in approximately n cubed operations, which simplifies to O(n³).
Space Complexity
O(N) – To analyze the auxiliary space, let N be the length of the input string of numbers. The algorithm generates every possible substring chunk, and in the worst-case scenario, the number of distinct prime substrings can grow quadratically with N. However, if we store the unique primes or a running list of discovered primes as mentioned in steps four and five, the collection can hold up to O(N squared) elements. Consequently, the auxiliary data structures storing these intermediate prime substrings and tracking the largest values dominate the memory usage, simplifying to a space complexity of O(N squared) or O(N) depending on whether duplicates and overlapping substrings are filtered in place.

Optimal Solution

Approach

The algorithm extracts all possible numeric substrings from the input string and ignores leading zeros by converting them to integers. It then checks each unique number for primality to build a collection of unique prime numbers. Finally, the primes are sorted in descending order, and the sum of up to the three largest values is returned.

Here's how the algorithm would work step-by-step:

  1. Define a helper function to determine if a given integer is prime.
  2. Iterate through all pairs of start and end indices to extract substrings and convert them to integers.
  3. Store the integer values in a set to ensure every candidate number is considered only once.
  4. Filter the unique integers to collect only those that are prime numbers.
  5. Sort the resulting list of unique primes in descending order.
  6. Sum the first three elements of the sorted list, or all elements if fewer than three exist, and return the result.

Code Implementation

def sum_of_largest_prime_substrings(string_input: str) -> int:
    def is_prime(candidate: int) -> bool:
        if candidate < 2:
            return False
        divisor = 2
        while divisor * divisor <= candidate:
            if candidate % divisor == 0:
                return False
            divisor += 1
        return True

    # Generate all unique integers from contiguous substrings
    unique_numbers = set()
    string_length = len(string_input)
    for start_index in range(string_length):
        for end_index in range(start_index + 1, string_length + 1):
            unique_numbers.add(int(string_input[start_index:end_index]))

    # Filter the set of unique numbers to keep only prime values
    unique_primes = [number for number in unique_numbers if is_prime(number)]

    # Sort prime numbers in descending order to identify the largest
    unique_primes.sort(reverse=True)

    # Return the sum of up to the three largest unique primes
    return sum(unique_primes[:3])

Big(O) Analysis

Time Complexity
O(N^2 * sqrt(M)) – With N being the length of the string (at most 10), there are O(N^2) substrings. For each unique number up to M (at most 10^10), checking primality takes O(sqrt(M)) time, which is well within execution limits for small inputs.
Space Complexity
O(N^2) – The set of unique substring numbers and the filtered list of primes store at most O(N^2) integers, requiring minimal auxiliary space.

Edge Cases

String is empty or null
How to Handle:
Return zero or an appropriate error code immediately since no substrings can be formed.
String length is very small like one or two characters
How to Handle:
Extract the few possible substrings and check them directly without complex slicing logic.
Input string contains leading zeros in substrings like 03
How to Handle:
Treat strings starting with zero as invalid prime numbers unless the substring is exactly the single digit 2.
Fewer than two distinct prime numbers can be formed from the substrings
How to Handle:
Return zero or handle the missing second prime gracefully according to problem constraints.
Large input string lengths causing combinatorial explosion of substrings
How to Handle:
Limit the maximum length of substrings checked since prime testing large numbers is inefficient.
Extremely large prime values causing integer overflow
How to Handle:
Use arbitrary precision arithmetic or 64-bit integers to safely store and sum the large prime values.
Multiple identical prime substrings found
How to Handle:
Use a set data structure to store unique prime values so duplicates do not count as distinct.
String contains non-digit characters
How to Handle:
Filter out or validate the input string upfront to ensure only numeric digits are processed.