diff --git a/2229.check-if-an-array-is-consecutive.js b/2229.check-if-an-array-is-consecutive.js new file mode 100644 index 00000000..3ec1aa5d --- /dev/null +++ b/2229.check-if-an-array-is-consecutive.js @@ -0,0 +1,21 @@ +/* URL of this problem + * https://leetcode.com/problems/check-if-an-array-is-consecutive/description/ + * + * @param {number[]} nums + * @return {boolean} + */ + +var isConsecutive = function(nums) { + const SortedNums = [...nums].sort((a, b) => a - b); + const RangeStart = Math.min(...nums); + const RangeEnd = RangeStart + nums.length - 1; + const RangeNums = []; + + for (let i = RangeStart; i <= RangeEnd; i++) { + RangeNums.push(i); + } + + return SortedNums.join("") === RangeNums.join(""); +}; + +module.exports = isConsecutive; \ No newline at end of file diff --git a/isConsecutive.test.js b/isConsecutive.test.js new file mode 100644 index 00000000..5182d23b --- /dev/null +++ b/isConsecutive.test.js @@ -0,0 +1,13 @@ +const isConsecutive = require("./2229.check-if-an-array-is-consecutive"); + +test("Return true if the input nums contains all the integers in the range", () => { + expect(isConsecutive([1,3,4,2])).toBeTruthy(); +}); + +test("Return false if the input nums misses any integer in the range", () => { + expect(isConsecutive([1,3])).toBeFalsy(); +}); + +test("Return false if the input nums contains Infinity", () => { + expect(isConsecutive([1,3,4,2,Infinity])).toBeFalsy(); +}); \ No newline at end of file