Solving Leetcode Interviews in Seconds with AI: Minimum Additions to Make Valid String
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2645" 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 word to which you can insert letters "a", "b" or "c" anywhere and any number of times, return the minimum number of letters that must be inserted so that word becomes valid. A string is called valid if it can be formed by concatenating the string "abc" several times. Example 1: Input: word = "b" Output: 2 Explanation: Insert the letter "a" right before "b", and the letter "c" right next to "b" to obtain the valid string "abc". Example 2: Input: word = "aaa" Output: 6 Explanation: Insert letters "b" and "c" next to each "a" to obtain the valid string "abcabcabc". Example 3: Input: word = "abc" Output: 0 Explanation: word is already valid. No modifications are needed. Constraints: 1 <= word.length <= 50 word consists of letters "a", "b" and "c" only.
Explanation
Here's the breakdown of the solution:
Dynamic Programming: The core idea is to use dynamic programming to solve this problem. We'll create a DP table where
dp[i][j]represents the minimum number of insertions needed to make the substringword[:i]valid up to thej-th character of "abc".State Transitions: We'll iterate through the
wordand consider the possible transitions. If the current character inwordmatches the expected character in "abc", we can move to the next state without any insertion. Otherwise, we need to insert characters to reach the desired state.Base Case and Result: The base case is
dp[0][0] = 0. The final result will be stored indp[n][0]where n is the length of theword. We needdp[n][0]because a valid string must be constructed by concatenating "abc" any number of times.Runtime & Storage Complexity: O(n), O(n) where n is the length of word.
Code
def add_to_make_valid(word):
n = len(word)
dp = [[float('inf')] * 3 for _ in range(n + 1)]
dp[0][0] = 0
for i in range(1, n + 1):
for j in range(3):
if word[i - 1] == "abc"[j]:
dp[i][j] = dp[i - 1][(j - 1) % 3] if j != 0 else dp[i-1][2]
else:
dp[i][j] = min(dp[i-1][(j-1) % 3] if j != 0 else dp[i-1][2] ,dp[i-1][j] + 1)
#Optimization for cases where we can make string empty at any point to start again
dp[i][0] = min(dp[i][0],dp[i-1][0]+2,dp[i-1][1]+1,dp[i-1][2])
return dp[n][0]