All interview topics
Algorithms & Data Structures

Recursion Interview Questions and Answers

Practice Recursion interview questions and answers organized by difficulty, with revealable explanations and related topics.

9 questionsEntry → Expert

Junior questions

4 questions
  1. Question 1
    Junior

    What is a good example of Recursion (other than generating a Fibonacci sequence)?

    • Recursion
    Reveal answer

    There are some: The binary tree search Check for a palyndrome Finding factorial Traversing the folder hierarchy of a directory tree as part of a file system Towers of Hanoi Merge sort Catalan numbers

  2. Question 1
    Junior

    What is the difference between Backtracking and Recursion?

    • Backtracking Recursion
    Reveal answer

    Recursion describes the calling of the same function that you are in. The typical example of a recursive function is the factorial. You always need a condition that makes recursion stop (base case). Backtracking is when the algorithm makes an opportunistic decision*, which may come up to be wrong. If the decision was wrong then the backtracking algorithm restores the state before the decision. It builds candidates for the solution and abandons those which cannot fulfill the conditions. A typical example for a task to solve would be the Eight Queens Puzzle. Backtracking is also commonly used within Neuronal Networks. Many times backtracking is not implemented recursively. If backtracking uses recursion its called Recursive Backtracking P.S. * Opportunistic decision making refers to a process where a person or group assesses alternative actions made possible by the favorable convergence of immediate circumstances recognized without reference to any general plan.

  3. Question 2
    Junior

    How Dynamic Programming is different from Recursion and Memoization?

    • Dynamic Programming Recursion
    Reveal answer

    Memoization is when you store previous results of a function call (a real function always returns the same thing, given the same inputs). It doesn't make a difference for algorithmic complexity before the results are stored. Recursion is the method of a function calling itself, usually with a smaller dataset. Since most recursive functions can be converted to similar iterative functions, this doesn't make a difference for algorithmic complexity either. Dynamic programming is the process of solving easier-to-solve sub-problems and building up the answer from that. Most DP algorithms will be in the running times between a Greedy algorithm (if one exists) and an exponential (enumerate all possibilities and find the best one) algorithm. DP algorithms could be implemented with recursion, but they don't have to be. DP algorithms can't be sped up by memoization, since each sub-problem is only ever solved (or the "solve" function called) once.

  4. Question 3
    Junior

    What is the difference between Backtracking and Recursion?

    • Backtracking Recursion
    Reveal answer

    Recursion describes the calling of the same function that you are in. The typical example of a recursive function is the factorial. You always need a condition that makes recursion stop (base case).

    Backtracking is when the algorithm makes an opportunistic decision*, which may come up to be wrong. If the decision was wrong then the backtracking algorithm restores the state before the decision. It builds candidates for the solution and abandons those which cannot fulfill the conditions. A typical example for a task to solve would be the Eight Queens Puzzle. Backtracking is also commonly used within Neuronal Networks. Many times backtracking is not implemented recursively. If backtracking uses recursion its called Recursive Backtracking P.S. * Opportunistic decision making refers to a process where a person or group assesses alternative actions made possible by the favorable convergence of immediate circumstances recognized without reference to any general plan.

Senior questions

