DEV Community

Cover image for Can you solve this interview problem?
Shuvo
Shuvo

Posted on

Can you solve this interview problem?

So few days ago I applied to a MNC and I had some interesting problems to solve in given amount of time. So let me share one with you, see if you can solve this.

Problem Description

So let's say we have a URL something like this:

let url = "https://dev.to/0shuvo0"
Enter fullscreen mode Exit fullscreen mode

Now they have converted the url to a base64 string.
So the URL have become something like this:

let url = "aHR0cHM6Ly9kZXYudG8vMHNodXZvMA=="
Enter fullscreen mode Exit fullscreen mode

Now what they did was split the sting to multiple parts and convert into an array

let url = ["aHR0cH", "M6Ly9kZX", "YudG8vMHN", "odXZvMA=="]
Enter fullscreen mode Exit fullscreen mode

But of course the madnesses doesn't stop here. Then the shuffled the array so it became something like this:

let url = ["M6Ly9kZX", "aHR0cH", "odXZvMA==", "YudG8vMHN"]
Enter fullscreen mode Exit fullscreen mode

And lastly they have converted that array to a string.

So here is your input

let url = `[ "6Ly9kZXYudG", "9jb21tZW5", "8vMHNodXZvMC", "aHR0cHM", "0LzFqZTFt" ]`
Enter fullscreen mode Exit fullscreen mode

Use the input to find the original URL programmatically you have 45 Minutes to do it.

Useful JavaScript functions that can help you

  • You can convert your array to sting by calling join method on it. Eg.
let urlStr = url.join("")
Enter fullscreen mode Exit fullscreen mode
  • You can use atob function to decode the base64 string.
let decoded = atob(urlStr)
Enter fullscreen mode Exit fullscreen mode

Now go and and see if you can solve this. Best of luck πŸ‘

0shuvo0 image

Was it useful? Support me on Patreon

Patreon Logo

Discussion (65)

Collapse
inhuofficial profile image
InHuOfficial • Edited on

Yes I can solve the interview problem (as in, the problem with interviews in the industry in general!).

I would look at the person interviewing me dead in the eyes and ask "who hurt them". What made them think in any way this question remotely resembles something you would need to do in the real world?

I would look at them asking why on Earth they thought it was a good interview question, what skills it proved I had that I would need to learn and just generally ask them why we can't create an interview process that actually proves talent.

I would ask them what happened to our industry where they thought this question is remotely useful and then would slowly rise from my seat, thank them for the opportunity and walk to the door.

Just as the door is about to close I would say "And please can I have the 🍬 treat 🍬 you promised me for solving it" and walk away, still searching for a company that doesn't ask dumb interview questions. πŸ˜‰πŸ€£

Being Serious for a second, besides the dig at our industry and it's stupid interview practices it was a fun little brain teaser. Have a β€πŸ¦„ for a nice morning wake up challenge!

Collapse
nombrekeff profile image
Keff

Yeah, I would run away from there as fast as possible. Can't imagine what the interviewer could do, seems like a psychopath really.

Just kidding, but I agree, this is not the type of question we should be asking in an interview, it shows nothing of value for the real world. I think this is more of a practice exercise for begginers more than anything. Though it's a fun little problem

Collapse
0shuvo0 profile image
Shuvo Author

Actually it was really interesting
Because the like you'd finally decode would lead you to the next step of recruitment

Thread Thread
inhuofficial profile image
InHuOfficial • Edited on

Haha now this would make it more interesting as remote interview technique, you can only proceed to the next step if you can decode the link.

You could also make it time sensitive so if they take too long to complete the task the link expires!

Still hate questions like this (yet again, not a stab at you, just our industry), but that line of thinking, a "follow the breadcrumbs" type of coding interview, that is an awesome and fun idea 🀣

Thread Thread
nombrekeff profile image
Keff

That's really cool, gamifing it and making it somewhat of a puzzle. I guess the complexity would increment as you solved more steps right?

Thread Thread
nombrekeff profile image
Keff

Yup, that's quite cool actually, making the process a bit more fun.

0shuvo0 profile image
Shuvo Author • Edited on

Yes, there also as time limit of link

Thread Thread
0shuvo0 profile image
Shuvo Author

maybe if we prove P = NP the way they Interview people will also change πŸ˜…

Thread Thread
moopet profile image
Ben Sinclair

You're saying it would be a valid question as part of a trail of clues?
I've always liked those provided they have any logical reasoning behind them. But this one doesn't, this one has two options:

  1. it gives you the steps they took toobfuscate their string and you have to reverse that, and maybe throw some permutations in there until you get the right answer, and hope that there isn't more than one answer that is a valid URL.
  2. it gives you the string and says "get on with it"

