3618. Split Array by Prime Indices
Description
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] = 4is placed in arrayA. - The remaining elements,
nums[0] = 2andnums[1] = 3are placed in arrayB. 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] = 7andnums[3] = 0are placed in arrayA. - The remaining elements,
nums[0] = -1andnums[1] = 5are placed in arrayB. sum(A) = 7 + 0 = 7,sum(B) = -1 + 5 = 4.- The absolute difference is
|7 - 4| = 3.
Constraints:
1 <= nums.length <= 105-109 <= nums[i] <= 109
Solutions
Solution 1: Sieve of Eratosthenes + Simulation
Thinking
The answer is the absolute difference between the sum at prime indices and the sum at composite indices, i.e. a signed sum over \(i\). Indices reach \(10^5\), so trial division per index is wasteful.
The sieve of Eratosthenes marks primality on \([0,10^5]\). Walk the array, add \(x\) at a prime index and \(-x\) otherwise, then take the absolute value.
The sieve can be reused; each query is a single linear scan.
We can use the Sieve of Eratosthenes to preprocess all prime numbers in the range \([0, 10^5]\). Then we iterate through the array \(\textit{nums}\). For \(\textit{nums}[i]\), if \(i\) is a prime number, we add \(\textit{nums}[i]\) to the answer; otherwise, we add \(-\textit{nums}[i]\) to the answer. Finally, we return the absolute value of the answer.
Ignoring the preprocessing time and space, the time complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{nums}\), and the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |