Skip to the content

Starts and ends the same

Problem

A chunk of a text is letters in a row, with none skipped. Out of "sun" come six chunks: "s", "u", "n", "su", "un" and "sun".

Write a function that takes a text and returns how many of its chunks start and end with the same letter.

A single letter counts, because it starts and ends with itself. That is why "abc" gives 3 and not 0, and "ab" gives 2.

Count them in "abcda": there are the five single letters, "a", "b", "c", "d" and "a", and there is the whole "abcda", which opens and closes with "a". That makes six.

Two chunks that start in different places are two chunks, even if they read the same: in "aaa" there are six. With an empty text the answer is 0.

A straight road: for every starting position, check every ending position from there on.

Examples

  • No letter repeats

    "abc" → 3

  • The one from the example

    "abcda" → 6

  • Two letters

    "ab" → 2

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def count_same_ends(text):
    pass

JavaScript

function countSameEnds(text) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n²) challenges

See all challenges →