[LeetCode] First Matching Character From Both Ends

3884. First Matching Character From Both Ends

You are given a string s of length n consisting of lowercase English letters.

Return the smallest index i such that s[i] == s[n - i - 1].

If no such index exists, return -1.

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int firstMatchingIndex(string s) {
int n = s.length();
for(int i = 0; i < n; i++) {
if(s[i] == s[n-i-1]) return i;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/first-matching-character-from-both-ends/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.