Next Greater Element III LeetCode solution in JavaScript

1
var nextGreaterElement = function (n) {
2
const MAX_VALUE = 2 ** 31 - 1;
3
const nums = `${n}`.split("");
4
let findPos;
5

6
for (let index = nums.length - 2; index >= 0; index--) {
7
if (nums[index] < nums[index + 1]) {
8
findPos = index;
9
break;
10
}
11
}
12

13
if (findPos === undefined) return -1;
14
for (let index = nums.length - 1; index >= 0; index--) {
15
if (nums[index] > nums[findPos]) {
16
[nums[index], nums[findPos]] = [nums[findPos], nums[index]];
17
break;
18
}
19
}
20

21
const mantissa = nums
22
.slice(findPos + 1)
23
.sort((a, b) => a - b)
24
.join("");
25
const result = Number(nums.slice(0, findPos + 1).join("") + mantissa);
26
return result > MAX_VALUE ? -1 : result;
27
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0