7 ms·
People rarely come up with a working solution within 30 minutes. Any solution is good as long as it doesn't overflow (there are a few suboptimal ones). But the
by mojuba 4y ago
People rarely come up with a working solution within 30 minutes. Any solution is good as long as it doesn't overflow (there are a few suboptimal ones). But the point of this question is, again, to understand what they know about how the computers work.
- angrais 4y agoWhat sort of role is it for? I'm asking as I doubt "know about how computers work" is necessary for most tech roles. I get it, having technical expertise is important, but still ...
- DenisM 4y agoCan you provide an example of a solution that someone without prior exposure could come up under 30 minutes? I'm having a hard time coming up with something that is not a monstrocity full of if s.
- ErikCorry 4y agoPerhaps the bar is not as high as you think. Coming up with a solution that has lots of ifs in will still put you at the high end of the interview distribution. Discussing intelligently with the interviewer why it's not great and how it can be improved is a lot better than not coming up with an answer at all.
- baobabKoodaa 4y agomin + (max - min) / 2 Edit: never mind, this can overflow too
- stephencanon 4y agoFortunately the cases where this might overflow (a and b have opposite sign) are precisely the cases where the naive (a+b)/2 is guaranteed to work. So put them together to get a suboptimal but perfectly fine solution.
- mojuba 4y agoOne of the solutions I came up with back in the day, without googling was this: int avg(int a, int b) { if ((a < 0) != (b < 0)) // not the same sign? return (a + b) / 2; else return a + (b - a) / 2; }
- DenisM 4y agoIt’s tricky. This will round (-2,-1) to -2, i.e. away from zero. For comparison, if we perform the canonical (a+b)/2 instead it will round to -1, i.e. towards zero. Now, the problem statement does not tell us how to round, so you’re technically correct, but the inconsistency bothers me.