DEV Community 👩‍💻👨‍💻

Cover image for Road to Genius: superior #51
Ilya Nevolin
Ilya Nevolin

Posted on

Road to Genius: superior #51

Each day I solve several coding challenges and puzzles from Codr's ranked mode. The goal is to reach genius rank, along the way I explain how I solve them. You do not need any programming background to get started, and you will learn a ton of new and interesting things as you go.

function backtrack(list, tempList, nums, start) {
    list.push([...tempList]);
    for(let i = start; i < nums.length; i++) {
        tempList.push(nums[i]);
        backtrack(list, tempList, nums, i + 1);
        tempList.pop();
    }
}

function subsets(nums) {
    const list = [];
    backtrack(list, [], nums, 0);
    return list;
}

let A = subsets([1, 2, 1]);
A = A.length

// A = ? (number)
Enter fullscreen mode Exit fullscreen mode

In today's challenge we have to deal with recursive backtracking. The caller function subsets reveals the nature of the code, it's going to create a list of different subsets from a given input. In this case subsets are similar to unique combinations, except they are not required to be unique.

coding challenge extra

For input: [1, 2, 1]
We expect the following subsets:
1
1 2
1 2 1
1 1
2
2 1
1
Enter fullscreen mode Exit fullscreen mode

There are 8 subsets possible so the answer should be as such:
coding challenge answer

If you work out this problem on paper you will find these exact subsets.

By solving these challenges you train yourself to be a better programmer. You'll learn newer and better ways of analyzing, debugging and improving code. As a result you'll be more productive and valuable in business. Get started and become a certified Codr today at https://nevolin.be/codr/

Latest comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.