Created
November 17, 2025 16:42
-
-
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.
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 | |
| * @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