3884 - First Matching Character From Both Ends (Easy)
Problem Link
https://leetcode.com/problems/first-matching-character-from-both-ends
Problem Statement
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.
Example 1:
Input: s = "abcacbd"
Output: 1
Explanation:
At index i = 1, s[1] and s[5] are both 'b'.
No smaller index satisfies the condition, so the answer is 1.
Example 2:
Input: s = "abc"
Output: 1
Explanation:
At index i = 1, the two compared positions coincide, so both characters are 'b'.
No smaller index satisfies the condition, so the answer is 1.
Example 3:
Input: s = "abcdab"
Output: -1
Explanation:
For every index i, the characters at positions i and n - i - 1 are different.
Therefore, no valid index exists, so the answer is -1.
Constraints:
1 <= n == s.length <= 100sconsists of lowercase English letters.
Approach 1: Traversal
We compare each character with the character at the same distance from the other end of the string. For an index , that opposite index is . For example, the first character is compared with the last character.
We check indices from left to right, so the first matching pair gives the smallest valid index. We store that index in and stop the loop. Initially, is , so if no pair matches, we return .
We only need to check the first half of the string because checking the second half would repeat the same pairs in reverse. When the length is odd, we also check the middle character, which always matches itself.
The time complexity is and the space complexity is .
class Solution:
def firstMatchingIndex(self, s: str) -> int:
n = len(s)
res = -1
for i in range((n + 1) // 2):
if s[i] == s[n - i - 1]:
res = i
break
return res