09 Sept 2026Go / Python / TypeScriptEasy

Remove Outermost Parentheses

Remove the first and last parenthesis from every primitive part of a valid parentheses string.

Track nesting depth, appending an opening parenthesis only after entering a primitive and a closing one only before leaving it.

complexity

O(n) time and O(n) output space.

solution files

  • Go remove-outermost-parentheses/solution.go
  • Python remove-outermost-parentheses/solution.py
  • TypeScript remove-outermost-parentheses/solution.ts

Solution files

Goremove-outermost-parentheses/solution.go
package main

func removeOuterParentheses(s string) string {
	result := make([]byte, 0, len(s))
	depth := 0
	for index := range s {
		if s[index] == '(' {
			if depth > 0 {
				result = append(result, s[index])
			}
			depth++
		} else {
			depth--
			if depth > 0 {
				result = append(result, s[index])
			}
		}
	}
	return string(result)
}
Pythonremove-outermost-parentheses/solution.py
class Solution:
    def removeOuterParentheses(self, s: str) -> str:
        result: list[str] = []; depth = class="syntax-number">0
        for character in s:
            if character == class="syntax-string">"(":
                if depth: result.append(character)
                depth += class="syntax-number">1
            else:
                depth -= class="syntax-number">1
                if depth: result.append(character)
        return class="syntax-string">"".join(result)
TypeScriptremove-outermost-parentheses/solution.ts
function removeOuterParentheses(s: string): string {
  const result: string[] = []; let depth = class="syntax-number">0;
  for (const character of s) { if (character === class="syntax-string">"(") { if (depth > class="syntax-number">0) result.push(character); depth += class="syntax-number">1; } else { depth -= class="syntax-number">1; if (depth > class="syntax-number">0) result.push(character); } }
  return result.join(class="syntax-string">"");
}