Valid Parenthesis

Easy

10 min read

March 10, 2025

Problem Statement

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

Understanding the Problem

The goal is to check if a string made up of {}, [], and () is valid—meaning every opening bracket has a matching closing bracket in the correct order. For example:

Valid: "()[]{}", "{[()]}"

Invalid: "(]", "([)]"

Solution Approach

Instead of using a stack, this solution maps each bracket to its index in the string "{}[]()", so:

'{' → 0, '}' → 1

'[' → 2, ']' → 3

'(' → 4, ')' → 5

Valid pairs are those where b - a === 1 && a % 2 === 0. The algorithm:

  1. Converts the input into an array of these indexes.
  2. Iterates through the array, removing valid adjacent pairs.
  3. Steps back if a pair was removed to catch new adjacents.
  4. Returns true if the array is empty at the end.

Code Implementation

var isValid = function(s : string) : boolean {
const pattern = "{}[]()";
let arr : number[] = [];

for (let i = 0; i < s.length; i++) {
arr.push(pattern.indexOf(s[i]));
}

const isPair = (a : number, b : number) : boolean = > {
return b - a == = 1 && a % 2 == = 0;
};

for (let i = 0; i < arr.length;) {
if (i + 1 < arr.length && isPair(arr[i], arr[i + 1])) {
arr.splice(i, 2);
if (i > 0) i--;
} else {
i++;
}
}
return arr.length == = 0;
};

Time and Space Complexity

O(N)

Testing

Result of valid parenthesis
Valid Parenthesis — Result

Takeaways

Everyone solves problems in their own way. Most people use a stack for this kind of thing, but this approach shows there's always another way to look at it. As long as it works and makes sense to you, it’s a valid solution.

But in a professional setting, of course, you’ll still need to optimize and choose the most efficient and maintainable approach when it really matters.