| >>Then declare a new array and iterate through the string backwards, appending each character to the new array. When you're done, collapse the array to a string. a. You can't iterate a 'String' backwards. You need to know the length first. And that requires traversing the string forwards at least once. b. Once you reach the end you are wasting the effort of revisiting the elements, since you visited them already once. c. A better option is build a build a double linked list, as you are traversing the list forward. d. Once you have the double linked list ready, you have pointers to both start and end, and you traverse the way you like. e. An even better way would be to design a data structure that contains all this meta data at String creation itself. Class CustomString {
char* headPointer;
char* tailPointer;
int length;
bool isPalindrome;
char* string;
/* Add your interview acrobatic things here */
}
Stuff like this.Now even though the answer in your comment is correct, they could reject you for not coming up with the answers I gave from point a through e above. Now imagine some one telling you that, on these grounds, you don't know a semicolon worth programming and are probably a liar. I hope you understand what's going on here. Every body can be rejected if they don't cut through your cookie cutter. |
That's not at all true in many languages. If a candidate asked "is this string's length known without an O(N) operation on the number of characters in it?" (or knew the answer for the default string constructs in the language they were using for the problem) I'd consider that a positive indicator. If they said what you just said, without consideration for the context, I'd consider that a negative.
This is not a case of someone expecting a given "cookie cutter" solution. Interviewers who do that are doing themselves and their candidates a disservice. This is a case where statements like "I know how strings work because I know how they work in $context" where $context is not what the interview expects you to work in will make a bad impression.