19

Recently I was asked this question on interview and I didn't know how to answer it.

Can anyone answer this question and describe it?

2 Answers 2

26

O(1) since the length is stored as an attribute: source

However, this trivia is worth countering with a discussion about micro-optimising theatre, as kindly provided by our hosts here and here; read those two links and you'll find a good talking point to change the momentum of the conversation next time similar questions come up, regardless of whether you know the particular answer!

How the interviewer reacts to your tangent will tell you a lot about how much you want to work with them..

Sign up to request clarification or add additional context in comments.

8 Comments

Thank you. Could you give some more similar articles to read? What about interviewer - he was looking for developer with much stronger qualification than I have and this question was not "just for fun". But it gave me better knowledge about my skill weaknesses.
+1 for "micro-optimization theater." Profile, profile, profile!
The interviewer was likely reading a prepared list of questions? Even at Google. The sooner you take them off the track the better.
I don't see where your source mentions that string length is stored as an attribute.
Comparing one O(n) string concatenation implementation vs. some other O(n) string concatenation implementation is probably micro-optimization theater. Knowing whether strlen is O(1) or O(n) can have a huge impact; just look at how sscanf's unexpected O(n) implementation led to O(n^2) parsing.
|
0

I would assume that function is O(n) because it would need to iterate through the string once.

2 Comments

And why would it need to do that? You're assuming it's stored as an array of chars with no additional information.
Because that is the right answer, it will obviously not be quadratic and worse than linear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.