Solving Leetcode Interviews in Seconds with AI: Count Substrings With K-Frequency Characters I
Introduction
In this blog post, we will explore how to solve the LeetCode problem "3325" 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
Given a string s and an integer k, return the total number of substrings of s where at least one character appears at least k times. Example 1: Input: s = "abacb", k = 2 Output: 4 Explanation: The valid substrings are: "aba" (character 'a' appears 2 times). "abac" (character 'a' appears 2 times). "abacb" (character 'a' appears 2 times). "bacb" (character 'b' appears 2 times). Example 2: Input: s = "abcde", k = 1 Output: 15 Explanation: All substrings are valid because every character appears at least once. Constraints: 1 <= s.length <= 3000 1 <= k <= s.length s consists only of lowercase English letters.
Explanation
Here's an efficient solution to the problem, along with explanations and code.
- Iterate through all possible substrings: The core idea is to generate all possible substrings of the input string
s. - Check frequency condition: For each substring, we count the frequency of each character and check if at least one character's frequency is greater than or equal to
k. Count valid substrings: If the frequency condition is met, we increment a counter.
Runtime Complexity: O(n^2), where n is the length of the string
s.- Storage Complexity: O(1), excluding the input string. The character counts use a fixed amount of space (26 integers).
Code
def count_substrings(s: str, k: int) -> int:
"""
Given a string s and an integer k, return the total number of substrings of s
where at least one character appears at least k times.
Example 1:
Input: s = "abacb", k = 2
Output: 4
Explanation: The valid substrings are:
"aba" (character 'a' appears 2 times).
"abac" (character 'a' appears 2 times).
"abacb" (character 'a' appears 2 times).
"bacb" (character 'b' appears 2 times).
Example 2:
Input: s = "abcde", k = 1
Output: 15
Explanation: All substrings are valid because every character appears at least once.
Constraints:
1 <= s.length <= 3000
1 <= k <= s.length
s consists only of lowercase English letters.
"""
n = len(s)
count = 0
for i in range(n):
for j in range(i, n):
substring = s[i:j+1]
char_counts = {}
for char in substring:
char_counts[char] = char_counts.get(char, 0) + 1
valid = False
for char in char_counts:
if char_counts[char] >= k:
valid = True
break
if valid:
count += 1
return count