Bird
0
0
DSA Cprogramming

String Reversal Approaches in DSA C

Choose your learning style9 modes available
Mental Model
Reversing a string means flipping its characters so the last becomes first and the first becomes last.
Analogy: Imagine reading a sentence backward, starting from the end and moving to the beginning, like rewinding a tape.
Original: h -> e -> l -> l -> o -> \nReversed: o -> l -> l -> e -> h -> \n↑start ↑end
Dry Run Walkthrough
Input: string: "hello"
Goal: Reverse the string so it reads "olleh"
Step 1: Swap first and last characters: 'h' and 'o'
o -> e -> l -> l -> h
Why: First and last characters must switch places to start reversal
Step 2: Swap second and second-last characters: 'e' and 'l'
o -> l -> l -> e -> h
Why: Continue swapping inward to reverse the string
Step 3: Middle character 'l' remains as is (odd length string)
o -> l -> l -> e -> h
Why: Middle character does not move in odd length strings
Result:
o -> l -> l -> e -> h
Reversed string: "olleh"
Annotated Code
DSA C
#include <stdio.h>
#include <string.h>

void reverseString(char *str) {
    int left = 0;
    int right = strlen(str) - 1;
    while (left < right) {
        // Swap characters at left and right
        char temp = str[left];
        str[left] = str[right];
        str[right] = temp;
        // Move pointers inward
        left++;
        right--;
    }
}

int main() {
    char str[] = "hello";
    reverseString(str);
    printf("%s\n", str);
    return 0;
}
while (left < right) {
loop until pointers meet or cross to cover all swaps
char temp = str[left]; str[left] = str[right]; str[right] = temp;
swap characters at left and right positions
left++; right--;
move pointers inward to next pair
OutputSuccess
olleh
Complexity Analysis
Time: O(n) because each character is visited once during swapping
Space: O(1) because reversal is done in place without extra storage
vs Alternative: Compared to creating a new reversed string (O(n) space), this approach saves memory by swapping in place
Edge Cases
empty string
function returns immediately with no changes
DSA C
while (left < right) {
single character string
no swaps occur, string remains same
DSA C
while (left < right) {
string with all same characters
swapping identical characters keeps string unchanged
DSA C
char temp = str[left];
When to Use This Pattern
When asked to reverse a string or array in place, use two pointers moving inward swapping elements to achieve reversal efficiently.
Common Mistakes
Mistake: Swapping characters without moving pointers inward causes infinite loop
Fix: Increment left and decrement right pointers after each swap
Mistake: Using a new string without freeing memory in languages like C
Fix: Prefer in-place reversal to avoid extra memory management
Summary
Reverses a string by swapping characters from ends moving inward.
Use when you need to reverse strings efficiently without extra space.
The key is two pointers swapping characters until they meet in the middle.