LeetCode: Powerful Integers Solution
1/**2 * @param {number} x3 * @param {number} y4 * @param {number} bound5 * @return {number[]}6 */7var powerfulIntegers = function (x, y, bound) {8 const res = new Set()9 const [X, Y] = [10 x === 1 ? bound : Math.floor(Math.log(bound) / Math.log(x)),11 y === 1 ? bound : Math.floor(Math.log(bound) / Math.log(y)),12 ]1314 for (let i = 0; i <= X; i++) {15 for (let j = 0; j <= Y; j++) {16 const val = x ** i + y ** j17 if (val <= bound) {18 res.add(val)19 }20 // 1^anything will always be 121 if (y === 1) {22 break23 }24 }25 // 1^anything will always be 126 if (x === 1) {27 break28 }29 }3031 return Array.from(res)32}3334// dfs35var powerfulIntegers = function (x, y, bound) {36 const res = new Set()37 const visited = new Set()38 const stack = [[0, 0]]3940 const getKey = (i, j) => `${i}-${j}`4142 while (stack.length > 0) {43 const [i, j] = stack.pop()4445 if (visited.has(getKey(i, j))) {46 continue47 }4849 visited.add(getKey(i, j))50 const val = x ** i + y ** j5152 if (val <= bound) {53 res.add(val)54 x > 1 && stack.push([i + 1, j])55 y > 1 && stack.push([i, j + 1])56 }57 }5859 return Array.from(res)60}
Comments
Loading comments...
Tags
leetcode
hash table
math
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: Prefix And Suffix Search
May 1, 2021