Data Structures and Algorithms (DSA)  

πŸ”„ Reverse a String Without Using Extra Space

πŸ“Œ Introduction

Reversing a string is one of the most common Data Structures and Algorithms (DSA) problems asked in coding interviews. While it sounds simple, the challenge here is to reverse the string without using extra space β€” meaning we should not create another string or array to store the reversed version.

This tests your understanding of in-place algorithms, memory usage, and pointer manipulation (especially in C or C++).

🧠 Problem Statement

Given a string, write a program to reverse it in-place (without using extra space).

Example

  • Input: "hello"

  • Output: "olleh"

πŸ“ Approach (Step-by-Step)

We can solve this using the two-pointer technique:

  1. Place one pointer at the beginning of the string (left).

  2. Place another pointer at the end of the string (right).

  3. Swap the characters at left and right.

  4. Move left forward and right backward.

  5. Repeat until left < right.

This way, the string is reversed without using extra space.

βš™οΈ Algorithm

  1. Initialize two variables: left = 0 and right = length - 1.

  2. While left < right:

    • Swap string[left] and string[right].

    • Increment left, decrement right.

  3. Stop when left >= right.

πŸ’» Implementation in C

#include <stdio.h>#include <string.h>

void reverseString(char str[]) {
    int left = 0;
    int right = strlen(str) - 1;
    char temp;

    while (left < right) {
        // Swap characters
        temp = str[left];
        str[left] = str[right];
        str[right] = temp;

        // Move pointers
        left++;
        right--;
    }
}

int main() {
    char str[] = "hello";
    printf("Original String: %s\n", str);
    reverseString(str);
    printf("Reversed String: %s\n", str);
    return 0;
}

πŸ” Dry Run Example

For str = "hello":

StepLeftRightString State
104oellh
213olleh
322Stop

Final result = "olleh" βœ…

⏱️ Time & Space Complexity

  • Time Complexity: O(n), since each character is swapped at most once.

  • Space Complexity: O(1), since we did not use any extra string or array.

🎯 Key Takeaways

  • The two-pointer technique is one of the most efficient ways to reverse a string.

  • This approach is in-place, which means it doesn’t use additional memory.

  • Commonly asked in coding interviews to test your problem-solving skills.

🏁 Conclusion

Reversing a string without extra space is a classic DSA problem that teaches us about pointer manipulation, memory optimization, and in-place algorithms. By mastering this, you also strengthen your foundation for more advanced string problems like palindrome checks, string rotation, and substring matching.