Anjanesh Lekshminarayanan
Anjanesh

Anjanesh

Finding out all the expressions within brackets

Anjanesh Lekshminarayanan's photo
Anjanesh Lekshminarayanan
·Mar 30, 2020·

min read

Subscribe to my newsletter and never miss my upcoming articles

Finding out all the expressions within brackets : I was actually asked to find out the smallest bracket expression within an expression, I have omitted the function to check for the smallest string and omitting spaces within the expression.

This was actually an interview question at a startup in Seawoods, Navi Mumbai.

Given an expression like ((a + b * d) * (x / 2)) * (1 + (y + (x - 2) / 10)) the smallest expression within brackets is x / 2 and x - 2. If we can find all the expressions within the brackets, then finding the smallest ones is as simple enough by finding the length after removing the spaces.

<?php
$s = "((a + b * d) * (x / 2)) * (1 + (y + (x - 2) / 10))";
$b = [];
$j = 0;
$stack = [];

for ($i = 0; $i < strlen($s); $i++)
{   
    if ($s[$i] == '(')
    {       
        $b[++$j] = '';
    }
    elseif ($s[$i] == ')')
    {       
        $stack[] = ($b[$j--] .= ')');   
    }
    for ($k = 1; $k <= $j; $k++)
    {
        $b[$k] .= $s[$i];
    }
}
echo $s.PHP_EOL;
print_r($stack);
echo PHP_EOL;
?>
php brackets.php 
((a + b * d) * (x / 2)) * (1 + (y + (x - 2) / 10))
Array
(
    [0] => (a + b * d)
    [1] => (x / 2)
    [2] => ((a + b * d) * (x / 2))
    [3] => (x - 2)
    [4] => (y + (x - 2) / 10)
    [5] => (1 + (y + (x - 2) / 10))
)
 
Share this