Bird
Raised Fist0
DSA Javaprogramming~20 mins

Recursion on Arrays and Strings in DSA Java - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Recursion Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Recursive Sum of Array Elements
What is the output of the following Java code that recursively sums elements of an array?
DSA Java
public class Main {
    public static int recursiveSum(int[] arr, int index) {
        if (index == arr.length) {
            return 0;
        }
        return arr[index] + recursiveSum(arr, index + 1);
    }

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4};
        System.out.println(recursiveSum(numbers, 0));
    }
}
A0
B24
CError at runtime
D10
Attempts:
2 left
💡 Hint
Think about how the function adds each element starting from index 0 until the end.
❓ Predict Output
intermediate
2:00remaining
Output of Recursive String Reverse
What is the output of this Java code that recursively reverses a string?
DSA Java
public class Main {
    public static String reverseString(String s) {
        if (s.isEmpty()) {
            return s;
        }
        return reverseString(s.substring(1)) + s.charAt(0);
    }

    public static void main(String[] args) {
        System.out.println(reverseString("code"));
    }
}
Aedoc
Bedco
CError: StringIndexOutOfBoundsException
Dcode
Attempts:
2 left
💡 Hint
The function takes the first character and puts it at the end after reversing the rest.
🧠 Conceptual
advanced
2:00remaining
Understanding Base Case in Recursive Array Search
In a recursive function that searches for a target value in an array, what is the correct base case to stop recursion?
AWhen the index reaches the length of the array
BWhen the target is found anywhere in the array
CWhen the array is empty
DWhen the index is negative
Attempts:
2 left
💡 Hint
Think about when the function should stop searching without finding the target.
🔧 Debug
advanced
2:00remaining
Identify the Error in Recursive Palindrome Check
What error will occur when running this Java code that checks if a string is a palindrome recursively?
DSA Java
public class Main {
    public static boolean isPalindrome(String s, int start, int end) {
        if (start >= end) {
            return true;
        }
        if (s.charAt(start) != s.charAt(end)) {
            return false;
        }
        return isPalindrome(s, start + 1, end - 1);
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("racecar", 0, 6));
    }
}
APrints false
BPrints true
CStringIndexOutOfBoundsException
DCompilation error
Attempts:
2 left
💡 Hint
Check the end index passed to the function and string length.
🚀 Application
expert
3:00remaining
Result of Recursive Flattening of Nested Integer Arrays
Given the following Java code that recursively flattens nested integer arrays into a single list, what is the printed output?
DSA Java
import java.util.*;

public class Main {
    public static void flatten(Object[] arr, List<Integer> result) {
        for (Object obj : arr) {
            if (obj instanceof Integer) {
                result.add((Integer) obj);
            } else if (obj instanceof Object[]) {
                flatten((Object[]) obj, result);
            }
        }
    }

    public static void main(String[] args) {
        Object[] nested = {1, new Object[]{2, 3}, 4, new Object[]{new Object[]{5}, 6}};
        List<Integer> flatList = new ArrayList<>();
        flatten(nested, flatList);
        System.out.println(flatList);
    }
}
A[1, 2, 3, 4, 6, 5]
B[1, 2, 3, 4, [5], 6]
C[1, 2, 3, 4, 5, 6]
DRuntime error due to casting
Attempts:
2 left
💡 Hint
The function adds integers directly and recursively processes nested arrays.

Practice

(1/5)
1. What does a recursive function on an array typically do to process the elements?
easy
A. It calls itself with a smaller part of the array until a base case is reached
B. It uses loops to iterate over the array elements
C. It modifies the array without calling itself
D. It sorts the array before processing

Solution

  1. Step 1: Understand recursion on arrays

    Recursive functions reduce the problem size by calling themselves with smaller parts of the array.
  2. Step 2: Identify base case and recursive call

    The function stops when the array part is empty or has one element (base case), otherwise it calls itself with a smaller array.
  3. Final Answer:

    It calls itself with a smaller part of the array until a base case is reached -> Option A
  4. Quick Check:

    Recursion = smaller problem calls [OK]
