Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Can 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.


Perhaps 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.


One 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;
    }


It’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.


min + (max - min) / 2

Edit: never mind, this can overflow too


Fortunately 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.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: