My programming exam (Bachelor Mathematics, we get one semester of programming) is coming up, and i managed to get my hands on the exam of two years ago. One of the questions is troubling me:
You get this code:
public static void Simuleer1()
{
String bs = "Hello world!";
int max = -1;
char let = '*';
int counter = 0;
for (int i=0;i<bs.length();i++) {
int tel = 1;
for (int j=i+1;j<bs.length();j++) {
if (bs.charAt(j) == bs.charAt(i)) tel++;
}
if (tel > max) {
max = tel;
let = bs.charAt(i);
}
}
System.out.println(max + " times " + let);
}
(Any possible mistakes in there are due to mistranslations on my part)So, practically we have a code telling us which character is found most in a String. If two chars are found equally often, the one that first appears gets shown.
Questions are:
1) What will the output be for the given string?
Well, that's a piece of cake, of course.
2) What is the time complexity (not sure if i translated this correctly) of this code?
Since we're using a for-loop in a for-loop, i personally think it's quadratic / O(n²); although that since the innermost loop keeps getting shorter, it may be linear*logarithmic / O(n log n) ?
3) Can we reduce the time complexity of this code, and if so, how?
Well, since there's no "and if not, ..." in the question, i'll assume the answer is yes. I've though about a few ways to shorten the second loop, but nothing to get to a linear / O(n) or logarithmic / O(log n) time complexity.
Any help is appreciated!
Thanks in advance! :D


Sign In
Create Account

Back to top









