Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Minimum Add to Make Parentheses Valid

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "921" 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

A parentheses string is valid if and only if: It is the empty string, It can be written as AB (A concatenated with B), where A and B are valid strings, or It can be written as (A), where A is a valid string. You are given a parentheses string s. In one move, you can insert a parenthesis at any position of the string. For example, if s = "()))", you can insert an opening parenthesis to be "(()))" or a closing parenthesis to be "())))". Return the minimum number of moves required to make s valid. Example 1: Input: s = "())" Output: 1 Example 2: Input: s = "(((" Output: 3 Constraints: 1 <= s.length <= 1000 s[i] is either '(' or ')'.

Explanation

Here's the breakdown of the solution:

  • Balance Tracking: The core idea is to iterate through the string and keep track of the balance between open and close parentheses. An open parenthesis increases the balance, and a close parenthesis decreases it.
  • Imbalance Correction: If the balance becomes negative, it means we have more closing parentheses than opening parentheses encountered so far. To correct this, we need to insert an opening parenthesis, incrementing the moves and resetting the balance to zero.
  • Final Adjustment: After processing the entire string, if the balance is positive, it indicates an excess of opening parentheses. We need to insert closing parentheses to balance them, incrementing the moves accordingly.

  • Time & Space Complexity: O(n) time complexity, O(1) space complexity, where n is the length of the input string.

Code

    def minAddToMakeValid(s: str) -> int:
    """
    Calculates the minimum number of moves required to make a parentheses string valid.

    Args:
        s: The input parentheses string.

    Returns:
        The minimum number of moves required to make the string valid.
    """

    balance = 0
    moves = 0

    for char in s:
        if char == '(':
            balance += 1
        elif char == ')':
            balance -= 1

        if balance < 0:
            moves += 1
            balance = 0

    moves += balance  # Add the remaining open parentheses

    return moves

More from this blog

C

Chatmagic blog

2894 posts