JS Interview Prep: Reverse a String

in #javascript7 years ago (edited)

Screenshot of Google Chrome (11-23-17, 9-09-30 PM).png

If you're ever interviewing for a developer job the expectation you should have is to answer some type of algorithm, white-boarding, or architecture question. I want to provide a gentle introduction to some of the questions I've encountered and prep my readers on questions you could potentially expect. The format of each of my posts will generally work like this

  1. Question
  2. Answer // Why does it work?
  3. Conclusion // Last thoughts

Note: There will be times where I can provide more than one solution.

Without further ado lets begin!

Question

Given a string, return the new string with the reversed order of characters.

reverse('dog') === 'god'
reverse('hello') === 'olleh'
reverse('yolo') === 'oloy'

Answer

There are many ways you can solve this problem. If you have the option to utilize javascript's built in functions like reverse() then I would recommend the solution below.

Solution 1

function reverse(string) {
  return string
    .split('')
    .reverse()
    .join('');
}

Explanation

  1. split the input string into an array. For example, if the string was "dog" the array would look like ['d', 'o', 'g'].
  2. reverse the array. `['g', 'o', 'd']
  3. merge the elements together via join. god

Solution 2

In the case your interviewer does not allow you to use the reverse function. You can try the solution below

function reverse(str) {
  return str.split('').reduce((acc, curr) => {
    return curr + acc;
  }, '');
}

Explanation

Similar to solution 1, the string needs to be split into an array. After the array is split you can utilize javascript's built in function called reduce. Reduce is a type of looping function. In the example above, acc is the accumulated value and curr is the current element in the loop. So if the input was dog. The pseudo result of what is actually happening is shown below.

dog split --> ['d', 'o', 'g']

[dog] reduce -->

# curr = 'd', acc = ''
return 'd' + '' --> 'd'

# curr = 'o', acc = 'd'
return 'o' + 'd' --> 'od'

# curr = 'g', acc = 'od'
return 'g' + 'od --> 'god'

Conclusion

There are many other solutions that exist for this particular problem, but I hope the two I provided makes sense. This is the first attempt at providing solutions so feedback is definitely welcome! Have a good Thanksgiving everyone!

Resources:

Reduce Function


Split Function


Reverse Function


Join Function

Coin Marketplace

STEEM 0.26
TRX 0.20
JST 0.037
BTC 94544.61
ETH 3425.86
USDT 1.00
SBD 3.91