-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path1842-next-palindrome-using-same-digits.js
More file actions
60 lines (49 loc) · 1.55 KB
/
1842-next-palindrome-using-same-digits.js
File metadata and controls
60 lines (49 loc) · 1.55 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
55
56
57
58
59
60
/**
* 1842. Next Palindrome Using Same Digits
* https://leetcode.com/problems/next-palindrome-using-same-digits/
* Difficulty: Hard
*
* You are given a numeric string num, representing a very large palindrome.
*
* Return the smallest palindrome larger than num that can be created by rearranging its
* digits. If no such palindrome exists, return an empty string "".
*
* A palindrome is a number that reads the same backward as forward.
*/
/**
* @param {string} num
* @return {string}
*/
var nextPalindrome = function(num) {
const length = num.length;
const halfLength = Math.floor(length / 2);
const leftHalf = num.slice(0, halfLength).split('');
if (!nextPermutation(leftHalf)) {
return '';
}
const rightHalf = leftHalf.slice().reverse();
const result = leftHalf.join('') + (length % 2 === 1 ? num[halfLength] : '') + rightHalf.join('');
return result;
function nextPermutation(digits) {
let pivot = -1;
for (let i = digits.length - 2; i >= 0; i--) {
if (digits[i] < digits[i + 1]) {
pivot = i;
break;
}
}
if (pivot === -1) return false;
for (let i = digits.length - 1; i > pivot; i--) {
if (digits[i] > digits[pivot]) {
[digits[pivot], digits[i]] = [digits[i], digits[pivot]];
break;
}
}
const leftPart = digits.slice(0, pivot + 1);
const rightPart = digits.slice(pivot + 1).reverse();
for (let i = 0; i < digits.length; i++) {
digits[i] = i < leftPart.length ? leftPart[i] : rightPart[i - leftPart.length];
}
return true;
}
};