🧠
Brute Force (Recursive Parsing with String Manipulation)
💡 This approach exists to build intuition by directly parsing and evaluating the expression recursively without any optimization. It helps understand the problem structure before improving efficiency.
Intuition
Recursively evaluate the expression by scanning characters. When encountering '(', recursively evaluate the sub-expression inside. Use a helper function to parse numbers and operators step-by-step.
Algorithm
- Define a recursive helper function that takes the expression string and current index.
- Iterate through the string, building numbers and applying '+' or '-' operators.
- When '(' is encountered, recursively evaluate the sub-expression until the matching ')'.
- Return the computed sum and the current index to the caller.
💡 The recursion and index passing can be tricky to track, but it mirrors how nested parentheses naturally group expressions.
def calculate(s: str) -> int:
def helper(i: int) -> (int, int):
total = 0
sign = 1
num = 0
while i < len(s):
c = s[i]
if c.isdigit():
num = num * 10 + int(c)
elif c == '+':
total += sign * num
num = 0
sign = 1
elif c == '-':
total += sign * num
num = 0
sign = -1
elif c == '(':
num, i = helper(i + 1)
elif c == ')':
total += sign * num
return total, i
i += 1
total += sign * num
return total, i
result, _ = helper(0)
return result
# Driver code
if __name__ == '__main__':
print(calculate("(1+(4+5+2)-3)+(6+8)")) # Output: 23
Line Notes
def helper(i: int) -> (int, int):Defines a recursive helper that returns the computed sum and current index to handle nested parentheses.
if c.isdigit():Builds the current number digit by digit to handle multi-digit numbers.
elif c == '(':Recursively evaluates the expression inside parentheses.
elif c == ')':Returns the current total and index when closing a parenthesis is found.
import java.util.*;
public class BasicCalculator {
public int calculate(String s) {
return helper(s, 0)[0];
}
private int[] helper(String s, int i) {
int total = 0, sign = 1, num = 0;
while (i < s.length()) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
} else if (c == '+') {
total += sign * num;
num = 0;
sign = 1;
} else if (c == '-') {
total += sign * num;
num = 0;
sign = -1;
} else if (c == '(') {
int[] res = helper(s, i + 1);
num = res[0];
i = res[1];
} else if (c == ')') {
total += sign * num;
return new int[]{total, i};
}
i++;
}
total += sign * num;
return new int[]{total, i};
}
public static void main(String[] args) {
BasicCalculator calc = new BasicCalculator();
System.out.println(calc.calculate("(1+(4+5+2)-3)+(6+8)")); // 23
}
}
Line Notes
private int[] helper(String s, int i) {Helper returns an int array with result and current index to handle recursion.
if (Character.isDigit(c)) {Accumulates multi-digit numbers from characters.
int[] res = helper(s, i + 1);Recursively evaluates expression inside parentheses.
return new int[]{total, i};Returns partial result and index when closing parenthesis is found.
#include <iostream>
#include <string>
using namespace std;
class Solution {
public:
pair<int,int> helper(const string& s, int i) {
int total = 0, sign = 1, num = 0;
while (i < (int)s.size()) {
char c = s[i];
if (isdigit(c)) {
num = num * 10 + (c - '0');
} else if (c == '+') {
total += sign * num;
num = 0;
sign = 1;
} else if (c == '-') {
total += sign * num;
num = 0;
sign = -1;
} else if (c == '(') {
auto res = helper(s, i + 1);
num = res.first;
i = res.second;
} else if (c == ')') {
total += sign * num;
return {total, i};
}
i++;
}
total += sign * num;
return {total, i};
}
int calculate(string s) {
return helper(s, 0).first;
}
};
int main() {
Solution sol;
cout << sol.calculate("(1+(4+5+2)-3)+(6+8)") << endl; // 23
return 0;
}
Line Notes
pair<int,int> helper(const string& s, int i) {Returns a pair with the computed sum and current index for recursion.
if (isdigit(c)) {Builds multi-digit numbers from consecutive digits.
auto res = helper(s, i + 1);Recursively evaluates sub-expression inside parentheses.
return {total, i};Returns result and index when closing parenthesis is encountered.
var calculate = function(s) {
function helper(i) {
let total = 0, sign = 1, num = 0;
while (i < s.length) {
let c = s[i];
if (c >= '0' && c <= '9') {
num = num * 10 + (c.charCodeAt(0) - '0'.charCodeAt(0));
} else if (c === '+') {
total += sign * num;
num = 0;
sign = 1;
} else if (c === '-') {
total += sign * num;
num = 0;
sign = -1;
} else if (c === '(') {
let res = helper(i + 1);
num = res[0];
i = res[1];
} else if (c === ')') {
total += sign * num;
return [total, i];
}
i++;
}
total += sign * num;
return [total, i];
}
return helper(0)[0];
};
// Test
console.log(calculate("(1+(4+5+2)-3)+(6+8)")); // 23
Line Notes
function helper(i) {Helper function returns [result, index] to handle nested parentheses recursively.
if (c >= '0' && c <= '9') {Accumulates multi-digit numbers from characters.
let res = helper(i + 1);Recursively evaluates expression inside parentheses.
return [total, i];Returns partial result and index when closing parenthesis is found.
The recursive helper function processes each character once, using an index to avoid substring slicing. The recursion depth depends on parentheses nesting, leading to O(n) space for the call stack.
💡 Although recursion is used, each character is visited once, so the time is linear. The call stack grows with nested parentheses.
Interview Verdict: TLE on large inputs
This approach is too slow for large inputs but is valuable to understand the problem structure before optimizing.