[LeetCode] Split Array by Prime Indices

3618. Split Array by Prime Indices

You are given an integer array nums.

Split nums into two arrays A and B using the following rule:

  • Elements at prime indices in nums must go into array A.
  • All other elements must go into array B.

Return the absolute difference between the sums of the two arrays: |sum(A) - sum(B)|.

A prime number is a natural number greater than 1 with only two factors, 1 and itself.

Note: An empty array has a sum of 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int factors[101010];
class Solution {
public:
long long splitArray(vector<int>& nums) {
for(long long i = 2; i < 101010; i++) {
if(factors[i]) continue;
for(long long j = i * i; j < 101010; j += i) factors[j] = i;
}
long long res = 0;
auto prime = [&](int i) {
return i >= 2 and factors[i] == 0;
};
for(int i = 0; i < nums.size(); i++) {
if(prime(i)) res -= nums[i];
else res += nums[i];
}
return abs(res);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/07/20/PS/LeetCode/split-array-by-prime-indices/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.