1 is an exercise demonstrating you can do a few different tasks, laid out more like chores, and 2 could be absolutely anything and is a game of nonsense rather than any kind of logical or lateral thinking.

Collapse
mudlabs profile image
Sam

Structuring interview questions at any company should be straight forward. Compile issues the company has actually faced and overcome recently. From that list produce question related to the role so you can see if a candidate can at best solve problems the company tends to have, or at least demonstrates good reasoning around those issues.

Collapse
lukeshiru profile image
LUKESHIRU

This! This right here is the reason I follow @inhuofficial

Collapse
inhuofficial profile image
InHuOfficial • Edited on

Sarcastic and snarky comments? 😜🀣

stop being so nice to me, my head won’t fit through the door πŸ˜‰β€οΈ

Thread Thread
lukeshiru profile image
LUKESHIRU

Maybe is the fact that you save me the time of writing something similar 🀣

Thread Thread
inhuofficial profile image
InHuOfficial

🀣 β€œgreat minds think alike”…or is it β€œfools seldom differ”, I will go for β€œgreat minds” as I don’t want to drag you down with me 😜

Collapse
0shuvo0 profile image
Shuvo Author

And yes its quite fun πŸ˜…
The permutation part is what people struggles to figure out

Collapse
0shuvo0 profile image
Shuvo Author

What kind of question would be good to know interviewees problem solving capability in about an hour?

Collapse
inhuofficial profile image
InHuOfficial

The concept is to build upon previous bits to show a persons thought process and how they organise (and reorganise) code.

Needs some refinement but I think a concept like this is way better.

Thread Thread
0shuvo0 profile image
Shuvo Author

You can't have such basic one for intermediate or senior role

Thread Thread
inhuofficial profile image
InHuOfficial

If you think it is too easy for senior devs then you can add more complexity.

It is the concept and what it looks at that is more important.

Instead of us testing if they can remember some obscure algorithm (that you would just look up) you can assess their thought process.

If you read the article you will see that the actual problems are not what is being tested, instead we are testing:

  • their thought processes,
  • refactoring,
  • thinking about extensibility,
  • following instructions and briefs and knowing where to ask questions etc.

These are the skills that matter in a team, I don't care if you can write a "travelling salesman problem" solve from memory, I just care that you can order your thoughts into a logical path to complete a given challenge in the real world and create code that is easy to maintain.

Also, it is just a concept, you can make it as difficult as you want by just adding harder requirements after point 8.

Thread Thread
0shuvo0 profile image
Shuvo Author • Edited on

To be honest I never liked CP
My leetcode rating it 1 star
But most tech companies will either demand a degree which I don't have or good cp skills

Thread Thread
inhuofficial profile image
InHuOfficial

Yeah, and that is half the issue as it skews the thought process!

It is always fun seeing how people spend months practicing coding interview problems who have been developing for years as it isn't what they do each day!

I always imagine it to be like a lorry driver being asked how to replace a clutch...kind of related but doesn't tell you how good they are at driving and a skill they will probably never need to use! 🀣

Thread Thread
0shuvo0 profile image
Shuvo Author

Maybe some day it will change

Collapse
0shuvo0 profile image
Shuvo Author

Many DSA/CP related questions won't resemble something you would need to do in the real world

Collapse
brunnerh profile image
brunnerh

If nothing is known about the URL beforehand, this seems underspecified. There are multiple valid URLs that can be constructed from the fragments.

function permutate(arr) {
    if (arr.length == 1) return [arr];

    return arr.map((item, i) => {
        var rest = [...arr];
        rest.splice(i, 1);
        return permutate(rest).map(x => [item, ...x])
    }).flat();
}

permutate(JSON.parse(url))
  .map(x => atob(x.join('')))
  .map(x => { try { return new URL(x).toString() } catch { return null } })
  .filter(Boolean);
Enter fullscreen mode Exit fullscreen mode

Yields:

https://dev.xn--tocommen%7C1414%20-oqa05ipa4v8fnd624dn60pha/1je1m
https://dev.tocomment/1je1m%C3%B2%C3%B3%076%C2%87Wf%C3%B3
https://dev.to/0shuvo0/comment/1je1m
https://dev.to/0shuvo0-%0B%C3%8CZ%C2%99L[%7D%C2%8D%C2%BD%C2%B5%C2%B5%C2%95%C2%B9
Enter fullscreen mode Exit fullscreen mode
Collapse
0shuvo0 profile image
Shuvo Author

