FastPrepValid Parentheses

Valid Parentheses

EPAM logoEPAM● EasyNEW GRADINTERNONSITE INTERVIEW

Problem statement

Given a string s that contains only the characters (, ), [, ], { and }, decide whether it is valid.

The string is valid when all of these rules hold:

  • Every opening bracket is closed by a closing bracket of the same type.
  • Brackets are closed in the right order: the bracket opened last is closed first.
  • Every closing bracket matches an opening bracket that comes before it.

Return true if s is valid, and false otherwise.

Function

isValid(s: String) → boolean

Examples

Example 1

s = "()[]{}"return = true

Each opening bracket is closed right away by a bracket of the same type.

Example 2

s = "{[()]}"return = true

The brackets are nested. The last bracket opened, (, is closed first, then [, then {.

Example 3

s = "([)]"return = false

The [ was opened after the (, so it must be closed first. The next closing bracket is ) while [ is still open, so the order is wrong.

Example 4

s = "(("return = false

Two brackets are opened but neither is closed.

Constraints

  • 1 <= s.length <= 10^4
  • s contains only the characters ()[]{}.

More EPAM problems

See EPAM hiring insights
Saved
public boolean isValid(String s) {
    // Write your code here.
}
Checking account…