Java Recursion 3
Java Recursion 3
Java
Recursion 3
Recursion is a programming concept where a function calls itself directly or indirectly to solve a problem by
breaking it down into smaller instances of the same problem. It involves a base case to stop the recursion
and prevent an infinite loop.
Question :
Find out all the subarrays of an array.
Array 1 2 3
SubArray-1 1
SubArray-2 2
SubArray-3 3
SubArray-4 1 2
SubArray-5 2 3
SubArray-6 1 2 3
Sample Input and Output :
Input : [1, 2, 3]
Output : [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
Code :
Java + DSA
import java.util.*;
psm.printSubArray(arr);
int n=arr.length;
System.out.println();
Explanation :
This Java code defines a class PrintSubarrayMain with a method printSubArray that prints all possible subarrays
of a given integer array using nested loops. The main method creates an instance and invokes the method with
an example array [1,2,3].
Space Complexity : The space complexity is constant, denoted as O(1), since the memory usage remains
fixed regardless of the input size. The code uses a few variables (i, j, k, n) that do not scale with the input
array length, contributing to constant space requirements.
Question :
Find out whether a given string is palindrome or not using recursion.
Java + DSA
Sample Input and Output :
Input : “Madam
Output : true
Code :
System.out.println(isPalindrome(input1));
int start = 0;
Java + DSA
private static boolean isPalindromeRecursive(String str,
int start, int end) {
return true;
if (str.charAt(start) != str.charAt(end)) {
return false;
Explanation :
This Java code determines if a given string, like "Madam", is a palindrome using a recursive approach. It
compares characters from both ends towards the center, and the recursive function returns true if the
characters match. The main method tests the string "Madam" and prints the result (true).
Space Complexity : O(n), where n is the length of the input string. The recursion stack grows linearly with the
length of the input string.
Question :
Calculate Greatest Common Divisor of two numbers.
Start with
x and y
NO x = y
y = 0? y=x%y
YES
Answer is x
Java + DSA
Sample Input and Output :
Input : 12 , 18
Output : 6
Code :
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
return a;
Explanation :
The program defines a class GCDCalculator. The main method initializes two numbers (num1 and num2) and
calls the findGCD function with these numbers. The findGCD function implements the Euclidean algorithm for
finding the GCD. It uses a while loop to repeatedly update the values of a and b until b becomes 0. In each
iteration, it calculates the remainder of the division (a % b) and updates a and b accordingly. Once the loop
exits, the GCD is stored in the variable a and returned to the main method for display.
Time and Space Complexity :
Time Complexity : The time complexity of the Euclidean algorithm is O(log min(a, b)). In the worst case, it
performs log(min(a, b)) divisions
Space Complexity : The space complexity is O(1) as the algorithm uses only a constant amount of extra
space.
Question :
Generate all binary strings of length n without consecutive 1’s
Sample Input and Output :
Input :
Output : ["000", "001", "010", "100", "101"]
Java + DSA
Code :
import java.util.ArrayList;
import java.util.List;
int n = 3;
generateStrings("", n, result);
return result;
if (n == 0) {
result.add(current);
return;
if (current.length() == 0 ||
current.charAt(current.length() - 1) == '0') {
} else {
Explanation :
The class BinaryStringsGenerator uses a main method to initialize n and call generateBinaryStrings. The latter
constructs binary strings without consecutive 1’s through recursive appending of '0' or '1' based on the last
character. The recursion halts when n is 0, and the current string is added to the result list.
Time and Space Complexity :
Time Complexity : O(2^n) - Each binary string of length n is generated, and at each position, there are two
choices (0 or 1)
Space Complexity : O(2^n) - The space required for storing all binary strings.
Java + DSA
Question :
Combination Sum :
Return a list of all unique combinations of candidates where the chosen numbers sum to target.
List<List<Integer>> result =
solution.combinationSum(nums, target);
System.out.println(combination);
Java + DSA
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
return list;
else{
tempList.add(nums[i]);
Explanation :
It uses a backtracking approach to explore and build combinations, considering reuse of elements. The
combinationSum method initializes the process, and backtrack recursively generates valid combinations.
Time and Space Complexity :
Time Complexity : O(2^n), where n is the length of nums
Space Complexity : O(n) due to the recursive call stack and space for the result and temporary lists.
Question :
Generate Parentheses :
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Java + DSA
Sample Input and Output :
Input : n=
Output : ["((()))","(()())","(())()","()(())","()()()"]
Code :
class Solution {
List<String> result;
return result;
result.add(sb.toString());
return;
return;
sb.deleteCharAt(sb.length() - 1);
sb.deleteCharAt(sb.length() - 1);
Explanation :
It uses backtracking to explore and build combinations, ensuring that the number of opening and closing
parentheses is balanced. The generateParenthesis method initializes the process, and the helper function
recursively generates valid combinations.
Space Complexity : O(n) - The space is used for the recursive call stack and the StringBuilder to store each
combination.
Java + DSA
Question :
We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every subsequent row, we look
at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. For example, for
n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110. Given two integer n and k, return the kth (1-
indexed) symbol in the nth row of a table of n rows.
Input : n=1 , k=
Output : 0
Code :
class Solution {
if(n < 3)
return k - 1;
Explanation :
It recursively reduces the problem by half at each step, using the fact that each row is constructed based on the
previous row.
Question :
Count and Say : The count-and-say sequence is a sequence of digit strings defined by the recursive formula:
countAndSay(1) = "1" countAndSay(n) is the way you would "say" the digit string from countAndSay(n-1), which is
then converted into a different digit string. To determine how you "say" a digit string, split it into the minimal
number of substrings such that each substring contains exactly one unique digit. Then for each substring, say
the number of digits, then say the digit. Finally, concatenate every said digit.
Java + DSA
Sample Input and Output :
Input : n=
Output : “1”
Code :
class Solution {
if(n==1)
return "1";
if(n==2)
return "11";
nm.append("11");
for(int i=3;i<=n;i++)
task(nm.toString(),kk);
nm.setLength(0);
nm.append(kk);
return nm.toString();
int count=1;
for(int i=0;i<s.length()-1;i++)
if(s.charAt(i) == s.charAt(i+1))
count++;
else
Java + DSA
nm.append(count);
nm.append(s.charAt(i));
count=1;
nm.append(count);
nm.append(s.charAt(s.length()-1));
Explanation : This Java code generates the nth term of the "Count and Say" sequence. It iteratively constructs
each term based on the previous one by counting consecutive identical digits. The countAndSay method
initializes the sequence and calls the helper method task to generate each term.
Space Complexity : O( ) 1 , as it works iteratively , it does not occupy any space in memory.
Question :
Permutation Sequence :
The set [1, 2, 3, ..., n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order, we get the following sequence for n = 3:
"123
"132
"213
"231
"312
"321"
Input : n=3, k=
O utput : 213“ ”
Code :
class Solution {
int sum=1;
Java + DSA
sum/=n--;
if(k%sum==0){sb.append(lr.remove(k/(sum)-1));
for(int i=lr.size()-1;i>=0;i--) sb.append(lr.get(i)); return
sb.toString();}
sb.append(lr.remove(k/(sum)));
k=k%sum;
return sb.toString();
Explanation : This Java code generates the kth permutation of numbers from 1 to n in lexicographical order. It
uses factorials to determine the number of permutations at each digit place, iteratively selecting digits based
on the given value of k. The code achieves linear time complexity and space complexity.
Java + DSA