Hint: Recursion breaks problem into smaller parts until simple case [OK]
Common Mistakes:
  • Thinking recursion uses loops instead of self-calls
  • Ignoring the base case in recursion
  • Assuming recursion sorts the array automatically
2. Which of the following is the correct syntax to define a recursive method in Java that takes an integer array and an index as parameters?
easy
A. void recurse(int arr[], index int) { ... }
B. public void recurse(int[] arr, int index) { ... }
C. public int recurse(int arr, int index) { ... }
D. public void recurse(int[] arr; int index) { ... }

Solution

  1. Step 1: Check Java method syntax

    Java methods require return type, method name, and parameters with types and commas.
  2. Step 2: Validate parameter types and order

    public void recurse(int[] arr, int index) { ... } correctly uses 'int[] arr' and 'int index' separated by a comma and proper method signature.
  3. Final Answer:

    public void recurse(int[] arr, int index) { ... } -> Option B
  4. Quick Check:

    Java method syntax = returnType name(type1 param1, type2 param2) [OK]
Hint: Remember Java method parameters need types and commas [OK]
Common Mistakes:
  • Using wrong parameter order or missing commas
  • Incorrect array parameter syntax
  • Missing return type in method definition
3. What will be the output of the following Java code?
public class Test {
  public static void printArray(int[] arr, int index) {
    if (index == arr.length) return;
    System.out.print(arr[index] + " ");
    printArray(arr, index + 1);
  }
  public static void main(String[] args) {
    int[] nums = {1, 2, 3};
    printArray(nums, 0);
  }
}
medium
A. Compilation error
B. 3 2 1
C. 1 2 3 0
D. 1 2 3

Solution

  1. Step 1: Trace the recursive calls

    printArray prints arr[index] then calls itself with index+1 until index equals arr.length (3).
  2. Step 2: Output elements in order

    It prints 1, then 2, then 3, then stops without extra output.
  3. Final Answer:

    1 2 3 -> Option D
  4. Quick Check:

    Recursion prints array elements in order [OK]
Hint: Recursion prints then calls next index until end [OK]
Common Mistakes:
  • Expecting reverse order output
  • Thinking extra elements print after recursion ends
  • Confusing base case condition
4. Identify the error in this recursive method that tries to sum elements of an integer array:
public int sumArray(int[] arr, int index) {
  if (index > arr.length) return 0;
  return arr[index] + sumArray(arr, index + 1);
}
medium
A. Array parameter should be List<Integer>
B. Method should return void instead of int
C. Base case condition should be index >= arr.length
D. Recursive call should use index - 1

Solution

  1. Step 1: Check base case condition

    Index should stop recursion when it reaches arr.length, so condition must be index >= arr.length.
  2. Step 2: Understand array bounds

    Using index > arr.length allows index == arr.length, which causes ArrayIndexOutOfBoundsException.
  3. Final Answer:

    Base case condition should be index >= arr.length -> Option C
  4. Quick Check:

    Base case must prevent out-of-bounds access [OK]
Hint: Base case index must not exceed array length [OK]
Common Mistakes:
  • Using wrong base case condition causing runtime error
  • Changing return type incorrectly
  • Incorrect recursive index update
5. Given a string, write a recursive method to check if it is a palindrome (reads the same forwards and backwards). Which approach correctly describes the recursion?
hard
A. Compare first and last characters, then recurse on substring excluding them
B. Reverse the string using recursion and compare with original
C. Count characters recursively and check if count is even
D. Use recursion to sort characters and check equality

Solution

  1. Step 1: Understand palindrome check logic

    Check if first and last characters match, then check the substring inside recursively.
  2. Step 2: Identify correct recursive approach

    Compare first and last characters, then recurse on substring excluding them matches this logic, reducing problem size each call until base case (empty or one char string).
  3. Final Answer:

    Compare first and last characters, then recurse on substring excluding them -> Option A
  4. Quick Check:

    Palindrome recursion = compare ends, recurse inside substring [OK]
Hint: Check ends match, then recurse inside substring [OK]
Common Mistakes:
  • Trying to reverse string recursively instead of comparing ends
  • Counting characters instead of comparing
  • Sorting characters which changes original order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard