Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created November 17, 2025 16:42
Show Gist options
  • Select an option

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

Select an option

Save tatsuyax25/c869178919f0b376fc9fe1fb559e39cb to your computer and use it in GitHub Desktop.
Given an binary array nums and an integer k, return true if all 1's are at least k places away from each other, otherwise return false.
/**
* @param {number[]} nums
* @param {number} k
* @return {boolean}
*/
var kLengthApart = function(nums, k) {
// Keep track of the index of the last '1' we saw
let lastOneIndex = -1;
// Loop through the array
for (let i = 0; i < nums.length; i++) {
// If we find a '1'
if (nums[i] === 1) {
// Case 1: If this is not the first '1' we've seen
if (lastOneIndex !== -1) {
// Check the distance between this '1' and the previous '1'
let distance = i - lastOneIndex;
// If the distance is less than or equal to k, return false
if (distance <= k) {
return false;
}
}
// Update lastOneIndex to the current position
lastOneIndex = i;
}
}
// If we finish the loop without finding violations, return true
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment