How to Reverse an array or string in a different way

How to Reverse an array or string in a different way

Reverse a String is the Most Asked JavaScripit Interview Question in the technical Round. There are many ways to solve problems by using the inbuilt method, brute force method and also Recursive Method and also we can solve by many methods.

Here we are going to solve this problem by using three different methods such as:-

  • inbuilt method
  • Brute force method
  • Recursive method

There are some test cases that helps in to understand the question:-

    • input = "string"
      • output = "gnirts"
    • input = "hello"
      • output = "olleh"
    • input = "hi my name"
      • output = "eman ym ih"



1. Reverse a String using the inbuilt method

=> For this method, we have to use two more inbuilt methods .split() and .join().

  • .split() => The split() method splits a String object into an array of strings by separating the string into substrings.
    • .join() => The join() method join all the elements of array into string.
function reverseString(data) {
  // first we have to split on bases of space
  // and then reverse it by using reverse method
  // and again join on the bases of space
  let result = data.split("").reverse().join("");
  return result;
}

2. Reverse a String by using the Brute force method

=> For this method, we have to run a loop from the last to the first element and then put in a new empty string.

function reverseString(arr) {
  // take a empty string where we put reverse array

  let result = "";

  // run a loop from last to start
  for (let i = arr.length - 1; i >= 0; i--) {
    result += arr[i];
  }
  return result;
}

3. Reverse a String by using the Recursive method

=> For this method, we use two more method .substr() and charAt().

  • substr() => The substr() method begins at a specified position, and returns a specified number of characters.

For Example:-

let str = "hello"
str.substr(1)
// OUTPUT :-
// "ello"
let str = "school"
str.substr(1,3)

// OUTPUT :-
// cho
  • charAt() => The charAt() method returns the character at a specified index (position) in a string.

For Example:-

let str = "hello"
str.charAt(1)

// OUTPUT :-
// e

Solution of Reverse String by Recursive method

function reverse(str) {
// check str is empty or not
  if (str== "") {
    return "";
  } else {
    return reverse(str.substr(1)) + str.charAt(0);
  }
}