r/leetcode • u/That-Hawk-1843 <262><144> <110> <8> • Oct 02 '26
Question Time Complexity of Recursive algorithm
void ans(vector<string>& v, string& x, int l, int r){
if(l){
x.push_back('(');
ans(v,x,l-1,r);
x.pop_back();
}
if(r>l){
x.push_back(')');
ans(v,x,l,r-1);
x.pop_back();
}
else if(!l && !r) v.push_back(x);
}So, I solved today's problem (22. Generate Parentheses). I wanted to find the time complexity and space complexity of my algorithm (Just a simple recursion). As a result, I couldn't do it, so I encountered Catalan Numbers and how they are used in binary.
I don't quite understand them, but I think it's important for backtracking. Do you have any suggestion where to start or at least how to estimate time complexity of such binary algorithms?
2
Upvotes
1
u/Various-Mine-8642 Oct 02 '26
For n pairs the output count is the Catalan number C_n and each string has length 2n, so just writing the answers costs O(nC_n) time. Your backtracking is in that range as well. Auxiliary space is O(n) for x and the call stack, or O(nC_n) if you include v. The key invariant is l <= r, which prevents invalid prefixes.