Day 2: Reverse a String in JavaScript – 3 Methods for Coding Interviews

๐Ÿš€ Day 2 – Reverse a String in JavaScript (Google/Amazon Favorite!)

Hello coders! ๐Ÿ‘‹
Welcome back to Code With Jaffer – Day 2 of our JavaScript + DSA Interview Prep Series.

Today’s challenge is simple, but often asked in interviews at Google, Amazon, and TCS:

Reverse a string using different techniques.

Let’s solve it in 3 different ways, with clear code and explanation! ๐Ÿ‘‡


๐Ÿง  Problem Statement:

Q: Reverse a given string.

Input: "hello"
Output: "olleh"


๐Ÿ”น Method 1: Using JavaScript Built-in Functions

javascript
function reverseStringBuiltIn(str) {
return str.split('').reverse().join('');
}
console.log(reverseStringBuiltIn("hello")); // Output: olleh

✅ Explanation:

  • split('') converts the string to an array → ['h','e','l','l','o']

  • reverse() reverses the array

  • join('') joins it back into a string

๐Ÿง  Best for: Quick and clean solution.
Time Complexity: O(n)


๐Ÿ”น Method 2: Using a For Loop

javascript
function reverseStringLoop(str) {
let reversed = '';
for (let i = str.length - 1; i >= 0; i--) {
reversed += str[i];
}
return reversed;
}
console.log(reverseStringLoop("hello")); // Output: olleh

✅ Explanation:

  • Loop runs from end to start.

  • Adds each character to the result string one by one.

๐Ÿง  Best for: Understanding logic flow manually.
Time Complexity: O(n)


๐Ÿ”น Method 3: Using Recursion

javascript
function reverseStringRecursion(str) {
if (str === "") return "";
return reverseStringRecursion(str.slice(1)) + str[0];
}
console.log(reverseStringRecursion("hello")); // Output: olleh

✅ Explanation:

  • Base case: empty string

  • Recursive case: reverse rest of the string + first character

๐Ÿง  Best for: Practicing recursion technique.
Time Complexity: O(n²) due to string slicing and concatenation


๐ŸŽฏ Interview Tip:

  • Explain each method clearly.

  • Show you can think in multiple ways.

  • Mention trade-offs in time/space complexity.


Comments

Popular posts from this blog

Day 4 – Palindrome Number in JavaScript Without Converting to String

Day 9 – Count Vowels in a String using JavaScript | DSA Challenge with Code & Explanation

Day 13: Find Missing Number in an Array – JavaScript DSA Challenge