LeetCode: Super Palindromes Solution

1/**
2 * @param {string} left
3 * @param {string} right
4 * @return {number}
5 */
6var superpalindromesInRange = function (left, right) {
7 ;[left, right] = [+left, +right]
8
9 const isPalindrome = s => s === s.split("").reverse().join("")
10
11 let palindromes = [1, 2, 3, 4, 5, 6, 7, 8, 9]
12 // as range is max of 1e18 => find from sqrt(1e18) = 1e9
13 // build palindrome from concatnate: xx, x0x, x1x,...x9x
14 // so x must be in range 9/2 = 4
15 for (let i = 1; i < 10000; i++) {
16 const s1 = String(i) + String(i).split("").reverse().join("")
17 palindromes.push(s1)
18 for (let j = 0; j < 10; j++) {
19 const s2 = String(i) + String(j) + String(i).split("").reverse().join("")
20 palindromes.push(s2)
21 }
22 }
23
24 palindromes = palindromes.map(Number).sort((a, b) => a - b)
25
26 let numberOfSuperPalindromesInRange = 0
27
28 for (const palindrome of palindromes) {
29 const s = String(BigInt(palindrome) ** 2n)
30 if (isPalindrome(s) && left <= Number(s) && Number(s) <= right) {
31 numberOfSuperPalindromesInRange++
32 }
33 }
34
35 return numberOfSuperPalindromesInRange
36}

Comments

Loading comments...

Tags

leetcode

math

string

array

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Maximum Distance Between A Pair Of Values

HoningJS

Search Posts