First Matching Character From Both Ends Problem
#3884
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3884.
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.
Solution
Approach: Simulation
Walk i over the first half of the string (including the middle character when the length is odd) and compare s[i] with s[n - i - 1]. Return the first i where they are equal. If none matches, return -1.
Complexity: time O(n), space O(1), where n is the length of s.
class Solution:
def firstMatchingIndex(self, s: str) -> int:
for i in range(len(s) // 2 + 1):
if s[i] == s[-i - 1]:
return i
return -1