#3765

Complete Prime Number

Medium
MathEnumerationNumber TheoryNumber TheoryString Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use a single function to check primality and iterate through prefixes and suffixes efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Convert the number to a string for easy manipulation.
  2. 2Step 2: Use a helper function to check if each prefix and suffix is prime.
  3. 3Step 3: Return true only if all checks pass.
solution.py14 lines
1def is_prime(n):
2    if n < 2:
3        return False
4    for i in range(2, int(n**0.5) + 1):
5        if n % i == 0:
6            return False
7    return True
8
9def is_complete_prime(num):
10    s = str(num)
11    for i in range(len(s)):
12        if not is_prime(int(s[:i + 1])) or not is_prime(int(s[i:])):
13            return False
14    return True

Complexity note: We check each prefix and suffix efficiently, leading to linear checks for n digits.

  • 1Primality check is crucial for both prefixes and suffixes.
  • 2Single-digit primes are special cases.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.