Count Number of Homogenous Substrings

Last Updated: 09-Nov-2023 17:52:13
234 Views
Summarize

Git is a distributed version control system DVCS designed for efficient source code management, suitable for both small and large projects. It allows multiple developers to work on a project simultaneously without overwriting changes, supporting collaborative work, continuous integration, and deployment. This Git and GitHub tutorial is designed for beginners to learn fundamentals and advanced concepts, including branching, pushing, merging conflicts, and essential Git commands. Prerequisites include familiarity with the command line interface CLI, a text editor, and basic programming concepts. Git was developed by Linus Torvalds for Linux kernel development and tracks changes, manages versions, and enables collaboration among developers. It provides a complete backup of project history in a repository. GitHub is a hosting service for Git repositories, facilitating project access, collaboration, and version control. The tutorial covers topics such as Git installation, repository creation, Git Bash usage, managing branches, resolving conflicts, and working with platforms like Bitbucket and GitHub. The text is a comprehensive guide to using Git and GitHub, covering a wide range of topics. It includes instructions on working directories, using submodules, writing good commit messages, deleting local repositories, and understanding Git workflows like Git Flow versus GitHub Flow. There are sections on packfiles, garbage collection, and the differences between concepts like HEAD, working tree, and index. Installation instructions for Git across various platforms Ubuntu, macOS, Windows, Raspberry Pi, Termux, etc. are provided, along with credential setup. The guide explains essential Git commands, their usage, and advanced topics like debugging, merging, rebasing, patch operations, hooks, subtree, filtering commit history, and handling merge conflicts. It also covers managing branches, syncing forks, searching errors, and differences between various Git operations e.g., push origin vs. push origin master, merging vs. rebasing. The text provides a comprehensive guide on using Git and GitHub. It covers creating repositories, adding code of conduct, forking and cloning projects, and adding various media files to a repository. The text explains how to push projects, handle authentication issues, solve common Git problems, and manage repositories. It discusses using different IDEs like VSCode, Android Studio, and PyCharm, for Git operations, including creating branches and pull requests. Additionally, it details deploying applications to platforms like Heroku and Firebase, publishing static websites on GitHub Pages, and collaborating on GitHub. Other topics include the use of Git with R and Eclipse, configuring OAuth apps, generating personal access tokens, and setting up GitLab repositories. The text covers various topics related to Git, GitHub, and other version control systems Key Pointers Git is a distributed version control system DVCS for source code management. Supports collaboration, continuous integration, and deployment. Suitable for both small and large projects. Developed by Linus Torvalds for Linux kernel development. Tracks changes, manages versions, and provides complete project history. GitHub is a hosting service for Git repositories. Tutorial covers Git and GitHub fundamentals and advanced concepts. Includes instructions on installation, repository creation, and Git Bash usage. Explains managing branches, resolving conflicts, and using platforms like Bitbucket and GitHub. Covers working directories, submodules, commit messages, and Git workflows. Details packfiles, garbage collection, and Git concepts HEAD, working tree, index. Provides Git installation instructions for various platforms. Explains essential Git commands and advanced topics debugging, merging, rebasing. Covers branch management, syncing forks, and differences between Git operations. Discusses using different IDEs for Git operations and deploying applications. Details using Git with R, Eclipse, and setting up GitLab repositories. Explains CI/CD processes and using GitHub Actions. Covers internal workings of Git and its decentralized model. Highlights differences between Git version control system and GitHub hosting platform.

2 trials left

 

Introduction:

Given a string s, the goal is to determine the number of homogenous substrings it contains. A string is considered homogenous if all its characters are the same. Substrings, on the other hand, are contiguous sequences of characters within a string. To handle potentially large results, the answer is returned modulo 10^9 + 7.

Problem Statement:

We are given a string s, and we need to count the number of homogenous substrings in it.

Example 1:

Input: "abbcccaa"
Output: 13

Explanation: The homogenous substrings are: "a" (appears 3 times), "aa" (appears 1 time), "b" (appears 2 times), "bb" (appears 1 time), "c" (appears 3 times), "cc" (appears 2 times), "ccc" (appears 1 time). The total count is 3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.

Example 2:

Input: "xy"
Output: 2

Explanation: The homogenous substrings are "x" and "y."

Example 3:

Input: "zzzzz"
Output: 15

Explanation: The string consists of five consecutive "z" characters. There are 15 substrings consisting of a single "z" character.

Constraints:

- 1 <= s.length <= 105
- s consists of lowercase letters.

Approach:

