The method hasTwoTrueValues
return true
if at least two values in an array of boolean
are true
. Provide the Big-O running time for all three implementations proposed.
// Version 1
public boolean hasTwoTrueValues(boolean[] arr) {
int count = 0;
for(int i = 0; i < arr.length; i++)
if(arr[i])
count++;
return count >= 2;
}
// Version 2
public boolean hasTwoTrueValues(boolean[] arr) {
for(int i = 0; i < arr.length; i++)
for(int j = i + 1; j < arr.length; j++ )
if(arr[i] && arr[j])
return true;
}
// Version 3
public boolean hasTwoTrueValues(boolean[] arr) {
for(int i = 0; i < arr.length; i++)
if(arr[i])
for(int j = i + 1; j < arr.length; j++)
if(arr[j])
return true;
return false;
}
These are my answers:
O(n)
O(n^2)
O(n^2)
I am really new to this Big-O Notation so I need guidance if my answers are correct/incorrect. If I'm wrong, could you please explain and help me to learn?
Version 1 is pretty straightforward and runs linear, so the runtime of that is O(n) on average.
Version 2 is a bit more interesting. It runs with n(n-1) on average, which is O(n2). There's an early return
in this loop, so it's definitely possible that it could break as early as the first two elements.
Version 3 is trickier. You have to be careful on this. The second loop will only run if arr[i]
is true
. The runtime of it has to be put into distinct categories then.
It's safe to say then that the average and worst runtime for Version 3 will be O(n2). Its best would be O(n), which is definitely possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With