easyStringsPattern: Pointer Manipulation

Matching Extremes Solution

Problem Statement

You are given a string s of even length. Using two pointers starting from the opposite ends of the string and moving towards the center, calculate the number of matching character pairs at symmetric positions.

Examples

Example 1:
Input:s = "abccba"
Output:3
Explanation: Comparing characters from the outside in: s[0] ('a') matches s[5] ('a'), s[1] ('b') matches s[4] ('b'), and s[2] ('c') matches s[3] ('c'). All 3 symmetric pairs match.
Example 2:
Input:s = "axbyca"
Output:1
Explanation: Comparing symmetric characters: s[0] ('a') matches s[5] ('a'). s[1] ('x') does not match s[4] ('c'). s[2] ('b') does not match s[3] ('y'). Only 1 pair matches.

Constraints

  • 2 <= s.length <= 10^5
  • s.length % 2 == 0
  • s consists only of lowercase English letters.
Time: O(N) Space: O(1)
Using the two-pointer technique, we can initialize one pointer at the start and one at the end of the string. We compare the characters at these pointers, count the matches, and move both pointers toward the center. This solves the problem in a single pass with O(1) auxiliary space.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.