In: Computer Science
what is the time complexity of those ?
//TODO - Question 18
public static int[][] fillRandomArray4(int n) {
int[][] arr = new int[n][n];
for(int i = 0; i < arr.length;
i++) {
arr[i] = new
int[] {(int)(Math.random() * 101),
(int)(Math.random() *
101),
(int)(Math.random() *
101)};
}
return arr;
}
//TODO - Question 19
public static int factorial(int n) {
if(n == 1 || n == 0) {
return 1;
}
return n * factorial(n-1);
}
//TODO - Question 20 - assume str.length() == n
public static boolean isPalindrome(String str) {
if(str.length() == 0 ||
str.length() == 1) {
return
true;
}
if(str.charAt(0) !=
str.charAt(str.length()-1)) {
return
false;
} else {
return
isPalindrome(str.substring(1,str.length()-1));
}
}
thanks for the questions.
=============================================================
Question 18
In this method, we are running a for loop n times which is
passed to this method as an argument,
there is only 1 for loop without any inner loops, hence the code
inside the for loop will run
n times (arr.length will return n)
So the time complexity will be linear and of order O(n)
=============================================================
Question 19
The method finds the factorial of a number, the function
recursively calls itself until the value of n
is 1 or 0, in every call the value of n is decremented by 1, so the
number of method call will be equal
to the value of n.
So the time complexity will be linear and of order O(n)
=============================================================
Question 20
The method finds if a string is palindrome, in every
recursive call the length of the string is reduced by 2
that is the first character and last character are removed and the
substring is passed as an argument in the
next recursive call.
The total iterations will be for a string of length n is n/2.
So the time complexity will be linear and of order O(n/2) or simply O(n)
=============================================================