Word Reversal Code Challenge

Here’s the scenario, you are given a string s that contains a sentence and your task is to write a word reversal function to reverse the order of all words that are longer than n characters.

Example:

  • s = The quick brown fox
  • n = 4

Then the result should be “The kciuq nworb fox”

Word Reversal Direct Approach

I always advocate for trying the direct approach before you start doing weird optimizations. So How could we approach this manually? Well first we’d need to split the words, then check each word and reverse it if it is longer than n:

const reverseWord(s,n) => {
    const words = s.split(" ")
    const reversedArray = words.map(word => {
        if (word.length > n){
            return word.split("").reverse().join(")
        }
        return word
    })
    return reversedArray.join(" ")
}Code language: JavaScript (javascript)

Great, this accomplishes our goal. So if you’re in an interview, I’d advise starting with this because in an interview your time is limited and it’s much better to submit something that works rather than spend all your time trying and potentially failing to do the best approach.

Can we do better?

But, just for fun, let’s see if we can get a better approach.

The first question we need to ask ourselves is what do we know about the problem? We know;

  • s is a string with a sentence in it
  • n is an integer
  • we want all words in s whose length is greater than n

This would seem to suggest looping through each word right? Not necessarily. What if we could just get the words that matched our requirements? If only there was some technology that could do that search for us that… oh wait, we do… regex. And even better we have a built-in function that accepts it and replaces the found words. So we can easily solve the same problem as follows

const reverseWord = (s, n) => {
    const re = new RegExp(`\\w{${n},}`,"g");
    return s.replace(re, word => {
        return word.split("").reverse().join("")
    })
}Code language: JavaScript (javascript)

Way smaller right? But there is an argument to be made about whether it’s more or less readable. I know regex isn’t everyone’s favorite technology so it’s up to you.

Fun fact, there is a bug in the code. Can you spot it? I was going to fix it but I thought it would make a nice easter egg. So if you find it, let me know on Twitter, @phoexer.

Till next time, happy coding.