Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Sunday, 24 March 2019

The Interview Question Today#23(18-3-19)

Question:
Given four integers a, b, c and d which signifies the number of four types of brackets.

A=> “((“
B=> “()”
C=> “)(“
D=> “))”

The task is to print any balanced bracket expression using all the given brackets. If we cannot form a balanced bracket expression then print -1. 

Examples:

Input: a = 3, b = 1, c = 4, d = 3

Output: (((((()()()()())))))()

Solution:
Approach: 
First check if the balanced bracket expression can be formed with the given number of brackets. We can form the expression if the number of A brackets is equal to the number of D brackets with any number of C brackets And B type brackets or if there are only type B brackets. Hence the combining condition will be:

(a == d && a) || (a == 0 && c == 0 && d == 0)

C program:

#include <stdio.h>

// Function to print balanced bracket expression if it is possible
int printBalancedExpression(int a, int b, int c, int d)
{
int i;
    if ((a == d && a) || (a == 0 && c == 0 && d == 0)) {

        for ( i = 1; i <= a; i++)
            printf("((");

        for ( i = 1; i <= b; i++)
            printf("()");
        for ( i = 1; i <= c; i++)
            printf(")(");

        for ( i = 1; i <= d; i++)
            printf("))");


    }

    else{
        printf(-1);
        return 0;}
        return 1;
}
int main()
{
    int a,b,c,d;
    printf("Enter Value of A:");
    scanf("%d",&a);
    printf("\nEnter Value of B:");
    scanf("%d",&b);
    printf("\nEnter Value of C:");
    scanf("%d",&c);
    printf("\nEnter Value of D:");
    scanf("%d",&d);
    printf("\n");
    if(printBalancedExpression(a, b, c, d)){
     printf("\tBalanced Brackets");
    }
    else{
     printf("\tUnBalanced Brackets");
    }
    return 0;
}

Output:
Enter Value of A:1

Enter Value of B:1

Enter Value of C:1

Enter Value of D:1

((())())        Balanced Brackets

0 comments:

Post a Comment