0% found this document useful (0 votes)
2 views

java recursion

The document contains various recursive algorithms including calculating the sum of an array, reversing an array, checking for palindromes, and performing linear and binary searches. It also discusses generating stair paths and counting ways to climb stairs, as well as generating letter combinations from phone digits. Each algorithm is accompanied by its time and space complexity analysis.

Uploaded by

Siddhant Fatewar
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

java recursion

The document contains various recursive algorithms including calculating the sum of an array, reversing an array, checking for palindromes, and performing linear and binary searches. It also discusses generating stair paths and counting ways to climb stairs, as well as generating letter combinations from phone digits. Each algorithm is accompanied by its time and space complexity analysis.

Uploaded by

Siddhant Fatewar
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

Fibonacci series

Time O(2^n)
Space O(2^n)

===========================================================
//Sum of elements of array using recursion

public static void main(String args[]) {


int[] a={1,2,3,4,5,6,7,8,9};
System.out.println(findSum(a,a.length));

}
public static int findSum(int[] a, int n)
{
if(n<=0)
return 0;
return a[n-1] + findSum(a,n-1);
}

//Reverse an array
public static void reverse(int[] arr, int i){

if(i>=arr.length/2)
return;

int temp=arr[i];
arr[i]=arr[arr.length-i-1];
arr[arr.length-i-1]=temp;

reverse(arr,i+1);

}
O(n/2)
O(n/2)

=====================================================================

//check if a string is palindrome


public static boolean checkPalindrome(String st, int i){
if(i>=st.length()/2)
return true;
if(st.charAt(i)==st.charAt(st.length()-i-1))
return checkPalindrome(st,i+1);
else
return false;
}
O(n/2)
O(n/2)

=================================================================================

// saydigits - love babbar


public static void main(String args[]) {
sayDigit(12045);

}
public static void sayDigit(int n)
{
if(n>9)
sayDigit(n/10);

String st="";

switch(n%10)
{
case 0 : st="zero";break;
case 1 : st="one";break;
case 2 : st="two";break;
case 3 : st="three";break;
case 4 : st="four";break;
case 5 : st="five";break;
case 6 : st="six";break;
case 7 : st="seven";break;
case 8 : st="eight";break;
case 9 : st="nine";
}
System.out.print(st+" ");
}

===============================================================

// check if a string is sorted or not


public static void main(String args[]) {
int[] a={1,2,3,5,7,9,11};
System.out.println(sortCheck(a,a.length));

}
public static boolean sortCheck(int[] a, int n){

if(n<2)
return true;

if(a[n-1]<a[n-2])
return false;
return sortCheck(a,n-1);
}

===============================================================

// lsearch using recursion


public static void main(String args[]) {
int[] a={1,2,3,5,7,9,11};
System.out.println(lsearch(a,1,0));

}
public static int lsearch(int[] a, int val, int i)
{
if(i==a.length)
return -1;

if(val==a[i])
return i;

return lsearch(a,val,i+1);
}

===================================================================
// Binary search using recursion

public static void main(String args[])


{
int[] a={1,2,3,5,7,9,11};
System.out.println(binarySearch(a, 0, a.length - 1, 9));

}
public static int binarySearch(int a[], int l, int r, int x)
{
if(r>=l)
{
int mid = l + (r - l) / 2;
if (a[mid] == x)
return mid;
if (a[mid] > x)
return binarySearch(a, l, mid - 1, x);
return binarySearch(a, mid + 1, r, x);
}
return -1;
}

===============================================================
// Get Stair Path - 0 to Nth or Nth to 0; - Pepcoding

import java.util.*;
public class MyClass {
public static void main(String args[])
{
int n = 6;
StringBuilder ds = new StringBuilder();
List<String> ans = new ArrayList<>();
help(n, ds, ans);
System.out.println(ans);
}
public static void help(int remSteps, StringBuilder ds, List<String> ans)
{
if(remSteps == 0)
{
ans.add(ds.toString());
return;
}
if(remSteps < 0)
return;

ds.append(1);
help(remSteps-1, ds, ans);
ds.deleteCharAt(ds.length()-1);

ds.append(2);
help(remSteps-2, ds, ans);
ds.deleteCharAt(ds.length()-1);

ds.append(3);
help(remSteps-3, ds, ans);
ds.deleteCharAt(ds.length()-1);
}
}
===================================================================================
====================

===================================================================================
==========================

// Count stair paths 0 to N th or Nth to 0 - leetcode 70

class Solution {
public int climbStairs(int n) {

if(n==1 || n==2)
return n;

return climbStairs(n-1) + climbStairs(n-2);


}
}

===================================================================================
=====================

// Letter combination of a phone number leetcode 17

class Solution
{
public List<String> letterCombinations(String digits)
{
List<String> result = new ArrayList<>();
if (digits.isEmpty()) return result;

Map<Character, String> map = new HashMap<>();


map.put('2', "abc");
map.put('3', "def");
map.put('4', "ghi");
map.put('5', "jkl");
map.put('6', "mno");
map.put('7', "pqrs");
map.put('8', "tuv");
map.put('9', "wxyz");

StringBuilder currentCombination = new StringBuilder();


backtrack(digits, 0, map, currentCombination, result);

return result;
}

private void backtrack(String digits, int index, Map<Character, String> map,


StringBuilder currentCombination, List<String> result)
{
if (index == digits.length())
{
result.add(currentCombination.toString());
return;
}

char digit = digits.charAt(index);


String letters = map.get(digit);
for(int i=0;i<letters.length();i++)
{
char k = letters.charAt(i);
currentCombination.append(k);
backtrack(digits, index + 1, map, currentCombination, result);
currentCombination.deleteCharAt(currentCombination.length() - 1); //
Backtrack by removing the last letter added
}
}
}

OR

// gfg - possible words from phone digits

class Solution
{
//Function to find list of all words possible by pressing given numbers.
static ArrayList <String> possibleWords(int a[], int N)
{
ArrayList<String> result = new ArrayList<>();

Map<Integer,String> map = new HashMap<>();


map.put(2,"abc");
map.put(3,"def");
map.put(4,"ghi");
map.put(5,"jkl");
map.put(6,"mno");
map.put(7,"pqrs");
map.put(8,"tuv");
map.put(9,"wxyz");

StringBuilder cc = new StringBuilder();


backtrack(a, 0, cc, map, result);

return result;

}
public static void backtrack(int[] a, int index, StringBuilder cc,
Map<Integer,String> map, ArrayList<String> result)
{
if(index == a.length)
{
result.add(cc.toString());
return;
}

String letters = map.get(a[index]);

for(int i=0; i<letters.length(); i++)


{
char k = letters.charAt(i);
cc.append(k);
backtrack(a, index+1, cc, map, result);
cc.deleteCharAt(cc.length()-1);
}
}
}

You might also like