Member-only story
Exploring Recursion and Two-Pointers Through ReverseString
DSA, Algorithms, Problem-solving techniques
In my previous blog, I talked about revising my knowledge of Data Structures & Algorithms. While exploring concepts like pointers and recursions, I found that reversing strings was surprisingly helpful in making these ideas easier to understand.
Strings are just sequences of characters. In JavaScript, which is my main coding language, strings can be worked with easily. For instance, let’s say we want to reverse the word ‘hello’ to get ‘olleh’. We can simply use a simple loop to go through the characters in reverse order:
function reverseString(str){
let reversedStr = "";
for(let i = str.length - 1; i >= 0; i--){
reversedStr += reversedStr;
}
return reversedStr;
}
// Test cases
// assuming s = ["hello"]
// 1) i = 5-1= 4, reversed = '' + str[0] = 'o'
// 2) i = 3, reversed = 'o' + str[3] = 'ol'
// 3) i = 2, reversed = 'ol' + str[2] = 'oll'
// 4) i = 1, reversed = 'oll' + str[1] = 'olle'
// 5) i = 0, reversed = 'olle' + str[0] = 'olleh'
// we return 'olleh'
Have you ever considered using two-pointers to reverse a string?
function reverseString(str){
let left = 0;
let right = str.length - 1;
while(left < right){
let temp = str[left];
// Perform swapping
str[left] =…