easy
0 views
String Reverse
Reverse the characters in a given string and print the result
Understand the Problem
Problem Statement
A string S is passed as input to the program. The program must reverse the string and print the reversed value.
Constraints
- String S contains only printable ASCII characters
- String length can vary from 1 to 1000 characters
- String may contain spaces, special characters, and alphanumeric characters
Examples
Example 1
Input
abcdeOutput
edcbaExplanation
The characters in 'abcde' are reversed to produce 'edcba'
Example 2
Input
abbaOutput
abbaExplanation
The string 'abba' is a palindrome, so when reversed it remains the same
Solution
#include <stdio.h>
#include <string.h>
int main() {
char s[1001];
fgets(s, sizeof(s), stdin);
// Remove newline character if present
int len = strlen(s);
if (s[len-1] == '\n') {
s[len-1] = '\0';
len--;
}
// Print string in reverse
for (int i = len - 1; i >= 0; i--) {
printf("%c", s[i]);
}
return 0;
}Time:O(n) - We iterate through the string once to print characters in reverse order
Space:O(1) - We only use a constant amount of extra space (excluding the input string storage)
Approach:
The C solution reads the input string using fgets() which safely handles input with spaces. We first remove the trailing newline character if present. Then we iterate through the string from the last character to the first character (len-1 down to 0) and print each character using printf(). This produces the reversed string.
Visual Explanation
Loading diagram...