707939. Count the Substrings

Easy

Count the Substrings

Summary

Given a string, count the number of substrings that appear in it. A substring is a contiguous sequence of characters within the original string.

This problem involves working with strings and manipulating them to find specific patterns or sequences. The key concept involved here is substring extraction.

Detailed Explanation

The approach to solving this problem is to iterate through the input string, considering each character as the starting point for a potential substring. For each character, we calculate the number of substrings that start at that position and extend in both directions (left and right) until they reach the end of the string or encounter a non-alphabetic character.

Here's a step-by-step breakdown of the solution:

  1. Initialize a variable substrings to store the count of substrings.
  2. Iterate through each character in the input string, considering it as the starting point for a potential substring.
  3. For each character, initialize two pointers: left and right, both pointing at the current character.
  4. Move the left pointer to the left until you encounter a non-alphabetic character or reach the start of the string. This will give you the length of the longest substring that starts at the current position and extends to the left.
  5. Move the right pointer to the right until you encounter a non-alphabetic character or reach the end of the string. This will give you the length of the longest substring that starts at the current position and extends to the right.
  6. Add the product of the lengths calculated in steps 4 and 5 to the substrings count, since this represents the number of substrings that start at the current position.
  7. Repeat steps 2-6 for each character in the input string.

Time complexity: O(n), where n is the length of the input string. We only need to iterate through the string once, and each operation (moving pointers or updating counts) takes constant time.

Space complexity: O(1), since we only use a few variables to store intermediate results.

Optimized Solutions

Java

View on GeeksforGeeks
public class SubstringCounter {
    public static int countSubstrings(String s) {
        int substrings = 0;
        for (int i = 0; i < s.length(); i++) {
            int left = i, right = i;
            while (left > 0 && Character.isLetter(s.charAt(left - 1))) {
                left--;
            }
            while (right < s.length() - 1 && Character.isLetter(s.charAt(right + 1))) {
                right++;
            }
            substrings += (right - left + 1);
        }
        return substrings;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.