Day 2/30: Reverse String In Place |
#30DayDSAChallenge
Today’s focus is on strings and in place operations, and this one teaches an important mindset shift. 👀
📌 The Problem:
Given a string, reverse it in place.
Example:
Input: "hello"
Output: "olleh"
❌ The Naive Approach:
Create a new string or array and reverse it.
This works, but it uses extra space.
Can we do it without extra memory?
✅ The Optimal Solution: Two Pointer Technique
The idea is simple but powerful.
Instead of creating a new string, we use two pointers:
• One starting at the beginning
• One starting at the end
At each step:
• Swap the characters
• Move both pointers toward the center
This continues until the pointers meet.
💻 JavaScript Implementation:
function reverseString(s){
let left = 0;
let right = s.length - 1; // Move pointers toward center
while (left < right){ // Swap characters
[s[left], s[right]] = [s[right], s[left]]; // Move pointers
left ;
right --;
}
return s;
⏱️ Complexity:
Time: O(n)
Space: O(1)
🎯 Why This Matters:
This problem introduces the two pointer pattern, which appears everywhere:
• String manipulation
• Array problems
• Palindrome checks
• Sliding window techniques
It also reinforces an important principle:
Not every problem needs extra space.
Sometimes, pointer movement is enough.
Key Takeaway:
Simple problems teach powerful patterns.
Mastering these basics makes harder problems feel lighter.
Day 2 done ✅
28 more days to go.