Reverse and Print Common Characters in Two Strings Using Python
Find common characters between two strings at the same index positions after reversing the second string
Understand the Problem
Problem Statement
Given two strings, S1 and S2, reverse S2 and find the characters that are common between S1 and the reversed S2 at the same index positions. Both strings will contain only lowercase letters.
Constraints
- The length of
S1should be between 2 and 500. - The length of
S2should also be between 2 and 500. - Both strings contain only lowercase letters (a-z).
- Comparison is case-sensitive.
Examples
energy
genuineenAfter reversing 'genuine' to 'eniuneg', comparing with 'energy' shows matches at index 0 ('e') and index 1 ('n'), resulting in 'en'.
growth
thrownoAfter reversing 'thrown' to 'nworht', comparing with 'growth' shows only one match at index 2 ('o'), resulting in 'o'.
abc
xyzAfter reversing 'xyz' to 'zyx', comparing with 'abc' shows no matches at any index position, resulting in an empty string.
Solution
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char s1[501], s2[501];
char result[501];
int i, j, len1, len2, result_len = 0;
// Read input strings
fgets(s1, sizeof(s1), stdin);
fgets(s2, sizeof(s2), stdin);
// Remove newlines
s1[strcspn(s1, "\n")] = 0;
s2[strcspn(s2, "\n")] = 0;
len1 = strlen(s1);
len2 = strlen(s2);
// Compare characters from end of s2 to beginning of s1
for (i = 0; i < len1 && i < len2; i++) {
if (s1[i] == s2[len2 - 1 - i]) {
result[result_len++] = s1[i];
}
}
result[result_len] = '\0';
printf("%s\n", result);
return 0;
}The C solution reads both strings using fgets() to handle spaces. It removes newlines, then iterates through both strings up to the length of the shorter one. For each position i, it compares s1[i] with s2[len2-1-i] (which effectively reverses s2 during comparison). Matching characters are stored in the result array, which is null-terminated and printed at the end.