You can take those multiple URLs as a challenge as well
Like sending https request to see the status

Collapse
brunnerh profile image
brunnerh

Those are additional assumption about the URL, though:

  • It uses a common web protocol like HTTP/HTTPS
  • There actually is a reachable server that would reply to those requests
Collapse
rushannotofficial profile image
Rushan S J

Hey, I got the solution. The only thing is that I'm more familiar with python but the same logic applied in other languages too.

import itertools, base64

originalarray = ["6Ly9kZXYudG", "9jb21tZW5", "8vMHNodXZvMC", "aHR0cHM", "0LzFqZTFt"]     # this is the input 

for i in itertools.permutations(originalarray, len(originalarray)):  # getting all possible combinations
    tmpdecodedstring = ""
    for k in i:     # iterate over each strng in the array and add it to the string
        tmpdecodedstring += str(k)
    try:
        print("URL is: " + str(str(base64.b64decode(tmpdecodedstring)).decode()))  # decode the string finally
    except:
        pass # only proper base64 string dont raise an error. If there is a error, that means that the string is incorrect and we try another permutation.
Enter fullscreen mode Exit fullscreen mode
Collapse
0shuvo0 profile image
Shuvo Author

Great

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 Author

Nice πŸ’“

Collapse
lukeshiru profile image
LUKESHIRU

Can you solve this interview question?

Yes

Should you?

If you want, just for fun, do it, but ideally you shouldn't waste your time in companies that see any kind of value in stuff like this.

Like the meme, this kind of questions in interviews translate to 🚩🚩🚩🚩🚩🚩🚩🚩🚩🚩

Collapse
microtot profile image
MicroTot • Edited on

This is the worst implementation here, but it workd

let url = ["aHR0cHM", "6Ly9kZXYudG", "8vMHNodXZvMC",  "9jb21tZW5",  "0LzFqZTFt" ]
var joinedUrl = url.join()
console.log(joinedUrl)

var result = joinedUrl.replace(/,/g, "")
var decoded = atob(result)
console.log(decoded)
Enter fullscreen mode Exit fullscreen mode

Output:

[LOG]: "https://dev.to/0shuvo0/comment/1je1m" 
Enter fullscreen mode Exit fullscreen mode
Collapse
choroba profile image
E. Choroba

A Perl solution I was able to write in less than 5 minutes:

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

use MIME::Base64 qw{ decode_base64 };
use List::Util qw{ shuffle };

my $cipher = '[ "6Ly9kZXYudG", "9jb21tZW5", "8vMHNodXZvMC", "aHR0cHM", "0LzFqZTFt" ]';

my @strings = $cipher =~ /"([^"]+)"/g;

my $string = "";
until ($string =~ /^[ -~]+$/) {
    @strings = shuffle(@strings);
    $string = decode_base64(join "", @strings);
}
say $string;
Enter fullscreen mode Exit fullscreen mode
Collapse
0shuvo0 profile image
Shuvo Author

Nice

Collapse
sharpninja profile image
The Sharp Ninja

The == goes at the end, so you only have to figure out the positions of 3 strings, or 9 combinations. Just brute force it and the first one that decodes to a string that starts with "http" and is well formed with a real dns name is your winner.

Collapse
jefflindholm profile image
Jeff Lindholm

This sounds like some of the 'oldschool' brain teasers (example: 'Why are manhole covers round?' -- which of course I answer 'because manholes are round, any other shape would be silly')
At least this is asking for you to code something vs. just ask if you know trivia.

Collapse
francisc profile image
Francisc

Looks like they were trying to find out the url to their app. For how they treated the ex-developer, he told them in his last day at the office: " I am quitting. But since you are so smart, I have moved your app to this url kjashdfkjashfkjashfkasjhiuoawuiy98ufasif. Now let the next guy find where your app is."

Collapse
0shuvo0 profile image
Shuvo Author

Savage

Collapse
enygma2002 profile image
Eduard Moraru • Edited on

Here's my not-so-fancy recursive solution :)

let url = [ "6Ly9kZXYudG", "9jb21tZW5", "8vMHNodXZvMC", "aHR0cHM", "0LzFqZTFt" ]

function testUrl(testUrl) {
  return/^[\x00-\x7F]*$/.test(testUrl);
}

