#32

Longest Valid Parentheses

HardStack / DPHas vizStringDynamic ProgrammingStack

Problem

Longest Valid Parentheses

You must solve the interview problem titled "Longest Valid Parentheses".

Difficulty: Hard. Topics: String, Dynamic Programming, Stack. Primary pattern: Stack / DP.

Read the title as the specification: implement the exact behavior it names, return the correct output type, and aim for an interview-optimal Stack / DP solution. Use the examples to lock input/output format, then confirm edge cases (empty, single element, duplicates, extremes).

Example 1

Input: sample input for Longest Valid Parentheses

Output: sample output for Longest Valid Parentheses

Apply a Stack / DP approach and match the required return type.

Example 2

Input: edge-case input for Longest Valid Parentheses

Output: edge-case output for Longest Valid Parentheses

Verify empty/single/boundary behavior.

Constraints

  • Interview-scale limits for a Hard Stack / DP problem.
  • Handle empty and single-element inputs when they are valid.
  • Prefer the optimal asymptotic complexity expected in interviews.
Loading visualization…

Explanation

Longest Valid Parentheses is a Hard interview problem tagged [String, Dynamic Programming, Stack]. The winning approach is typically **Stack / DP**.

Intuition

Some parenthesis problems need both matching and length accumulation.

Approach

Combine stack structure for validity with DP for longest counts.

  1. Clarify what dp[i] stores.
  2. Use stack indices to jump.
  3. Extend lengths across adjacent valid segments.

Solution

Curated solution in C#, Python, Java, JavaScript, and C++ — switch languages with the tabs.

Exact solutionStack / DP

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n²)

Space: O(n)

Before coding, restate the problem, name the pattern (Stack / DP), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #32 Longest Valid Parentheses as understood when the pattern clicks.