JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

JavaScript

/**
 * Function to remove the minimum number of parentheses to make the string valid.
 * @param {string} s - Input string with parentheses and lowercase English characters.
 * @returns {string} - Valid string after removing minimum parentheses.
 */
function minRemoveToMakeValid(s) {
  // Create a set to store indices of unmatched parentheses
  const unmatchedIndices = new Set();

  // Create a stack to keep track of unmatched opening parentheses
  const stack = [];

  // Iterate through the string to find unmatched parentheses
  for (let i = 0; i < s.length; i++) {
    if (s[i] === '(') {
      stack.push(i); // Push the index of an opening parenthesis onto the stack
    } else if (s[i] === ')') {
      if (stack.length === 0) {
        unmatchedIndices.add(i); // Mark the index of an unmatched closing parenthesis
      } else {
        stack.pop(); // Match the closing parenthesis with the top opening parenthesis
      }
    }
  }

  // Add remaining unmatched opening parentheses to the set
  unmatchedIndices.add(...stack);

  // Construct the valid string by excluding characters at unmatched indices
  const result = s
    .split('')
    .filter((_, i) => !unmatchedIndices.has(i))
    .join('');

  return result;
}

// Example usage:
const inputString = "))((";
const resultString = minRemoveToMakeValid(inputString);

// Output the result
console.log(resultString);