Split Array by Prime Indices Problem
#3618
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3618.
You are given an integer array nums.
Split nums into two arrays A and B using the following rule:
- Elements at prime indices in
numsmust go into arrayA. - All other elements must go into array
B.
Return the absolute difference between the sums of the two arrays: |sum(A) - sum(B)|.
Note: An empty array has a sum of 0.
Example 1:
Input: nums = [2,3,4]
Output: 1
Explanation:
- The only prime index in the array is 2, so nums[2] = 4 is placed in array A.
- The remaining elements, nums[0] = 2 and nums[1] = 3 are placed in array B.
- sum(A) = 4, sum(B) = 2 + 3 = 5.
- The absolute difference is |4 - 5| = 1.
Example 2:
Input: nums = [-1,5,7,0]
Output: 3
Explanation:
- The prime indices in the array are 2 and 3, so nums[2] = 7 and nums[3] = 0 are placed in array A.
- The remaining elements, nums[0] = -1 and nums[1] = 5 are placed in array B.
- sum(A) = 7 + 0 = 7, sum(B) = -1 + 5 = 4.
- The absolute difference is |7 - 4| = 3.
Constraints:
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Sieve + Simulation
Indices are below 10^5, so a sieve of Eratosthenes over [0, 10^5] tells us once which indices are prime. Then scan nums: add nums[i] to a running total when i is prime and subtract it otherwise. That total is sum(A) - sum(B), so return its absolute value. The sums reach about 10^14, so use a 64-bit integer.
Complexity: O(n) time for the scan (plus a one-time sieve) and O(1) extra space per call.
m = 10**5 + 10
primes = [True] * m
primes[0] = primes[1] = False
for i in range(2, m):
if primes[i]:
for j in range(i + i, m, i):
primes[j] = False
class Solution:
def splitArray(self, nums: List[int]) -> int:
return abs(sum(x if primes[i] else -x for i, x in enumerate(nums)))