by timmg · 6mo ago · 0 comments
The only one I remember was to check if two strings were equal (in C). I wrote (maybe buggy) code to iterate both pointers, comparing while looking for the null terminator.
The interviewer stopped me and said, “You should compare their lengths first. If they are different, you can exit early.”
I was pretty young and didn’t know much, but I explained, “But you have to look for the terminator to find length so it’ll take twice as long.”
He snapped, “There are optimized functions for that!”
I assumed he was right. Needless to say, I didn’t get the job.
Maaaany years later, I realized the std library was probably open source. So I checked (one). It was nice to be vindicated :D
NUL-terminated strings don't know their lengths and so, without an "n" variant function and running strlen() ahead-of-time, must iterate the entire thing. Pascal format strings (supported up to 255 byte lengths in the classic form) could find length as an O(1) operation because there was no terminator necessarily.
Snapping with know-it-all arrogance is toxic and doesn't help anyone. You were correct because strcmp has to iterate both strings, just like strlen would.. and it's totally pointless.
#include <string.h>
/* C89 and handles NULL and overlapping strings */
int strequal(const char *a, const char *b) {
return (a == b || (a != NULL && b != NULL && strcmp(a, b) == 0));
}
I think you dodged several bullets by not getting hired there because they sounded insufferable.