#3884
First Matching Character From Both Ends
EasyTwo PointersStringTwo PointersString Matching
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Using two pointers, we can efficiently check characters from both ends towards the center, reducing unnecessary comparisons.
⚙️
Algorithm
3 steps- 1Step 1: Initialize two pointers, left at 0 and right at n-1.
- 2Step 2: While left < right, check if s[left] == s[right].
- 3Step 3: If they match, return left; if no match found, return -1.
solution.py8 lines
1def first_matching_char(s):
2 left, right = 0, len(s) - 1
3 while left < right:
4 if s[left] == s[right]:
5 return left
6 left += 1
7 right -= 1
8 return -1ℹ
Complexity note: We only traverse the string once, making it linear time complexity.
- 1Using two pointers reduces unnecessary comparisons.
- 2Matching characters can occur at various positions, not just the middle.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.