top of page

Reverse String | Oracle Interview Question



PROBLEM

Write a function to reverse a given string using a stack.

let inputString = "ABCDEFG";
let reversedString = reverseString(string);

console.log(reversedString);

Expected output : GFEDCBA


ALGORITHM


Step 1: Create a stack utility function.

Step 2: Split the input string into an Array of characters.

Step 3: Loop through this array and push all the characters into the stack.

Step 4: Start popping all the items and appending them to a new string;

Step 5: When the stack is empty, the new string obtained is the reversed str


SOLUTION

First things first, since the interviewer is asking us to use a stack to solve this problem, let's implement a simple stack in javascript using closures and then we will use this stack function to solve the actual problem.

JAVASCRIPT CODE


function Stack() {
  let data = [];
  let length = 0;


  return {
    push: (item) => {
      length++;
      return data.push(item);
    },
    pop: () => {
      if (length <= 0) {
        return null;
      } else {
        length--;
        return data.pop();
      }
    },
    peek: () => {
      if (length <= 0) {
        return null;
      } else {
        return data[length - 1];
      }
    },
    isEmpty: () => {
      return !length;
    },
  };
}

Now let's write the code for the function to reverse a given input string utilizing the Stack.


function reverseString(str) {

  let result = "";
  let stack = new Stack();


  let strArr = str.split("");


  strArr.forEach((element) => {
    stack.push(element);
  });


  while (!stack.isEmpty()) {
    result += stack.pop();
  }


  return result;

}


let str = "ABCDEFG";
console.log(reverseString(str));


All the best,

Manoj


120 views0 comments

Recent Posts

See All
bottom of page