#3618
Split Array by Prime Indices
MediumArrayMathNumber TheorySieve of EratosthenesArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log log n)Space O(n)
Use the Sieve of Eratosthenes to find all prime indices efficiently, then split the array in a single pass.
⚙️
Algorithm
3 steps- 1Step 1: Generate a list of prime indices using the Sieve of Eratosthenes.
- 2Step 2: Iterate through nums, adding to sumA for prime indices and sumB for others.
- 3Step 3: Return |sumA - sumB|.
solution.py15 lines
1def split_array(nums):
2 n = len(nums)
3 is_prime = [True] * n
4 is_prime[0] = is_prime[1] = False
5 for i in range(2, int(n**0.5) + 1):
6 if is_prime[i]:
7 for j in range(i*i, n, i):
8 is_prime[j] = False
9 sumA, sumB = 0, 0
10 for i in range(n):
11 if is_prime[i]:
12 sumA += nums[i]
13 else:
14 sumB += nums[i]
15 return abs(sumA - sumB)ℹ
Complexity note: Sieve of Eratosthenes runs in O(n log log n) and we traverse nums once, making it efficient.
- 1Understanding prime numbers is crucial.
- 2Efficient algorithms can significantly reduce complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.