function test(segments, currentString) {
  //console.log("try(segments: " + segments + " currentString: " + currentString)
  if (segments.length == 0) {
    let decoded = atob(currentString)
    if (decoded.startsWith("https://") && testUrl(decoded)) {
      console.log("Encoded: " + currentString)
      console.log("Decoded: " + decoded);
    }
  } else {
    for (let i=0; i<segments.length; i++) {
      let newString = currentString + segments[i];
      let remainingSegments = segments.slice(0, i).concat(segments.slice(i+1, segments.length))

      test(remainingSegments, newString)
    }
  }
}

test(url, "")
Enter fullscreen mode Exit fullscreen mode

Outputs:

Encoded: aHR0cHM6Ly9kZXYudG8vMHNodXZvMC9jb21tZW50LzFqZTFt
Decoded: https://dev.to/0shuvo0/comment/1je1m
Enter fullscreen mode Exit fullscreen mode
Collapse
d3skdev profile image
d3skdev
Collapse
0shuvo0 profile image
Shuvo Author

Seems like your code only works is it elements of array is in a particular order

I shuffled the array again and its not working

let url = `[ "6Ly9kZXYudG", "9jb21tZW5", "8vMHNodXZvMC", "aHR0cHM", "0LzFqZTFt" ]`;

const base64 = JSON.parse(url);
const sort = base64.sort(() => 0 - Math.random()).join("");
const decode = atob(sort);

document.getElementById("url").innerHTML =  decode;
Enter fullscreen mode Exit fullscreen mode
Collapse
d3skdev profile image
d3skdev

i see, please check my update

Thread Thread
0shuvo0 profile image
Shuvo Author

It works
Pro tip: you can optimize it by first getting the permutation of the array

Collapse
jayakrishnancn profile image
jayakrishnancn

Quick question, why did you use sort(() => 0 - Math.random()) ?
to reverse sort?

Collapse
sarathm09 profile image
sarathm09

No, it shuffles the array elements. Basically he is shuffling the array again and again till he gets it right

Collapse
0shuvo0 profile image
Shuvo Author

You solved it? Great πŸ‘

Collapse
0shuvo0 profile image
Shuvo Author

Have a treat 🍬

Collapse
kb1hyr profile image
kb1hyr

Convert the strings in each array element back to base64, then iterate through each possible combination until you find one that, converted back into a string, starts with http. This is aided by the fact the last array element will always end in ==.

Collapse
Sloan, the sloth mascot
Comment deleted
Collapse
0shuvo0 profile image
Shuvo Author

Actually it doesn't decode to dev.to/0shuvo0
And you won't know the expected URL beforehand

Collapse
itr13 profile image
Mikael Klages

Ignore the input and ddos their site with random urls until you find the correct url.

Personally I would decline to solve their challenge and show them source code I've written in the past, though honestly, this specific question sounds like a big red flag.

Collapse
documentednerd profile image
Kevin Mack

I fail to see how this interview problem does anything other than play "stump the chump." Realistically interviews are about determining if a person's skills, and personality are a fit for the team, and the work being done. How does this accomplish any of that? I can't think of a single time that this scenario would be applicable to an actual project. And I am of the belief that at any interview, "you are interviewing them, as much as they are interviewing you." This would speak volumes to me as part of a terrible "Know-it-all" / gate keeper culture that I would not want to be a part of.

Collapse
thacken profile image
Chris Thackrey

This was a fun problem I haven't crossed paths with before, please consider sharing more like this!

Collapse
0shuvo0 profile image
Shuvo Author

Many thanks.

Collapse
joeattardi profile image
Joe Attardi

What a ridiculous interview question.

Collapse
ky1e_s profile image
Kyle Stephens

I sincerely hope nobody is being asked questions like this in interviews.

/ends

Collapse
crimson589 profile image
crimson

I don't want to code but is it...

  1. Turn String back to array (JSON.parse)
  2. Join the array values together
  3. decode the value
  4. Check if it was decoded successfully and if the result was a valid URL
  5. If not, join the array in another sequence and repeat step 2

?

Can probably shorten it by always putting the string with an equal sign at the end and just looping the rest.

Collapse
0shuvo0 profile image
Shuvo Author

Yes but there might be multiple valid URL tho

Collapse
sully8665 profile image
Sully8665

Solved it in 30 mins :)

Collapse
0shuvo0 profile image
Shuvo Author

That's great 🚀

Collapse
0shuvo0 profile image
Shuvo Author

Glad you liked it

Collapse
thatanjan profile image
Anjan Shomooder

I would add little more complexity.
remove all elements from the array. Now solve it.πŸ˜‚

Collapse
0shuvo0 profile image
Shuvo Author

and don't even tell them about the problem at all