Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created October 28, 2025 19:36
Show Gist options
  • Select an option

  • Save tatsuyax25/66471ff73da1cd60a03c9d700f5fe403 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/66471ff73da1cd60a03c9d700f5fe403 to your computer and use it in GitHub Desktop.
You are given an integer array nums. Start by selecting a starting position curr such that nums[curr] == 0, and choose a movement direction of either left or right. After that, you repeat the following process: If curr is out of the range [0, n -
/**
* Counts how many zero positions in the array can lead to all elements being reduced to zero
* by moving forward or backward and decrementing non-zero values.
*
* @param {number[]} nums - Array of non-negative integers
* @return {number} - Total number of valid selections from zero positions
*/
var countValidSelections = function (nums) {
// Collect indices where the value is zero
const zeroIndexArr = nums.reduce((acc, cur, idx) => {
if (cur === 0) acc.push(idx);
return acc;
}, []);
// If there are no zero positions, no valid selections are possible
if (zeroIndexArr.length === 0) return 0;
let validSelections = 0;
/**
* Checks if all elements in the array are zero
* @param {number[]} arr
* @return {boolean}
*/
const isArrayZero = (arr) => arr.every((val) => val === 0);
/**
* Simulates movement from a starting index in a given direction,
* toggling direction whenever a non-zero element is decremented.
*
* @param {number} cur - Starting index
* @param {number[]} nums - Copy of the original array
* @param {"forward"|"backward"} direction - Initial movement direction
* @return {boolean} - True if all elements become zero during traversal
*/
const moveLogic = (cur, nums, direction) => {
while (cur >= 0 && cur < nums.length) {
// Move in the current direction
cur = direction === "forward" ? cur + 1 : cur - 1;
// If within bounds and value is positive, decrement and flip direction
if (cur >= 0 && cur < nums.length && nums[cur] > 0) {
nums[cur]--;
direction = direction === "forward" ? "backward" : "forward";
}
}
return isArrayZero(nums);
};
// Try each zero index as a starting point in both directions
zeroIndexArr.forEach((z) => {
if (moveLogic(z, [...nums], "forward")) validSelections++;
if (moveLogic(z, [...nums], "backward")) validSelections++;
});
return validSelections;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment