Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions 1437.check-if-all-1s-are-at-least-length-k-places-away.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/* URL of this problem
* https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/description/
*
* @param {number[]} nums
* @param {number} k
* @return {boolean}
*/

var kLengthApart = function(nums, k) {
const OneIdxes = [];
let IsKLenApart = true;

// Create an array of 1's indexes in nums in an order of occurrence
nums.forEach((num, idx) => {
if (num === 1) {
OneIdxes.push(idx);
}
});
for (let i = 0; i < OneIdxes.length - 1 && IsKLenApart; i++) {
// Caluculate the distance between two of 1
const Distance = Math.abs(OneIdxes[i] - OneIdxes[i + 1]) - 1;

IsKLenApart = Distance >= k ? true : false;
}

return IsKLenApart;
};

module.exports = kLengthApart;
13 changes: 13 additions & 0 deletions kLengthApart.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const kLengthApart = require("./1437.check-if-all-1s-are-at-least-length-k-places-away");

test("Return true if all 1's are at least k places away from each other", () => {
expect(kLengthApart([1,0,0,0,1,0,0,1], 2)).toBeTruthy();
});

test("Return false if any pair of 1's has less than k places in between", () => {
expect(kLengthApart([1,0,0,1,0,1], 2)).toBeFalsy();
});

test("Return true if the argument nums comprises only 1s and the argument k is 0", () => {
expect(kLengthApart([1,1,1,1,1], 0)).toBeTruthy();
});