1. Reverse a String

Let's go back to our whiteboarding steps to understand how to best solve this problem.

Define the Problem

In this case, the problem is relatively simple: we need to reverse a string. This may sound like a question that wouldn't be asked, but it's one of the most common questions we've found in our search for frequently asked interview questions.

Let's bring back Jonathan as our interviewee and get started.

Jonathan: Do I need to create a function that passes in a string as an argument and then returns a reversed string? Should I also console.log the reversed string?

Interviewer: Yes.

Jonathan: I'll be using JavaScript to solve this; is that okay?

Interviewer: Yes.


Think

Jonathan thinks about the problem for a bit. He's already starting to come up with a solution and writes out some of his thoughts on the board. Here's his pseudocode:

// Create function that will take in a string and output a reversed string
  // Create variable to store reversed string
  // loop through string and go through each character in the string backwards, starting with last character
    // Within loop, concatenate each letter in string to variable declared earlier.
  // Log reversed string
  // return reversed string

// Call function

Write Code and Syntax

Now that the hard part is done, Jonathan just needs to write out the syntax to fill in the pseudocode. As Jonathan is writing the function, he explains his steps.

The first part of the whiteboard code looks like the following:

// Create function that will take in a string and output a reversed string
    function reverseStr (str) {
        // Create variable to store reversed string
        var revStr = '';
        // loop through string and go through each character in the string backwards, starting with last character
        for (var i = str.length - 1; i >= 0; i--) {
            // Within loop, concatenate each letter in string to variable declared earlier.
            revStr += str[i];
        }
    }

Jonathan: I first create a function that will take in a single argument, representing the string. I then create the logic that will reverse the string by creating a for loop to go backward through the string, starting with the last character in the string. The result is a reversed string stored in revStr.

// Create function that will take in a string and output a reversed string
function reverseStr (str) {
// Create variable to store reversed string
    var revStr = '';
    // loop through string and go through each character in the string backwards, starting with last character
    for (var i = str.length - 1; i >= 0; i--) {
        // Within loop, concatenate each letter in string to variable declared earlier.
        revStr += str[i];
    }
    // Log reversed string
    console.log(revStr);
    // return reversed string
    return revStr;
}
// Call function
reverseStr("I want to be reversed");

Jonathan: Finally, we log the string, return the string to the function, and then call the function to execute to the function.

Interviewer: Can this function perform some validations to make sure it's a string being passed in? Also, this method may work better in newer browsers, but what about older ones?

Jonathan: The current function definition doesn't contain data validation nor is it optimized for older browsers. Let me make those changes now.

// Refactor function with data validation and increased efficiency in older browsers
  // Initialize variable to store reversed string in an array
  // Put data validation for data type, length, and falsy values
  // Create similar for loop as before, but instead pushing to the variable.
  // Join and console.log/return revStr
function reverseStr(str){
  var revStr = [];
  if(!str || typeof str != 'string' || str.length < 2 ) return str;

for(var i = str.length-1; i>=0;i--){
    revStr.push(str[i]);
  }
  var arrRevStr = revStr.join('');
  console.log(arrRevStr);
  return arrRevStr;
}

Jonathan: I've put in some data validation now to make sure information was passed in. I also added a validation to allow for strings only, as well as added a check to make sure the length of string is at least more than 1. If any of the validations fail, the string is returned back to the client. I then improved the efficiency of the loop by using an array to push items into and returning them. This accounts for older browsers.

Interviewer: Good. Can you use a built-in method to make it a bit cleaner?

Jonathan: Hmm, let me think.

Jonathan takes some time to think, and then comes up with a possible solution while pseudocoding:

// Create function to reverse string
  // Put simple conditional for data validation. String validation not needed, since methods will only work on string.
  // Use split, reverse, and join methods to reverse string and store in variable
  // console.log and return str
function reverseStr(str){
  if(!str || str.length <2) return str;
  var revStr = str.split('').reverse().join('');
  console.log(revStr);
  return revStr;
}

Jonathan: I've reduced the number of lines of code by chaining some built-in methods together. I first converted the string to an array using split, and then used the reverse method to reverse the elements in the array. Finally, I joined them back together into a string using the join method, and then logged and returned the string.

Interviewer: Good.