Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Substrings of Size Three with Distinct Characters

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "1876" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

A string is good if there are no repeated characters. Given a string s​​​​​, return the number of good substrings of length three in s​​​​​​. Note that if there are multiple occurrences of the same substring, every occurrence should be counted. A substring is a contiguous sequence of characters in a string. Example 1: Input: s = "xyzzaz" Output: 1 Explanation: There are 4 substrings of size 3: "xyz", "yzz", "zza", and "zaz". The only good substring of length 3 is "xyz". Example 2: Input: s = "aababcabc" Output: 4 Explanation: There are 7 substrings of size 3: "aab", "aba", "bab", "abc", "bca", "cab", and "abc". The good substrings are "abc", "bca", "cab", and "abc". Constraints: 1 <= s.length <= 100 s​​​​​​ consists of lowercase English letters.

Explanation

  • Iterate through the string s using a sliding window of size 3.
    • For each window, check if all the characters within the window are distinct (i.e., the substring is "good").
    • Increment a counter if the substring is good.
  • Time Complexity: O(n), where n is the length of the string s. Space Complexity: O(1).

Code

    def countGoodSubstrings(s: str) -> int:
    """
    Counts the number of good substrings of length three in a string.
    A string is good if there are no repeated characters.

    Args:
        s: The input string.

    Returns:
        The number of good substrings of length three in s.
    """

    count = 0
    for i in range(len(s) - 2):
        substring = s[i:i+3]
        if len(set(substring)) == 3:
            count += 1
    return count

More from this blog

C

Chatmagic blog

2894 posts