function solve(arr) { //reading input let minString = arr.shift(); let maxString = arr.shift(); let min = Number.parseInt(minString); let max = Number.parseInt(maxString); // We can visualize the problem as a forest of binary trees each rooted with the digit i, with: // - Left children being created by just appending (parent last digit - 1) (as long as parent last digit != 0) // - Right children being created by just appending (parent last digit + 1) (as long as parent last digit != 9) // 1 2 3 ... // / \ / \ / \ // 10 12 21 23 32 34 // \ / \ / \ / \ / \ / \ // 101 121 123 210 212 232 234 321 323 343 345 let solutions = []; let solution = ''; for (let i = 1; i < 10; i++) { solution = i.toString(); recurse(Number(solution)); } // Sorting is needed here since the current recursive algorithm creates special numbers by traversing the tree in a dfs manner // If we would instead traverse using a bfs approach over all trees, we can save the sorting step (and the recursive calls) solutions.sort((a, b) => a - b); console.log(solutions.join('\n')); //builds the numbers by appending smaller/larger digit at the end. There are multiple ways to do this: // 1. We can either have solution be a string and append digits at the end // 2. We can have solution be a number and when we want to append a new digit we just multiply solution by 10 and then add the new digit function recurse(digit) { let curNumber = Number(solution); if (curNumber > max) { return; } if (curNumber >= min && curNumber <= max) { solutions.push(curNumber); } let smaller = digit - 1; let bigger = digit + 1; //extends the number with a smaller digit if (digit != 0) { solution += smaller; recurse(smaller); solution = solution.substring(0, solution.length - 1); } //extends the number with a larger digit if (digit != 9) { solution += bigger; recurse(bigger); solution = solution.substring(0, solution.length - 1); } } }