Question

In: Computer Science

Describe an O(n)-time algorithm that checks if brackets in a given arithmetic expression is properly placed,...

Describe an O(n)-time algorithm that checks if brackets in a given arithmetic expression is properly placed, i.e., all left brackets are matched with their right counterparts and there are no unmatched brackets between any pair of matched brackets. Note that there are generally more than one types of brackets and only those of the same type can match against each other. For simplicity, you can assume that all operands are represented as ‘a’ and addition, +, is the only available operation. See below for examples of expressions, where brackets are improperly used:

(a + a) + a), (a + (a +a), ((a + ) a), a + {a + (a + a)), a + [a + (a + a] + a) Your algorithm must be non-recursive and may use a stack.

C++

Solutions

Expert Solution

Algorithm:

  • Declare a character stack S.
  • Now traverse the expression string exp.
    1. If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
    2. If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and if the popped character is the matching starting bracket then fine else parenthesis are not balanced.
  • After complete traversal, if there is some starting bracket left in stack then “not balanced”
// CPP program to check for balanced parenthesis. 
#include <bits/stdc++.h> 
using namespace std; 

// function to check if paranthesis are balanced 
bool areParanthesisBalanced(string expr) 
{ 
        stack<char> s; 
        char x; 

        // Traversing the Expression 
        for (int i = 0; i < expr.length(); i++) { 
                if (expr[i] == '(' || expr[i] == '[' || expr[i] == '{') { 
                        // Push the element in the stack 
                        s.push(expr[i]); 
                        continue; 
                } 

                // IF current current character is not opening 
                // bracket, then it must be closing. So stack 
                // cannot be empty at this point. 
                if (s.empty()) 
                        return false; 

                switch (expr[i]) { 
                case ')': 

                        // Store the top element in a 
                        x = s.top(); 
                        s.pop(); 
                        if (x == '{' || x == '[') 
                                return false; 
                        break; 

                case '}': 

                        // Store the top element in b 
                        x = s.top(); 
                        s.pop(); 
                        if (x == '(' || x == '[') 
                                return false; 
                        break; 

                case ']': 

                        // Store the top element in c 
                        x = s.top(); 
                        s.pop(); 
                        if (x == '(' || x == '{') 
                                return false; 
                        break; 
                } 
        } 

        // Check Empty Stack 
        return (s.empty()); 
} 

// Driver program to test above function 
int main() 
{ 
        string expr = "{()}[]"; 

        if (areParanthesisBalanced(expr)) 
                cout << "Balanced"; 
        else
                cout << "Not Balanced"; 
        return 0; 
} 

Time Complexity: O(n)
Auxiliary Space: O(n) for stack.


Related Solutions

1. Given three arrays of N names each, describe an O(nlogn) algorithm to determine if there...
1. Given three arrays of N names each, describe an O(nlogn) algorithm to determine if there is any name common to all three arrays, and if so, return the first such name.? 2. Given an input array with all equal values, compare the following sorting algorithm using big-O notation. Running Time Space Complexity Merge Sort Quick Sort Heap Sort
Algorithm design:Suppose that three types of parentheses are allowed in an expression: parentheses, square brackets, and...
Algorithm design:Suppose that three types of parentheses are allowed in an expression: parentheses, square brackets, and curly braces. Please design an efficient algorithm to determine whether the parentheses in the expression are correctly paired. Please write down the algorithm idea and steps. Please explain what kind of data structure is used to solve the problem, and then give the specific algorithm steps
(15 pts) Describe an O(n)-time algorithm that partitions a doubly linked list L into two doubly...
(15 pts) Describe an O(n)-time algorithm that partitions a doubly linked list L into two doubly linked lists L1 and L2, where L1 contains the odd-number-th elements in L and L2 contains the even-number-th elements in L. Elements in both L1 and L2 should appear in the same order as they appear in L. For example, if L contains the numbers 4, 7, 9, 1, and -3, in that order, then the output L1 should contain 4, 9, and -3,...
Suppose that we performed the algorithm SELECT whose running time is O(n) on 133 elements, and...
Suppose that we performed the algorithm SELECT whose running time is O(n) on 133 elements, and found the median of medians x by making groups of 5 elements. What is the maximum number of elements which are guaranteed to be greater than equals to x (without counting x, itself)?
(Linear time algorithm for finding duplicates of two sorted arrays, 20pt) Devise a linear time O(m+n)...
(Linear time algorithm for finding duplicates of two sorted arrays, 20pt) Devise a linear time O(m+n) algorithm to find the duplicates between two sorted arrays (m, n are the sizes of two arrays). For instance, for inputs {1,3,5,7} and {1,2,3,4}, the correct outputs should be {1,3
Give an O(lg n)-time EREW algorithm to perform the prefix computation on an array x[1. ....
Give an O(lg n)-time EREW algorithm to perform the prefix computation on an array x[1. . n]. Do not use pointers, but perform index computations directly.
Algorithm problem 4 [3.1-4] Is (2^(n+1))∈O(2^n)? Is (2^(2n))∈O(2^n)?
Algorithm problem 4 [3.1-4] Is (2^(n+1))∈O(2^n)? Is (2^(2n))∈O(2^n)?
Write a program (preferably in Java) that, given an arithmetic expression, first transforms it to a...
Write a program (preferably in Java) that, given an arithmetic expression, first transforms it to a postfix form, and then computes its value (by using stack-based algorithms). Assume that all the numbers in the arithmetic expression are one-digit numbers, i.e., each of these numbers is either 0, or 1, or 2, ..., or 9. For example, your program should correctly process expressions like 2+3*4, but there is no need to process expressions like 11+22.
Present an O(n) algorithm that sorts n positive integer numbers a1, a2, . . . ,...
Present an O(n) algorithm that sorts n positive integer numbers a1, a2, . . . , an which are known to be bounded by n 2 (so ai ≤ n 2 , for every i = 1, . . . , n. Use the idea of Radix Sort (discussed in class and presented in Section 8.3 in the textbook). Illustrate your algorithm by showing on paper similar to Fig. 8.3, page 198 in the textbook (make sure you indicate clearly...
A sequence {an} is given by: an = n2 - 1, n € N. Show that it is not an arithmetic progression (A.P)?
A sequence {an} is given by: an = n2 - 1,   n € N. Show that it is not an arithmetic progression (A.P)?   
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT