Solving Leetcode Interviews in Seconds with AI: Count Substrings Starting and Ending with Given Character
Introduction
In this blog post, we will explore how to solve the LeetCode problem "3084" 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
You are given a string s and a character c. Return the total number of substrings of s that start and end with c. Example 1: Input: s = "abada", c = "a" Output: 6 Explanation: Substrings starting and ending with "a" are: "abada", "abada", "abada", "abada", "abada", "abada". Example 2: Input: s = "zzz", c = "z" Output: 6 Explanation: There are a total of 6 substrings in s and all start and end with "z". Constraints: 1 <= s.length <= 105 s and c consist only of lowercase English letters.
Explanation
Here's the solution to the problem:
- Count Occurrences: Iterate through the string and count the number of times the character
cappears. Calculate Substrings: Use the formula
n * (n + 1) // 2wherenis the count of characterc. This formula calculates the number of substrings that can be formed using these occurrences as start and end points.Runtime Complexity: O(n), where n is the length of the string. Storage Complexity: O(1).
Code
def count_substrings(s: str, c: str) -> int:
"""
Given a string s and a character c. Return the total number of substrings of s that start and end with c.
Example 1:
Input: s = "abada", c = "a"
Output: 6
Explanation: Substrings starting and ending with "a" are: "a", "aba", "abada", "a", "ada", "a".
Example 2:
Input: s = "zzz", c = "z"
Output: 6
Explanation: There are a total of 6 substrings in s and all start and end with "z".
Constraints:
1 <= s.length <= 105
s and c consist only of lowercase English letters.
"""
count = 0
for char in s:
if char == c:
count += 1
return count * (count + 1) // 2