Created
December 5, 2025 17:35
-
-
Save tatsuyax25/597169d8334b8a7d9f9f38a79c373b91 to your computer and use it in GitHub Desktop.
You are given an integer array nums of length n. A partition is defined as an index i where 0 <= i < n - 1, splitting the array into two non-empty subarrays such that: Left subarray contains indices [0, i].
Right subarray contains indices [i + 1, n
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {number[]} nums | |
| * @return {number} | |
| */ | |
| var countPartitions = function(nums) { | |
| // Step 1: Compute the total sum of the array. | |
| // We'll use this to quickly calculate the right subarray sum at each partition. | |
| let totalSum = 0; | |
| for (let num of nums) { | |
| totalSum += num; | |
| } | |
| // Step 2: Initialize variables | |
| let leftSum = 0; // running sum of the left subarray | |
| let count = 0; // number of valid partitions | |
| // Step 3: Iterate through possible partitions | |
| // A partition index i splits the array into [0..i] and [i+1..n-1]. | |
| // So we stop at n-2, because the right subarray must be non-empty. | |
| for (let i = 0; i < nums.length - 1; i++) { | |
| // Add current element to the left sum | |
| leftSum += nums[i]; | |
| // Right sum is total minus left sum | |
| let rightSum = totalSum - leftSum; | |
| // Step 4: Check if the difference is even | |
| // Instead of computing (leftSum - rightSum), we can check parity: | |
| if ((leftSum % 2) === (rightSum % 2)) { | |
| count++; | |
| } | |
| } | |
| // Step 5: Return the total count of valid partitions | |
| return count; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment