Skip to Content
LeetCode The Hard Way
3800 - 3899

3884 - First Matching Character From Both Ends (Easy)

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 <= 100
  • s consists 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 ii, that opposite index is n−i−1n - i - 1. 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 resres and stop the loop. Initially, resres is −1-1, so if no pair matches, we return −1-1.

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 O(n)O(n) and the space complexity is O(1)O(1).

Written by@wkw
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

On this page