Skip to main content
Back to problems
#3618
Medium Algorithms

Split array by prime indices

Array Math Number Theory
49.3% acceptance
Feb 25, 2026
54
3
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)|. Note: An empty array has a sum of 0.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn split_array(nums: Vec<i32>) -> i64 {
    let n = nums.len();
    let sieve = Self::sieve(n);
    let mut sum_a = 0i64;
    let mut sum_b = 0i64;
    for i in 0..n {
      if sieve[i] { sum_a += nums[i] as i64; }
      else         { sum_b += nums[i] as i64; }
    }
    (sum_a - sum_b).abs()
  }

  fn sieve(n: usize) -> Vec<bool> {
    if n == 0 { return vec![]; }
    let mut is_prime = vec![true; n];
    if n > 0 { is_prime[0] = false; }
    if n > 1 { is_prime[1] = false; }
    let mut i = 2;
    while i * i < n {
      if is_prime[i] {
        let mut j = i * i;
        while j < n { is_prime[j] = false; j += i; }
      }
      i += 1;
    }
    is_prime
  }
}