3 questions
  1. Question 2
    Senior

    How to recursively reverse a Linked List?

    • Linked Lists Recursion JavaScript
    Reveal answer

    Start from the bottom up by asking and answering tiny questions: What is the reverse of null (the empty list)? null . What is the reverse of a one element list? the element. What is the reverse of an n element list? the reverse of the rest of the list followed by the first element. P.S. How to understand that part?

    head.next.next = head;
    head.next = null;
    

    Think about the origin link list: 1->2->3->4->5 Now assume that the last node has been reversed. Just like this: 1->2->3->4<-5

    And this time you are at the node 3 , you want to change 3->4 to 3<-4 , means let 3->next->next = 3 (as 3-

    next is 4 and 4->next = 3 is to reverse it) Complexity Analysis: Time Complexity: O(n) Space Complexity: O(n) Assume that n is the list's length, the time complexity is

    O(
    n) . The extra space comes from implicit stack space
    

    due to recursion. The recursion could go up to n levels deep then space complexity is

    O(
    n) .
    Implementation:
    JS
    var reverseList = function(head) {
      if (!head) {
        return head;
      }
    let pre = head.next;
    head.next = null;
    return fun(head, pre);
    function fun(cur, pre) {
      if (pre == null) {
        return cur;
      }
    let tmp = pre.next;
    pre.next = cur;
    return fun(pre, tmp);
    }
    }
    Java
    Node reverse(Node head) {
      // if head is null or only one node, it's reverse of itself.
      if ( (head == null) || (head.next == null) ) return head;// reverse the sub-list leaving the head node.
      Node reverse = reverse(head.next);// head.next still points to the last element of reversed sub-list.
      // so move the head to end.
      head.next.next = head;// point last node to nil, (get rid of cycles)
      head.next = null;
      return reverse;
    }
    PY
    class Solution(object):
    def reverseList(self, head):
    # Recursive
    """
    :type head: ListNode
    :rtype: ListNode
    """
    if not head or not head.next:
    

    return head

    p = self.reverseList(head.next)
    head.next.next = head
    head.next = None
    

    return p

  2. Question 7
    Senior

    How to recursively reverse a Linked List?

    • Linked Lists Recursion JavaScript
    Reveal answer

    Start from the bottom up by asking and answering tiny questions: What is the reverse of null (the empty list)? null . What is the reverse of a one element list? the element.

    What is the reverse of an n element list? the reverse of the rest of the list followed by the first element. P.S. How to understand that part?

    head.next.next = head;
    head.next = null;
    

    Think about the origin link list: 1->2->3->4->5 Now assume that the last node has been reversed. Just like this: 1->2->3->4<-5 And this time you are at the node 3 , you want to change 3->4 to 3<-4 , means let 3->next->next = 3 (as 3-

    next is 4 and 4->next = 3 is to reverse it) Complexity Analysis: Time Complexity: O(n) Space Complexity: O(n) Assume that n is the list's length, the time complexity is

    O(
    n) . The extra space comes from implicit stack space
    

    due to recursion. The recursion could go up to n levels deep then space complexity is

    O(
    n) .
    Implementation:
    JS
    var reverseList = function(head) {
      if (!head) {
        return head;
      }
    let pre = head.next;
    head.next = null;
    return fun(head, pre);
    function fun(cur, pre) {
      if (pre == null) {
        return cur;
      }
    let tmp = pre.next;
    pre.next = cur;
    return fun(pre, tmp);
    }
    }
    Java
    Node reverse(Node head) {
      // if head is null or only one node, it's reverse of itself.
      if ( (head == null) || (head.next == null) ) return head;
    
      // reverse the sub-list leaving the head node.
      Node reverse = reverse(head.next);// head.next still points to the last element of reversed sub-list.
      // so move the head to end.
      head.next.next = head;// point last node to nil, (get rid of cycles)
      head.next = null;
      return reverse;
    }
    PY
    class Solution(object):
    def reverseList(self, head):
    # Recursive
    """
    :type head: ListNode
    :rtype: ListNode
    """
    if not head or not head.next:
    

    return head

    p = self.reverseList(head.next)
    head.next.next = head
    head.next = None
    

    return p

  3. Question 9
    Senior

    Is it always possible to write a non-recursive form for every Recursive function?

    • Recursion
    Reveal answer

    When you use a function recursively, the compiler takes care of stack management for you, which is what makes recursion possible. Anything you can do recursively, you can do by managing a stack yourself (for indirect recursion, you just have to make sure your different functions share that stack). A simple formal proof is to show that both μ recursion (general recursive function) and a non-recursive calculus such as GOTO are both Turing complete. Since all Turing complete calculi are strictly equivalent in their expressive power, all recursive functions can be implemented by the non-recursive Turing-complete calculus.

Mid questions

