Solving Leetcode Interviews in Seconds with AI: Number of Substrings With Only 1s
Introduction
In this blog post, we will explore how to solve the LeetCode problem "1513" 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 binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 7. Example 1: Input: s = "0110111" Output: 9 Explanation: There are 9 substring in total with only 1's characters. "1" -> 5 times. "11" -> 3 times. "111" -> 1 time. Example 2: Input: s = "101" Output: 2 Explanation: Substring "1" is shown 2 times in s. Example 3: Input: s = "111111" Output: 21 Explanation: Each substring contains only 1's characters. Constraints: 1 <= s.length <= 105 s[i] is either '0' or '1'.
Explanation
Here's an efficient solution to count substrings with all 1's in a binary string:
- Count Consecutive 1s: Iterate through the string, keeping track of the length of consecutive sequences of '1's.
- Calculate Substrings: For each sequence of '1's of length n, the number of substrings with all 1's is n( n + 1) / 2.
Modulo Arithmetic: Apply the modulo operator to prevent integer overflow.
Runtime Complexity: O(n), where n is the length of the string. Storage Complexity: O(1).
Code
def numSub(s: str) -> int:
"""
Given a binary string s, return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 109 + 7.
"""
MOD = 10**9 + 7
count = 0
result = 0
for char in s:
if char == '1':
count += 1
else:
result = (result + (count * (count + 1) // 2)) % MOD
count = 0
result = (result + (count * (count + 1) // 2)) % MOD
return result