Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1541: Minimum Insertions to Balance a Parentheses String

In this guide, we solve Leetcode #1541 Minimum Insertions to Balance a Parentheses String in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if: Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Stack, Greedy, String

Intuition

A locally optimal choice leads to a globally optimal result for this structure.

That means we can commit to decisions as we scan without backtracking.

Approach

Sort or preprocess if needed, then repeatedly take the best available local choice.

Maintain the minimal state necessary to validate the greedy decision.

Steps:

  • Sort or preprocess as needed.
  • Iterate and pick the best local option.
  • Track the current solution.

Example

Input: s = "(()))" Output: 1 Explanation: The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be "(())))" which is balanced.

Python Solution

class Solution: def minInsertions(self, s: str) -> int: ans = x = 0 i, n = 0, len(s) while i < n: if s[i] == '(': # 待匹配的左括号加 1 x += 1 else: if i < n - 1 and s[i + 1] == ')': # 有连续两个右括号,i 往后移动 i += 1 else: # 只有一个右括号,插入一个 ans += 1 if x == 0: # 无待匹配的左括号,插入一个 ans += 1 else: # 待匹配的左括号减 1 x -= 1 i += 1 # 遍历结束,仍有待匹配的左括号,说明右括号不足,插入 x << 1 个 ans += x << 1 return ans

Complexity

The time complexity is O(n log n). The space complexity is O(1) to O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy