JavaScript Interview Program

Question: Given a string exp, Write a program to check whether the parentheses, curly braces, and square brackets

Test Case 1:

//input
const exp = "{()}[]"
//output
Balanced

Test Case 2:

//input
const exp = "{(]}[("
//output
Not Balanced

The problem

You must ensure that the given string exp are properly aligned and balanced. The string "()" is balanced, for example, since each opening bracket has a corresponding closing bracket that fits its type and order. The string "(]" on the other hand is unbalanced since the second closing bracket sequence does not match the opening bracket sequence.

The Solution

To solve this problem, we'll use a stack data structure. A stack is a collection of elements with two main operations: push to add an element to the top of the stack and pop to remove the top element. We'll use the stack to keep track of the opening brackets as we encounter them, and for each closing bracket, we'll ensure that it matches the corresponding opening bracket popped from the stack.

Let's break down the implementation step by step.

Step 1: Create the Stack

We'll start by creating a Stack class that implements the basic stack operations.

//Stack.js
class Stack {
  constructor() {
    this.stack = [];
  }
  //Adding an element to  the stack;
  push(item) {
    this.stack.push(item);
  }
  //Removing an element from the stack;
  pop() {
    return this.stack.pop();
  }

  isEmpty() {
    return this.stack.length === 0;
  }
}

// exporting the instance of Stack so we can use in our main program
export const paraStack = new Stack();

If you are not familiar with the stack data structure, please watch this video it'll help you understand the program.

Step 2: Check Balanced Brackets

In this main program, we will get the input from the user. we will iterate through the string. if it's an open type of bracket it'll be pushed into the stack. If it's a close type of bracket it'll be popped from the stack. before that it checks the stack if it's empty it'll return Not Balanced. Finally, we check if the stack is empty after all operations if the stack is empty, the exp is Balanced else it's Not Balanced.

let's dive into the program

//App.js
import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
//imported the stack instance from Stack.js
import { paraStack } from './stack.js';
const rl = readline.createInterface({ input, output });

(async () => {
    //Reading the input from the user.
  const userInput = await rl.question('Enter the string with parentheses, curly braces, and square brackets: ');

  for (let i = 0; i < userInput.length; i++) {
    //pushing opening brackets to stack
    if (userInput[i] === '(' || userInput[i] === '{' || userInput[i] === '[') {
      paraStack.push(userInput[i]);
    } else if (userInput[i] === ')' || userInput[i] === '}' || userInput[i] === ']') {
        //if the stack is empty consoling "Not Balanced"  
        if (paraStack.isEmpty()) {
        console.log("Not balanced");
        rl.close();
        return;
      }

      const popped = paraStack.pop();
      //comparing the popped element if it's not matching consoling "Not Balanced"
      if (
        (userInput[i] === ')' && popped !== '(') ||
        (userInput[i] === '}' && popped !== '{') ||
        (userInput[i] === ']' && popped !== '[')
      ) {
        console.log("Not balanced");
        rl.close();
        return;
      }
    }
  }

  //Finally checking after all the operation are done, if it's empty they are balanced!
  if (paraStack.isEmpty()) {
    console.log("Balanced");
  } else {
    console.log("Not balanced");
  }

  rl.close();
})();

Conclusion

In this blog post, we've explored a simple JavaScript program that uses a stack data structure to check for balanced parentheses, curly braces, and square brackets within a given string. By leveraging the stack's properties, we can efficiently ensure that the opening and closing brackets are correctly matched and in the right order. This concept has applications in various fields, from text processing to compiler design.

Feel free to extend this program further by handling additional types of brackets or by integrating it into a larger application. Understanding data structures and algorithms like stacks can significantly enhance your problem-solving skills as a programmer!