This is one of the classics, and yeah, I've gotten this one too. But this one's a gimme since it's so simple and you really are just expected to have heard it. Someone at Microsoft asked me this one and I considered it a massive gift. I thought for a few moments, articulated the solution, and then wrote the code. Then I said, "of course, everyone's heard this one before; I didn't just come up with that on the spot." (you may as well wait to admit this at the end instead of the beginning since you then get an open-ended amount of time to give a stellar answer to what they asked, then you get honesty credit for admitting you knew it all along, plus you've eaten up time that they might have used to switch questions on you).
There are much worse ones on leetcode, and people expecting you to get the optimal solution are absurd. I fully expect to fail those unless I'm lucky. I don't study leetcode problems, because my interview approach is to first and foremost, implement a naive (aka slow) but correct solution in the time allotted, then engage in a conversation about ideas for improving it (not a rewrite). This has worked for me for decades, and it's also what I expect of people I'm interviewing.
This type of approach allows the interviewee to demonstrate that 1) they can write basic code, 2) they can solve a problem, 3) they can critique their own code and discuss perf implications, 4) they can think of ways to improve it even if they don't necessarily have time for a rewrite, and it allows the interviewer to demonstrate that they aren't a dick who's just playing "I'm smarter than you because I'm in the advantaged position."
There are much worse ones on leetcode, and people expecting you to get the optimal solution are absurd. I fully expect to fail those unless I'm lucky. I don't study leetcode problems, because my interview approach is to first and foremost, implement a naive (aka slow) but correct solution in the time allotted, then engage in a conversation about ideas for improving it (not a rewrite). This has worked for me for decades, and it's also what I expect of people I'm interviewing.
This type of approach allows the interviewee to demonstrate that 1) they can write basic code, 2) they can solve a problem, 3) they can critique their own code and discuss perf implications, 4) they can think of ways to improve it even if they don't necessarily have time for a rewrite, and it allows the interviewer to demonstrate that they aren't a dick who's just playing "I'm smarter than you because I'm in the advantaged position."