Suppose we have the following problem along with a java method that can help.
A user enters passwords between 5 characters and 35 characters long inclusive. We need to make sure they don't repeat the same char 3 times in a row.
boolean has3CharsInARow(char [] password){
for(int left=0, middle=1, right=2; right < password.length; left++, middle++, right++){
if(password[left]==password[middle] && password[middle]==password[right]){
return true;
}
}
return false;
}
What is the time complexity (For simplicity assume Big O notation and worst case scenario)?
My thoughts are we don't know where the 3 chars occur in the password so we have to search all appropriate chars to be sure. But I am struggling to classify it as O(1) or O(n) for n chars.
What is the argument for O(1)? Well given the context, we know there are constraints on the password it can at most be 35 characters long. So in the worst case we don't find 3 repeating chars we scan O(34) 33 for right indices 2 through 34 and 1 more for when right is 35 and then we exit the guard of the loop and finally return false. Since 34 is a constant, in general we say O(34) = O(1) which is constant time complexity.
What is the argument for O(n)? Well we care about how the time efficiency of the function behaves as it's input length grows. If we suppose that T(n) is the running time of has3CharsInARow, we can say T grows linearly proportional for every unit or char increase in the password length. So T is in the class of functions O(n).
Where do we draw the line between O(1) and O(n)?
Edit: Since one answerer has wrote O(n) then does that mean this equivalent method is O(n) too?
boolean has3CharsInARow(char [] password){
switch(password.length){
case 0:
case 1:
case 2:
return false;
case 3: return password[0] == password[1] && password[1] == password[2];
case 4: return password[0] == password[1] && password[1] == password[2] ||
password[1] == password[2] && password[2] == password[3];
...
case 35: return ...;
}
}