To count the number of homogenous substrings in the given string efficiently, we can use a simple loop. We iterate through the string, maintaining a count of consecutive characters that are the same. When we encounter a different character, we calculate the number of homogenous substrings that can be formed using the previous character and add it to the total count.

Pseudocode:

  1. Initialize count = 0 and length = 1.
  2.  Iterate through the string s from the second character (index 1) to the last character (index n-1).
  3. If the current character is the same as the previous character, increment length.
  4.  If the current character is different, calculate the number of homogenous substrings using the previous character: (length * (length + 1)) / 2, and add it to count.
  5. After the loop, add the count of homogenous substrings for the last character.
  6. Return count modulo 10^9 + 7.

Code :

#include <stdio.h>

int countHomogenous(char *s) {
    int mod = 1000000007;
    long count = 0;
    int length = 1;

    for (int i = 1; s[i] != '\0'; i++) {
        if (s[i] == s[i - 1]) {
            length++;
        } else {
            // Add the count of homogenous substrings of the previous character to the total count.
            count = (count + (long) length * (length + 1) / 2) % mod;
            length = 1;
        }
    }

    // Add the count of homogenous substrings for the last character.
    count = (count + (long) length * (length + 1) / 2) % mod;

    return (int) count;
}

int main() {
    char s[] = "abbcccaa";
    int result = countHomogenous(s);
    printf("Output: %d\n", result);

    return 0;
}

Output

Output: 13
#include <iostream>
#include <string>

using namespace std;

int countHomogenous(string s) {
    int mod = 1000000007;
    long long count = 0;
    int length = 1;

    for (int i = 1; i < s.length(); i++) {
        if (s[i] == s[i - 1]) {
            length++;
        } else {
            // Add the count of homogenous substrings of the previous character to the total count.
            count = (count + (long long)length * (length + 1) / 2) % mod;
            length = 1;
        }
    }

    // Add the count of homogenous substrings for the last character.
    count = (count + (long long)length * (length + 1) / 2) % mod;

    return static_cast<int>(count);
}

int main() {
    string s = "abbcccaa";
    int result = countHomogenous(s);
    cout << "Output: " << result << endl;

    return 0;
}

Output

Output: 13
public class Solution {
    public static int countHomogenous(String s) {
        int mod = 1000000007;
        long count = 0;
        int length = 1;

        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) == s.charAt(i - 1)) {
                length++;
            } else {
                // Add the count of homogenous substrings of the previous character to the total count.
                count = (count + (long) length * (length + 1) / 2) % mod;
                length = 1;
            }
        }

        // Add the count of homogenous substrings for the last character.
        count = (count + (long) length * (length + 1) / 2) % mod;

        return (int) count;
    }

    public static void main(String[] args) {
        String s = "abbcccaa";
        int result = countHomogenous(s);
        System.out.println("Output: " + result);
    }
}

Output

Output: 13
def count_homogenous(s):
    mod = 1000000007
    count = 0
    length = 1

    for i in range(1, len(s)):
        if s[i] == s[i - 1]:
            length += 1
        else:
            # Add the count of homogenous substrings of the previous character to the total count.
            count = (count + length * (length + 1) // 2) % mod
            length = 1

    # Add the count of homogenous substrings for the last character.
    count = (count + length * (length + 1) // 2) % mod

    return int(count)

# Example usage
s = "abbcccaa"
result = count_homogenous(s)
print("Output:", result)

Output

Output: 13
<?php
function countHomogenous($s) {
    $mod = 1000000007;
    $count = 0;
    $length = 1;

    for ($i = 1; $i < strlen($s); $i++) {
        if ($s[$i] == $s[$i - 1]) {
            $length++;
        } else {
            // Add the count of homogenous substrings of the previous character to the total count.
            $count = ($count + $length * ($length + 1) / 2) % $mod;
            $length = 1;
        }
    }

    // Add the count of homogenous substrings for the last character.
    $count = ($count + $length * ($length + 1) / 2) % $mod;

    return (int)$count;
}

// Example usage
$s = "abbcccaa";
$result = countHomogenous($s);
echo "Output: " . $result . "\n";
?>

Output

Output: 13

Time Complexity:

The time complexity of this solution is O(n), where n is the length of the input string s. We iterate through the string once, and the operations within the loop are constant time.

Space Complexity:

The space complexity of this solution is O(1) as we only use a constant amount of extra space for variables.

Conclusion:

Counting homogenous substrings in a string is a common problem that can be efficiently solved with a simple algorithm. This solution works well for strings of varying lengths and provides results modulo 10^9 + 7 to handle potentially large counts.

You may also like this!