![]() |
VOOZH | about |
Given a string s consisting of lowercase characters, the task is to find the count of all substrings that start and end with the same character.
Examples :
Input : s = "abcab"
Output : 7
Explanation: The substrings are "a", "abca", "b", "bcab", "c", "a", "b".
Input : s = "aba"
Output : 4
Explanation: The substrings are "a", "aba", "b", and "a".
The idea is to check each possible substring in the string and count those that have the same first and last character.
7
The idea is to use the fact that for each character in the alphabet, we can directly calculate how many substrings would start and end with that character without actually generating all possible substrings. By counting the frequency of each character in the string, we can use the combination formula to determine how many ways we can select two occurrences of the same character to form the start and end of substrings, plus the substrings of length 1.
Step by step approach:
7
Related Articles: