Ctrl K

Pieces With Matching Ends

Medium
You are given a string word of lowercase English letters. Count the contiguous non-empty pieces of it whose first and last letters are the same. Pieces are told apart by position: two pieces with the same text at different places are counted twice. A single letter counts as a piece too.
Example 1
word="radar" → 7

Five one-letter pieces, plus "ada" (ends a…a) and the whole "radar" (ends r…r). That makes 7.

Example 2
word="bbb" → 6

Every piece works: three of length one, two of length two, one of length three, so 6.

Example 3
word="xyz" → 3
Constraints
  • 1 ≤ len(word) ≤ 10⁵
  • word contains only lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSeparate Two Words by Letters MediumPieces With a Fixed Zero-to-One Ratio MediumEven Vowel and Consonant Pieces MediumPieces with a Whole Average Weight MediumMatching Ends per Range Medium
loading Python…
Input
word="radar"
Expected
7

Run checks the first 3 tests in your browser. Submit checks all 81 tests on the server, hidden ones included.