DEV Community

Cover image for How to approach solving a challenge during a coding interview

How to approach solving a challenge during a coding interview

Ady Ngom on May 13, 2019

Like many things in life, mastery requires practice and the coding interview is no exception. Often times though, the focus is on trying to find th...
Collapse
 
gypsydave5 profile image
David Wickes

Hi Ady! Can I leave you some comments?

Tests. There are no tests around this code. I'm not saying you need to do test-driven development. But if you're going to perform refactoring on a codebase it's important that you're covered by tests that will tell you whether you've introduced a bug while you're ~showing off~ cleaning up the code.

You could argue that this is unimportant for something as trivial as Fizz Buzz - you can easily perform manual testing of your single function with a few select cases. But I would say that, during a coding interview, it's really important to treat the problem with the same respect that you'd give to any program you'd write professionally. It's a real opportunity to show off how you like to work and how you think.

A few test cases, which can be run quickly, can easily demonstrate the interviewer that you've not introduced any regressions in your code.

Other than that, I like where you took the code in the end (but I think there's an even more ridiculous iteration you could get to in one line).

Collapse
 
adyngom profile image
Ady Ngom

You bet you can leave comments David and what a great contribution.

Regarding TDD I think it can definitely be something to ask at the top of the exercise, you would be surprised that some of the companies would tell not be too worried about it in the interview context but will definitely like that you are thinking that way.

Most of the times, the TDD aspect will be raised as a follow-up question regarding quality and maintainability. I even had many scenarios of where the setup will be a stub function with failing tests and the exercise was to make the tests pass and add more if needed.

I totally agree that, as an interviewer, I would highly think of a candidate who talks and write tests from the get-go. I will probably add a section in the article of what it could look like.

Now regarding one liners :)
I actually have come up with about three of them while I was deep diving, and I still came back to the final solution of the article for a few reasons but mainly for:

  • intuitiveness: I can scan real quick and see the logic and have an idea of what's going on
  • readability: I did not squint
  • no significant gain: either in performance or anything else since dev code gets minified anyways before prod

For the one-liners, even I was the one who came up with the solution I still needed a minute to remember how I got there so I can only imagine if someone else was to review my code.

I agree that it is subjective and might be about coding culture and style.

Please add the fix for the iteration. I'll be happy to add it as an option to the article.

Cheers

Collapse
 
johnboy5358 profile image
John

Hi Ady,

With regards testing and your final code for fizzBuzz...


function fizzBuzz( start = 1, end = 100) {
    for( let i = start; i <= end; i++) {
        let output =  ( (i % 3) ? '' : 'Fizz' ); // output is assigned a value or empty
        output += ( (i % 5) ? '' : 'Buzz') ; // output concatenates the next value
        console.log(output || i); // || or operator if output is falsy will show i value
    }
}
fizzBuzz(1,15);


Since testing was mentioned previously, I would like to hear more about your strategy for testing functions that do not have a useful return value (fizzBuzz returns undefined; output is only via console.log).

Perhaps, a follow up post to cover this would be interesting.

Thanks for the post.

Thread Thread
 
adyngom profile image
Ady Ngom

Hey John nice to hear from you. Yes will certainly do a follow up and just today someone was asking testing during a lecture.
Will address it aASAP.
Cheers

Thread Thread
 
johnboy5358 profile image
John

Thanks Ady, I will await your future post on the subject, but in the meantime, I can see a way that fizzBuzz could be tested although it would need some modification from it's present form.

Thread Thread
 
adyngom profile image
Ady Ngom

Great please do share your solution if you do not mind. As I mentioned the one proposed is a personal preference and there are many other ways to solve for it.
Testing for it should also be pretty straightforward. If console.log is an issue we could build and return an array of outputs in the function and write a test for small subsets.

Collapse
 
jeddevs profile image
Theo • Edited

Hello,
Not a javascript user here, (python and lua). Still found this a very insightful read.

I would like to add that simlifying code to such a degree to take up less lines can make it less readable, overall not making the end product much better in my opinion.
(Correct me if i'm wrong 🙂.)
But it's certainly interesting to see!
(Even if my limited understanding of js restricted me from understanding the final final solution fully.)

I quickly opened up trusty repl and did one up in python:

def FizzBuzz():
  for i in range (1,101):
    #print(i/3)
    if i%3 == 0 and i%5 == 0:
      print("FizzBuzz")
    elif i%3 == 0:
      print("Fizz")
    elif i%5 == 0:
      print("Buzz")
    else: 
      print(i)
FizzBuzz()
Collapse
 
jeddevs profile image
Theo • Edited

I also wrote one up in lua, because I have um, no uh, life. 😊

function FizzBuzz()
  for i = 1,100 do
    --print(i)
    if i%3 == 0 and i%5 == 0 then
      print("FizzBuzz")
    elseif i%3 == 0 then
      print("Fizz")
    elseif i%5 == 0 then
      print("Buzz")
    else
      print(i)
    end
  end
end
FizzBuzz()
Collapse
 
theodesp profile image
Theofanis Despoudis

Lua rocks

Collapse
 
adyngom profile image
Ady Ngom

"...because I have um, no uh, life" haha welcome to the club :)

Collapse
 
adyngom profile image
Ady Ngom

Very readable and does the job for someone who does not code in Python. Life is complicated already, code does not need to be :)

Collapse
 
jeddevs profile image
Theo

Merci Monsieur!

Collapse
 
