This question I've received during interview. My answer is O(1), is it correct?
Asked
Active
Viewed 515 times
1
-
This depends on the implementation. – Oct 28 '11 at 18:47
-
what interview is this for, college professor? I haven't used those terms since I graduated college almost 20 years ago – Rodolfo Oct 28 '11 at 18:47
-
In one social network company )) (no fb) – NiLL Oct 28 '11 at 18:48
-
1This was answered here: http://stackoverflow.com/questions/5292325/algorithmic-complexity-of-php-function-strlen – Jonathan M Oct 28 '11 at 18:48
-
Voting to close as a duplicate of [Algorithmic complexity of PHP function strlen()](https://stackoverflow.com/questions/5292325/algorithmic-complexity-of-php-function-strlen) – Mark Amery Oct 12 '17 at 14:57
1 Answers
2
If strlen counts each character in the string, then it's O(n). If the String class holds a length in some private variable, then it's O(1).

Mike Christensen
- 88,082
- 50
- 208
- 326
-
-
And if the designers of PHP wanted to be uncool about it, they could make it have any complexity at all. Kind of a strange, memorization-based question to ask. – Patrick87 Oct 28 '11 at 18:47
-
@Patrick87 strlen can't have "no complexity". Usually it is either O(1) or O(n), n being the number of characters. It can be even O(n!) or O(∞), but such strlen algorithms are never used in practice. – Oct 28 '11 at 18:49
-
@WTP: Not sure that I said it could have "no complexity"... just that it could have any complexity, as you illustrate. When we say that an integer variable can have any of the values between 1 and 10, we typically mean that it must have one of them... sort of implicit. And whether or not inefficient strlen() implementations are used in practice is an empirical question; to answer it, you'd need (in this instance) to actually check the PHP implementation... unless you assume viable programming languages use efficient implementations, which - however reasonable - represents a leap of faith. – Patrick87 Oct 28 '11 at 18:58
-
@Patrick87 sorry, I misunderstood your first comment. I read "make it have **no** complexity at all." – Oct 28 '11 at 19:00