BackmediumArraysAdobe

Cargo Ship Balancing Solution

Problem Statement

Given an integer array nums representing the weight of cargo crates placed consecutively on a ship, determine whether there exists an index i (0<i<nums.length) such that the sum of the elements to the left of i equals the sum of the elements to the right of i. Return true if at least one such split point exists; otherwise return false. The split must produce two non‑empty sub‑arrays.

Example 1
Input
[1,2,3,3,2,1]
Output
true

Explanation: Total weight = 12. Prefix sums: after index0 →1, after1 →3, after2 →6. At index3 the left side weight is 1+2+3 = 6 and the right side weight is 3+2+1 = 6, so a valid split exists.

Example 2
Input
[5,5]
Output
true

Explanation: Total weight = 10. Splitting after the first element gives left weight 5 and right weight 5, satisfying the condition.

Example 3
Input
[10,-5,5,0]
Output
true

Explanation: Total weight = 10. Prefix sum after the second element (indices 0‑1) is 10+(-5)=5; the remaining elements sum to 5+0=5, so the array can be split at that point.

Constraints

  • 2 <= nums.length <= 100000
  • -1000000000 <= nums[i] <= 1000000000
  • All calculations fit in 64‑bit signed integer
  • Expected time complexity O(n)
  • Expected auxiliary space O(1)
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Cargo Ship Balancing — Problem Statement & Solution Guide

ArraysMediumTwo Pointers
TimeO(n)
|
SpaceO(1)

Problem Description

Given an integer array nums representing the weight of cargo crates placed consecutively on a ship, determine whether there exists an index i (0<i<nums.length) such that the sum of the elements to the left of i equals the sum of the elements to the right of i. Return true if at least one such split point exists; otherwise return false. The split must produce two non‑empty sub‑arrays.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Cargo Ship Balancing"

medium

WHY DOES IT MATTER?

Equilibrium detection appears in load balancing, financial ledger reconciliation, and memory partitioning, where a split point guarantees equal resource distribution without extra passes.

OPTIMIZATION CHALLENGE

The key insight is that the right side sum can be expressed as total‑left‑current, eliminating the need for a second traversal or nested loops, thus collapsing O(n^2) to O(n).

REAL-WORLD CONNECTION

Think of a cargo ship where you need to place a divider so that the weight on both sides is identical—this mirrors distributed systems that must partition data evenly across nodes to avoid hotspots.

During the interview, compute totalSum first, then iterate while updating leftSum; if leftSum equals totalSum‑leftSum‑nums[i] you’ve found the split—no need for extra arrays.

COMPLEXITY AT A GLANCE

⏱ Time:O(n)
💾 Space:O(1)

Core Theory — Why This Approach?

The problem is a classic instance of the "pivot index" or "equilibrium index" problem, which can be solved efficiently using prefix sums. A naive solution would recompute left and right sums for each candidate index, leading to O(n^2) time, which quickly becomes infeasible for large cargo manifests (n can be up to 10^5 or more). By pre‑computing the total sum of the array and then iterating once while maintaining a running left‑hand sum, we can derive the right‑hand sum in O(1) per step (rightSum = totalSum‑leftSum‑nums[i]). This single‑pass technique embodies the optimal paradigm of "scan with auxiliary aggregate" and guarantees linear time with constant extra space, which is essential for real‑time ship loading systems that must make split decisions instantly.

Interview Questions on This Problem

Q1How would you modify the solution to return the leftmost pivot index instead of a boolean?

Maintain the same single‑pass scan; as soon as leftSum equals totalSum‑leftSum‑nums[i] you return i. If the loop finishes without a match, return -1.

Q2If the cargo weights can be negative, does the algorithm still work? Why?

Yes. The algorithm relies only on arithmetic equality of sums, not on sign. The running left sum and derived right sum remain correct even with negative values.

Q3Can you extend the approach to find all pivot indices in O(n) time?

During the same linear scan, whenever leftSum equals rightSum, record the index in a list. After the loop, return the list; this still uses O(n) time and O(k) extra space for k pivots.

Examples

Example 1

Input

[1,2,3,3,2,1]

Output

true

Explanation: Total weight = 12. Prefix sums: after index0 →1, after1 →3, after2 →6. At index3 the left side weight is 1+2+3 = 6 and the right side weight is 3+2+1 = 6, so a valid split exists.

Example 2

Input

[5,5]

Output

true

Explanation: Total weight = 10. Splitting after the first element gives left weight 5 and right weight 5, satisfying the condition.

Example 3

Input

[10,-5,5,0]

Output

true

Explanation: Total weight = 10. Prefix sum after the second element (indices 0‑1) is 10+(-5)=5; the remaining elements sum to 5+0=5, so the array can be split at that point.

Constraints

  • 2 <= nums.length <= 100000
  • -1000000000 <= nums[i] <= 1000000000
  • All calculations fit in 64‑bit signed integer
  • Expected time complexity O(n)
  • Expected auxiliary space O(1)

Optimal Approach & Strategy

First compute the total sum, then iterate once while maintaining a left‑hand sum; the right sum is derived on the fly, allowing an O(n) time, O(1) space solution.

Brute Force Approach

For each index, sum all elements left of it and all elements right of it, then compare the two sums; repeat for every possible split.

Verified Code Solutions

JavaScript Solution
Time: O(n)
// jsSolution
function cargoShipBalancing(nums) {
    if (nums.length < 2) return false;
    let totalSum = nums.reduce((a, b) => a + b, 0);
    let leftSum = 0;
    for (let i = 0; i < nums.length; i++) {
        if (leftSum === totalSum - leftSum - nums[i]) {
            return true;
        }
        leftSum += nums[i];
    }
    return false;
}

Asked in Top Tech Interviews

Adobe

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.