diff --git a/1437.check-if-all-1s-are-at-least-length-k-places-away.js b/1437.check-if-all-1s-are-at-least-length-k-places-away.js new file mode 100644 index 00000000..4ecfb1b6 --- /dev/null +++ b/1437.check-if-all-1s-are-at-least-length-k-places-away.js @@ -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; \ No newline at end of file diff --git a/kLengthApart.test.js b/kLengthApart.test.js new file mode 100644 index 00000000..8effbeda --- /dev/null +++ b/kLengthApart.test.js @@ -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(); +}); \ No newline at end of file