3884. First Matching Character From Both Ends
Description
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.
Solutions
Solution 1: Simulation
We iterate over the first half of the string \(s\). For each index \(i\), we check whether the characters at position \(i\) and position \(n - i - 1\) are equal. If they are, we return index \(i\). If no such index is found after the iteration, we return -1.
The time complexity is \(O(n)\), where \(n\) is the length of the string \(s\). The space complexity is \(O(1)\).
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 | |