Posts

Showing posts with the label recursion

Is the space complexity of a recursive algorithm necessarily at least as large as the depth of the recursive call?

Image
Clash Royale CLAN TAG #URR8PPP Is the space complexity of a recursive algorithm necessarily at least as large as the depth of the recursive call? I am having trouble determining when recursive functions are sub-optimal to their iterative counterparts when space is an issue. When writing recursive functions, is the space complexity necessarily at least as large as the depth of the recursive call if it is not tail recursive? For example, lets remove duplicates from a linked list using recursion. This can be done trivially with an iterative approach in O(n^2) time and O(1) space. But is the recursive variant also O(1) space? removeDuplicatesRecursive() { let current = this.head; while (current.next) { if (this.head.data === current.next.data) { current.next = current.next.next } else { current = current.next; } } if (this.head.next) { removeDuplicatesRecursive(this.head.next); } return head; } Yo...

Deleting all consonants from a string using recursion in c++

Image
Clash Royale CLAN TAG #URR8PPP Deleting all consonants from a string using recursion in c++ I'm almost completely new to programming and I try to learn C++. This is the first task where I feel like I hit a wall. I tried to search but because people usually use a loop to solve the problem I could not find anything. I tried to find a recursive solution to delete all consonants from a string (I think I know how to solve it using loops, but wanted to expand my knowledge on recursion). #include <iostream> #include <string> using namespace std; int i = 0; string s(""); string del_cons(string z){ if(i == (z.length()-1) ){ s+= z.substr(i); return s; } else if(z[i] == 'a' || z[i] == 'e' || z[i] == 'i' || z[i] == 'o' || z[i] == 'u'){ i++; s+= del_cons(z.substr(i)); return s; } else{ s+= z.substr(i,1); i++; s+= del_cons(z.substr(i)); return...

Path from given node to root in a binary tree

Image
Clash Royale CLAN TAG #URR8PPP Path from given node to root in a binary tree I've been trying to figure this problem out for a while now and I'm not really getting anywhere with it. Essentially, given some binary tree and a node on that tree, how would you find the path from that given node back to the root? Does anyone have an idea on how I could implement this? Any input would be greatly appreciated, my sincere thanks from a novice coder. give your code. how u store data – sajib 2 days ago Does your node implementation have a notion of parent, or does it only know its children? – Roddy of the Frozen Peas 2 days ago Hint: Stack, DFS – Jiga...