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

I did a phone interview once for Facebook and my interviewer used binary search of an array of integers. I think it is a good thing to use for a first filter because even if you don't know it from memory it is pretty obvious from first principles, and it involves both looping (or recursion) and branching and it is only 10 lines of code. Also there are a few twists you can apply afterwards:

1. Turn it into bisect: return the index at which the searched value should be inserted to maintain the sorted list.

2. Allow any type of array member and require a comparison function provided that returns the standard -1,0,1.

3. Point out that binary search can be used for membership testing with O(log(n)) comparisons where n is array length. Then ask for a data-structure that can perform membership testing in constant time (answer: hash table.)

EDIT: the actual programming was in a shared buffer (something like etherpad). I was mock-interviewing a friend and I had him do it on paper and that worked alright too.

EDIT2: The hardest part about discussing FizzBuzz is avoiding derailing the discussion into FizzBuzz code golf.

  #!/usr/bin/env python
  for i in range(1,101):
    print [i,"Fizz","Buzz","FizzBuzz"][(0==i%3)+2*(0==i%5)]


>The hardest part about discussing FizzBuzz is avoiding derailing the discussion into FizzBuzz code golf.

Well, since we're going there... have some JavaScript again!

  for(var i=0;i++<100;console.log(((i%3?'':'Fizz')+(i%5?'':'Buzz'))||i));
In the spirit of http://140byt.es I also condensed my pyramatrix function (though without the visualization) to 135 characters:

  function(a){a=a|1;var b=[],c=a>>1,d=Math.abs,e=0,f;for(;e<a;e++)for(b[e]=[],f=0;f<a;f++)b[e][f]=1+c-d(d(c-e)>d(c-f)?c-e:c-f);;return b}
And to get the same visualization as in the original version, you can use this helper function:

  function(a){var b=a.length,c='',d=0,e;for(;d<b;d++){for(e=0;e<b;)c+='['+a[d][e++]+']';c+='\n'}console.log(c)}
Assign those to say, pyramatrix and visualize and you can call visualize(pyramatrix(n)) and get the same pretty output!


1 line longer, but extensible.

  #!/usr/bin/env python
  rules = {3:'fizz, 5:'buzz'}
  for n in xrange(1, 101):
    print ''.join(n%x is 0 and rules[x] or '' for x in rules) or n


#include <stdio.h>

void main(){for(int i=1;i<=100;i++)printf(i%3&&i%5?"%d\n":"%szz\n",i%3?(i%5?i:"Bu"):i%5?"Fi":"FizzBu");}

;)




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

Search: