Skip to content

Commit faba347

Browse files
committed
Add solution #556
1 parent 2dc488d commit faba347

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,7 @@
440440
552|[Student Attendance Record II](./0552-student-attendance-record-ii.js)|Hard|
441441
553|[Optimal Division](./0553-optimal-division.js)|Medium|
442442
554|[Brick Wall](./0554-brick-wall.js)|Medium|
443+
556|[Next Greater Element III](./0556-next-greater-element-iii.js)|Medium|
443444
557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy|
444445
560|[Subarray Sum Equals K](./0560-subarray-sum-equals-k.js)|Medium|
445446
563|[Binary Tree Tilt](./0563-binary-tree-tilt.js)|Easy|
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 556. Next Greater Element III
3+
* https://leetcode.com/problems/next-greater-element-iii/
4+
* Difficulty: Medium
5+
*
6+
* Given a positive integer n, find the smallest integer which has exactly the same digits existing
7+
* in the integer n and is greater in value than n. If no such positive integer exists, return -1.
8+
*
9+
* Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it
10+
* does not fit in 32-bit integer, return -1.
11+
*/
12+
13+
/**
14+
* @param {number} n
15+
* @return {number}
16+
*/
17+
var nextGreaterElement = function(n) {
18+
const digits = [...String(n)];
19+
let i = digits.length - 2;
20+
21+
while (i >= 0 && digits[i] >= digits[i + 1]) i--;
22+
if (i < 0) return -1;
23+
24+
let j = digits.length - 1;
25+
while (j >= 0 && digits[j] <= digits[i]) j--;
26+
27+
[digits[i], digits[j]] = [digits[j], digits[i]];
28+
let left = i + 1;
29+
let right = digits.length - 1;
30+
while (left < right) {
31+
[digits[left], digits[right]] = [digits[right], digits[left]];
32+
left++;
33+
right--;
34+
}
35+
36+
const result = +digits.join('');
37+
return result > n && result <= 2**31 - 1 ? result : -1;
38+
};

0 commit comments

Comments
 (0)