Day 18 is to check the previous index of the array is less than the current index of the array.
For example, an array of [3, 5, 2, 4, 5]
will return [-1, 3, -1, 2, 4]
.
From the array above if the previous index (3
) less than the current index (5
) return the previous index (3
), but if previous index (5
) is not less than current index (2
), return -1
;
These are the solution in JavaScript
1st - Using Unshift
function arrayPreviousLess(nums) {
let result = [];
for (i=nums.length-1; i >= 0; i--) {
(nums[i] > nums[i-1]) ? result.unshift(nums[i-1]) : result.unshift(-1);
}
return result;
}
When using Unshift, it starts from the last index and insert value on the beginning of the array on each iteration.
Meanwhile....
2nd - Using Push
function arrayPreviousLess(nums) {
let result = [];
for (i=0; i < nums.length; i++) {
(nums[i-1] < nums[i]) ? result.push(nums[i-1]) : result.push(-1);
}
return result;
}
When using Push, it starts the index from 0 and insert value on the last of the array on each iteration.
Top comments (0)