DEV Community

Discussion on: Can you solve this interview problem?

Collapse
 
nombrekeff profile image
Keff

Some people just want to see the world burn lol!!!!

Fun exercise nonetheless, here is what I came up with in 5 minutes. I did it in NodeJS though.

A couple of notes on the solution:

  1. It only works with simple urls as the one mentioned in the example, it wont work if the URI has query params, or more complex structure
  2. I had to google how to do permutations as I have never needed to use it in the real world
  3. If we wanted to check for more complex urls, we could update the isValidUrl function to do so, without changing anything else

But basically the logic is this:

  1. Convert string into an array by removing unnecessary characters ([]") and then split by comma (,)
  2. Permutate the array
  3. Filter all non-valid urls
  4. What you're left with is the correct URL
const permutator = (inputArr) => {
    let result = [];

    const permute = (arr, m = []) => {
        if (arr.length === 0) {
            result.push(m);
        } else {
            for (let i = 0; i < arr.length; i++) {
                const curr = arr.slice();
                const next = curr.splice(i, 1);
                permute(curr.slice(), m.concat(next));
            }
        }
    }

    permute(inputArr);

    return result;
}

const isValidUrl = (candidateUrl) => {
    return /^https:\/\/dev.to\/([\w0-9]+\/?)+$/i.test(candidateUrl);
}

const array = url.replace(/[\[ \]"]/g, '').split(',')
const correctUrl = permutator(array)
    .map(p => p.join(''))
    .map(s => Buffer.from(s, 'base64').toString())
    .filter(isValidUrl)
    .pop();

console.log(correctUrl);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
0shuvo0 profile image
Shuvo

Nice 💓