Skip to main content
LeetCode 921, Medium. Topics: String, Stack, Greedy. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 15 parametrized pytest cases, and a playground notebook:

Problem

<p>A parentheses string is valid if and only if:</p> <ul> <li>It is the empty string,</li> <li>It can be written as <code>AB</code> (<code>A</code> concatenated with <code>B</code>), where <code>A</code> and <code>B</code> are valid strings, or</li> <li>It can be written as <code>(A)</code>, where <code>A</code> is a valid string.</li> </ul> <p>You are given a parentheses string <code>s</code>. In one move, you can insert a parenthesis at any position of the string.</p> <ul> <li>For example, if <code>s = ”()))”</code>, you can insert an opening parenthesis to be <code>”(()))”</code> or a closing parenthesis to be <code>”())))”</code>.</li> </ul> <p>Return <em>the minimum number of moves required to make </em><code>s</code><em> valid</em>.</p>

Examples

Constraints

  • 1 <= s.length <= 1000
  • s[i] is either ’(’ or ’)’.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026