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
✅ 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
✅ 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
✅ 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
Post a Comment