I am solving this problem on leetcode. Can't figure out the time and space complexity for my solution.
Particularly, I can't understand how to apply Master Theorem here in case when we have FOR loop. What is a and b here? Since input divided multiple times and for different size of subproblems. Another complication is memoization.
class Solution {
private Map<String, List<Integer>> cache = new HashMap<>();
public List<Integer> diffWaysToCompute(String equation) {
if (cache.containsKey(equation)) return cache.get(equation);
if (!(equation.contains("+") || equation.contains("-") || equation.contains("*"))) return Collections.singletonList(Integer.valueOf(equation));
List<Integer> result = new ArrayList<>();
for (int i = 0; i < equation.length();i++) {
char ch = equation.charAt(i);
if (ch == '+' || ch == '-' || ch == '*') {
List<Integer> left = diffWaysToCompute(equation.substring(0, i));
List<Integer> right = diffWaysToCompute(equation.substring(i+1, equation.length()));
result.addAll(crossCalc(left, right, ch));
}
}
cache.put(equation, result);
return result;
}
private List<Integer> crossCalc(List<Integer> left, List<Integer> rigth, char sign) {
List<Integer> result = new ArrayList<>();
for (Integer l : left) {
for (Integer r : rigth) {
if (sign == '-') {
result.add(l - r);
} else if (sign == '+') {
result.add(l + r);
} else {
result.add(l*r);
}
}
}
return result;
}
}
I am looking for explanation how to calculate time complexity, not only the answer. Preferably if you could explain complexity for both with and without memoization. Thanks!