↓Skip to main content
  1. LeetCode/

LeetCode 3884: First Matching Character From Both Ends

·2 mins· ·
LeetCode Easy Two-Pointers String
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2026-03-29

  • Submissions: Accepted (first try)

Approach
#

Find the smallest i with s[i] == s[n - 1 - i]. Check from i = 0 toward the middle; the first match is the answer.

Checking up to the middle is enough: past the middle, the pair (i, n - 1 - i) was already checked.

Observation: with an odd length, the middle character is compared with itself and always matches, so odd lengths always have an answer; only even lengths can return -1.

My Solution
#

class Solution:
    def firstMatchingIndex(self, s: str) -> int:
        n = len(s)
        for i in range((n + 1) // 2):
            if s[i] == s[n - 1 - i]:
                return i
        return -1

My original looped to n, with the same result (when nothing matches, the second half just rechecks the same pairs); this version stops at the middle.

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Looping only to n // 2: with an odd length, the middle character is missed.

Interview Explanation
#

I check s[i] against s[n - 1 - i] from i = 0 toward the middle and return the first match; the middle is far enough, since later pairs were already seen. With an odd length the middle character always matches itself, so only even lengths can fail. Time O(n).

Related

LeetCode 3823: Reverse Letters Then Special Characters in a String
·2 mins
LeetCode Easy Two-Pointers String
LeetCode 3823 note: two converging-pointer passes, swapping only letters the first time and only special characters the second
LeetCode 2697: Lexicographically Smallest Palindrome
·2 mins
LeetCode Easy Two-Pointers String Greedy
LeetCode 2697 note: converging pointers, setting both ends to the smaller character whenever they differ
LeetCode 3794: Reverse String Prefix
·2 mins
LeetCode Easy Two-Pointers String
LeetCode 3794 note: one line with slicing; a hand-written two-pointer version must convert the string to a list first
LeetCode 3750: Minimum Number of Flips to Reverse Binary String
·2 mins
LeetCode Easy Two-Pointers Bit-Manipulation String
LeetCode 3750 note: compare the binary string with its reverse bit by bit; the number of mismatches is the answer
LeetCode 2000: Reverse Prefix of Word
·1 min
LeetCode Easy Two-Pointers String Stack
LeetCode 2000 note: find the first index i of ch, reverse word[:i + 1] and append the rest; return the word unchanged if ch is absent
LeetCode 942: DI String Match
·1 min
LeetCode Easy Array Two-Pointers String Greedy
LeetCode 942 note: two pointers hold the smallest and largest unused values; place the smallest on I and the largest on D