2 questions
  1. Question 5
    Mid

    Explain what is DFS (Depth First Search) algorithm for a Graph and how does it work?

    • Backtracking Graph Theory Recursion
    Reveal answer

    Depth First Traversal or Depth First Search is a edge based recursive algorithm for traversing (visiting) all the vertices of a graph or tree data structure using a stack. The purpose of the algorithm is to mark each vertex as visited while avoiding cycles. DFS traverse/visit each vertex exactly once and each edge is inspected exactly twice. DFS is a genuinely recursive algorithm that uses stack for backtracking purposes, not for storing the vertex discovery "front" (as is the case in BFS). The DFS algorithm works as follows: Start by putting any one of the graph's vertices on top of a stack. Take the top item of the stack and add it to the visited list.

    Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the top of the stack. Keep repeating steps 2 and 3 until the stack is empty. DFS example step-by-step: Considering A as the starting vertex which is explored and stored in the stack. B successor vertex of A is stored in the stack. Vertex B have two successors E and F, among them alphabetically E is explored first and stored in the stack. The successor of vertex E, i.e., G is stored in the stack. Vertex G have two connected vertices, and both are already visited, so G is popped out from the stack. Similarly, E s also removed. Now, vertex B is at the top of the stack, its another node(vertex) F is explored and stored in the stack. Vertex F has two successor C and D, between them C is traversed first and stored in the stack. Vertex C only have one predecessor which is already visited, so it is removed from the stack. Now vertex D connected to F is visited and stored in the stack. As vertex D doesn’t have any unvisited nodes, therefore D is removed. Similarly, F, B and A are also popped. The generated output is – A, B, E, G, F, C, D.

  2. Question 6
    Mid

    Convert a Binary Tree to a Doubly Linked List

    • Binary Tree Divide & Conquer Linked Lists Recursion Data Structures
    Reveal answer

    This can be achieved by traversing the tree in the in-order manner that is, left the child -> root ->right node.

    In an in-order traversal, first the left sub-tree is traversed, then the root is visited, and finally the right sub-tree is traversed. One simple way of solving this problem is to start with an empty doubly linked list. While doing the in-order traversal of the binary tree, keep inserting each element output into the doubly linked list. But, if we look at the question carefully, the interviewer wants us to convert the binary tree to a doubly linked list in-place i.e. we should not create new nodes for the doubly linked list. This problem can be solved recursively using a divide and conquer approach. Below is the algorithm specified. Start with the root node and solve left and right sub-trees recursively At each step, once left and right sub-trees have been processed: fuse output of left subtree with root to make the intermediate result fuse intermediate result (built in the previous step) with output from the right sub-tree to make the final result of the current recursive call Complexity Analysis: Time Complexity: O(n) Space Complexity: O(n)

    Recursive solution has

    O(
    h) memory complexity as it will consume memory on the stack up to the height of
    

    binary tree h . It will be

    O(
    log n) for balanced tree and in worst case can be
    O(
    n) .
    Implementation:
    Java
    public static void BinaryTreeToDLL(Node root) {
      if (root == null)
      return;
      BinaryTreeToDLL(root.left);
      if (prev == null) {
        // first node in list
        head = root;
      } else {
        prev.right = root;
        root.left = prev;
      }
    prev = root;
    BinaryTreeToDLL(root.right);
    if (prev.right == null) {
      // last node in list
      head.left = prev;
      prev.right = head;
    }
    }
    PY
    def BinaryTreeToDLL(self, node):
    #Checks whether node is None
    if(node == None):
    return;#Convert left subtree to doubly linked list
    self.BinaryTreeToDLL(node.left);#If list is empty, add node as head of the list
    if(self.head == None):
    

    #Both head and tail will point to node

    self.head = self.tail = node;
    

    #Otherwise, add node to the end of the list else: #node will be added after tail such that tail's right will point to node

    self.tail.right = node;
    #node's left will point to tail
    node.left = self.tail;
    #node will become new tail
    self.tail = node;#Convert right subtree to doubly linked list
    self.BinaryTreeToDLL(node.right);