steelwolf180 profile image
Max Ong Zong Bao

Really cool that you break it down part by part.

I think TDD is good only when you are testing a non-junior engineer with very liberal amount of time to work on it.

Instead of a time crunch of within 1 hour for a coding challenge.

Collapse
 
adyngom profile image
Ady Ngom

Glad you like it Max. I agree that regarding TDD level and time will play a key role here. A good interviewer would not hesitate to take the driver seat in carrying the session towards anything that can add value and overall help the candidate shine.

Collapse
 
vivecuervo7 profile image
vivecuervo7

Out of curiosity, how would it end up looking if you'd clearly solved the problem before and are simply typing in the solution?

I was given this task as a challenge in the bootcamp I'm enrolled in, my first instinct was to jump straight for a nested ternary. After some thinking I then went for the string concatenation (using Ruby in this particular case).

The concern is that my natural instinct to go with ternary may have appeared to be a "he's done this before" despite that not being the case - but now that I've solved it, it would be difficult for me to not just type in my cleanest solution.

How would one navigate this in an interview? Type it in, commenting that you'd previously done the challenge? Alert the interviewer to the fact at the risk of sounding cocky? Play it stupid and solve through more simplistic steps that really wouldn't occur to you naturally?

Collapse
 
adyngom profile image
Ady Ngom

Hello and thank you for the great question. I have been itching to do actually a full article on this particular subject and I think it's time to put it together, so coming up soon.

In the meantime, I want to take a second and state that having someone who has been exposed to the problem before is not a bad thing at all. It simply shows someone who is well prepared or who has experience.

Now, if they pretend that they have never seen it and 'fake' their way to the solution, I personally feel like that does not reflect as an honest trait of character and any savvy interviewer will not be fooled by it.

I personally think that an interview shouldn't be a disconnected exercise or a trivia showdown of things that have no connection with something that a candidate has been doing long enough to have proficiency in it.

It should be expected that the canditate has seen or been exposed to a similar exercise before. Now it's up to the interviewer to craft a good exercise with the right follow up questions that can reveal depth, understanding, style and culture. For that to happen though the interviewer has to be solid and knowledgeable on the discipline. Sometimes, unfortunately, that is not the case..

Let me finish off with a somewhat relatable example. Let's say you are a private cab company that wants to hire a professional driver that knows the city well and can find the best routes to optimize travel time.

Let's say Main Street and 1st is the most impossible intersection at certain times of the day, but there are ways around it. I'm pretty sure that a savvy local driver might've encountered it many times before. Why wouldn't I want to hear his take and experience about it? I probably would ask them about how they would navigate from certain points without GPS. Essentially I would ask them about what they know and what they have been actually challenged and solved for.

The above example might be a stretch, but I honestly believe that it does not matter at all. I'm even an advocate of having the candidate review all the possible questions that I would evaluate him/her before coming on site. I think that they will be more relaxed which is a win for everyone. The 'depth' conversation will even be richer from that perspective.

Collapse
 
vivecuervo7 profile image
vivecuervo7

Thanks for the response! With regards to your cab analogy, it seems the best approach would essentially be to write down said cleanest solution and while doing so, discuss why it was chosen over other approaches and the possible pitfalls, and how one would circumvent them if they were included in the scope of the question.

I guess it can be an opportunity to show that you're capable of seeing how your solution may need to adapt to slight changes in requirements - I believe the way I solved this in Ruby would have failed with numbers where the length exceeded that of the "Fizz/Buzz" and I'd imagine addressing this while writing the solution would demonstrate a good ability to criticize one's own code.

Appreciate the response - opened my eyes to a different way to approach already known solutions!

Thread Thread
 
adyngom profile image
Ady Ngom

Yes, the whole point is to dig as deep as possible to assess levels of understanding. I, for example like the formulation of "How would you explain the concept of closures to a junior developer and to a non technical person?" versus "What is a Javascript closure? Provide some examples"
I think the first one is more prone to reveal depth in understanding than the second formulation which by the way is the most popular screening question in Javascript.
Thank you for adding to the discussion, I surely appreciate the comments.

Collapse
 
leob profile image
leob

I would approach it "top down" with pseudo code:

for i = 1 to 100 do
    fizz = isMultiple(3, i)
    buzz = isMultiple(5, i)

    if fizz & buzz
       output 'FizzBuzz'
    elseif fizz
       output 'Fizz'
    elseif buzz
       output 'Buzz'
    else
       output i
    endif
next

Then all that's left is to write the 'isMultiple' function ;-)

Collapse
 
adyngom profile image
Ady Ngom

Pseudo code is synonym to thinking out loud in an interview context and is a golden approach that I personally highly recommend.
Awesome stuff and thank you for sharing :)

Collapse
 
delta456 profile image
Swastik Baranwal

Amazing! Thanks for sharing!

Collapse
 
adyngom profile image
Ady Ngom

Awesome glad you like it. Cheers

Collapse
 
manish169 profile image
Manish

A nice and simple explanation of things.
The thing you said about managing pulses in the interview is absolutely true. This happens to me In every interview.

Collapse
 
anuraghazra profile image
Anurag Hazra

We could do (!(i % 15)) right?

Collapse
 
adyngom profile image
Ady Ngom

yup you could as well always try to read out your conditionals in plain English to make sense of out them. So if I was to replace i with 10 or 15 using your construct I would be saying
is (10%15) falsy? is (6) falsy? No
is (15%15) falsy? is (0) falsy? Yes