Intuition
Index i and index n - i - 1 are mirror positions around the center of the string. As i grows from 0, its mirror shrinks from the end, so the two positions meet in the middle. Walk a left pointer in from index 0 and a right pointer in from the end at the same speed; the first pair that holds equal characters sits at the smallest qualifying index.
Explanation
Idea
The condition s[i] == s[n - i - 1] compares position i with its mirror across the center of the string. Because i and n - i - 1 are symmetric, testing index i is exactly the same comparison as testing index n - i - 1 — so any matching index in the second half mirrors one in the first half that we would reach earlier. That means the smallest answer always lives in the first half, and we can find it by sweeping two pointers inward from both ends.
Algorithm
- Put a left pointer
iat index0and a right pointerjat indexn - 1. At every stepjequalsn - i - 1, sos[i]ands[j]are exactly the mirrored pair we care about. - While
i <= j:- If
s[i] == s[j], theniis the smallest index whose character matches its mirror — returni. - Otherwise step both pointers inward:
i += 1,j -= 1.
- If
- If the pointers cross without a match, no index satisfies the condition — return
-1.
Scanning from the outside in means i is tested in increasing order (0, 1, 2, ...), so the first match we hit is guaranteed to be the smallest index.
Worked example: "abcacbd" (n = 7)
i = 0,j = 6:s[0] = 'a'vss[6] = 'd'— different, move inward.i = 1,j = 5:s[1] = 'b'vss[5] = 'b'— equal. Return1.
No index smaller than 1 matched, so 1 is the answer.
Why -1 happens: "abcdab" (n = 6)
i = 0,j = 5:'a'vs'b'— differ.i = 1,j = 4:'b'vs'a'— differ.i = 2,j = 3:'c'vs'd'— differ.- Now
i = 3,j = 2, soi > jand the loop ends with no match — return-1.
Complexity
- Time: O(n). Each pointer advances at most n/2 steps and does O(1) work per step.
- Space: O(1). Only two integer indices are kept; the string is never copied.
Implementation
class Solution {
public int firstMatchingIndex(String s) {
int i = 0, j = s.length() - 1;
while (i <= j) {
if (s.charAt(i) == s.charAt(j)) return i;
i++;
j--;
}
return -1;
}
}