Solving Leetcode Interviews in Seconds with AI: Repeated String Match
Introduction
In this blog post, we will explore how to solve the LeetCode problem "686" 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 two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b to be a substring of a after repeating it, return -1. Notice: string "abc" repeated 0 times is "", repeated 1 time is "abc" and repeated 2 times is "abcabc". Example 1: Input: a = "abcd", b = "cdabcdab" Output: 3 Explanation: We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it. Example 2: Input: a = "a", b = "aa" Output: 2 Constraints: 1 <= a.length, b.length <= 104 a and b consist of lowercase English letters.
Explanation
Here's the breakdown of the solution:
- Determine the minimum repetitions: Start by repeating string
aa sufficient number of times to ensure the repeated string's length is at least the length ofb. - Substring Check: Check if
bis a substring of the repeateda. If found, return the number of repetitions. One More Repetition Check: If
bis not found, repeataone more time and check again. This handles cases wherebspans across the boundary of the initial repetitions. If still not found return -1.Runtime Complexity: O(M * N) where M is the number of repetitions and N is the length of string
b.- Space Complexity: O(M * K) where M is the number of repetitions and K is the length of string
a.
Code
def repeatedStringMatch(a: str, b: str) -> int:
"""
Given two strings a and b, return the minimum number of times you should repeat string a
so that string b is a substring of it. If it is impossible for b to be a substring of a after
repeating it, return -1.
"""
n = len(a)
m = len(b)
repetitions = (m + n - 1) // n # Minimum repetitions needed
repeated_a = a * repetitions
if b in repeated_a:
return repetitions
repeated_a += a
if b in repeated_a:
return repetitions + 1
return -1