Why do the first two Java implementations to print the string ‘n’ times result in a stack overflow
error when ‘n’ is large (e.g., 10^4)
, whereas the third implementation does not encounter this issue?
First Snippet –
import java.util.ArrayList;
import java.util.List;
public class Solution {
static void print(int count, ArrayList<String> list){
if(count < 1){
return;
}
list.add("Coding Ninjas" + " ");
count--;
print(count, list);
}
public static List<String> printNtimes(int n){
// Write your code here.
ArrayList<String> list = new ArrayList<String>();
print(n, list);
return list;
}
}
Second Snippet –
import java.util.ArrayList;
import java.util.List;
public class Solution {
static List<String> print(int count, ArrayList<String> list){
if(count == 0){
return list;
}
list.add("Coding Ninjas" + " ");
count--;
return print(count, list);
}
public static List<String> printNtimes(int n){
// Write your code here.
ArrayList<String> list = new ArrayList<String>();
return print(n, list);
}
}
Third Snippet –
import java.util.ArrayList;
import java.util.List;
public class Solution {
static List<String> print(List<String> list, String str, int n){
if(n == 0){
return list;
}
list.add(str);
return print(list, str, n - 1);
}
public static List<String> printNtimes(int n){
// Write your code here.
ArrayList<String> list = new ArrayList<>();
String str = "Coding Ninjas ";
return print(list, str, n);
}
}
I’m not able to figure out why this is happening because all of the three different codes are doing the same thing. I’m trying to solve this problem with O(n) Time Complexity. Anyone can help me to figure out why the third snippet is not giving the stackoverflow error ?
Hitesh Kumar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.