-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0967-numbers-with-same-consecutive-differences.js
More file actions
54 lines (47 loc) · 1.49 KB
/
0967-numbers-with-same-consecutive-differences.js
File metadata and controls
54 lines (47 loc) · 1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Numbers With Same Consecutive Differences
* Time Complexity: O(2^n)
* Space Complexity: O(2^n)
*/
var numsSameConsecDiff = function (n, k) {
let collectionOfResults = [];
let levelOneNumbers = Array.from(
{ length: 9 },
(_, initialDigitIndex) => initialDigitIndex + 1,
);
if (n === 1) {
collectionOfResults = levelOneNumbers;
return collectionOfResults;
}
let currentNumbersBuilding = levelOneNumbers;
let currentLengthBuilding = 1;
while (currentLengthBuilding < n) {
let nextIterationNumbers = [];
for (
let numberPointer = 0;
numberPointer < currentNumbersBuilding.length;
numberPointer++
) {
let currentNumberValue = currentNumbersBuilding[numberPointer];
let lastNumericCharacter = currentNumberValue % 10;
let nextCharacterPlusK = lastNumericCharacter + k;
if (nextCharacterPlusK <= 9) {
let constructedNumberPlus =
currentNumberValue * 10 + nextCharacterPlusK;
nextIterationNumbers.push(constructedNumberPlus);
}
if (k !== 0) {
let nextCharacterMinusK = lastNumericCharacter - k;
if (nextCharacterMinusK >= 0) {
let constructedNumberMinus =
currentNumberValue * 10 + nextCharacterMinusK;
nextIterationNumbers.push(constructedNumberMinus);
}
}
}
currentNumbersBuilding = nextIterationNumbers;
currentLengthBuilding++;
}
collectionOfResults = currentNumbersBuilding;
return collectionOfResults;
};