📌 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

📝 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

🎯 Key Takeaways

🏁 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.