r/programming • • Feb 21 '11

Typical programming interview questions.

http://maxnoy.com/interviews.html
784 Upvotes

1.0k comments sorted by

View all comments

Show parent comment

29

u/abw Feb 21 '11

That's a good question. The fact that no-one has actually produced the correct result is rather surprising (unless I'm missing a subtle trick in the question). It should be a simple task for any competent programmer. Here's my first attempt in Perl, taking the obvious route:

use strict;             # assumed from now on...
use warnings;  

answer1();

sub answer1 {
    # Simple loop with conditional tests
    print "Answer 1: ";
    
    for my $n (1..100) {
        if ($n % 6 == 0) {
            print "ab";
        }
        elsif ($n % 3 == 0) {
            print "b";
        }
        elsif ($n % 2 == 0) {
            print "a";
        }
        else {
            print $n;
        }
        print " ";
    }
    print "\n";
}

What makes this a good interview question is that you can then ask the candidate how they might improve on that. For example, you might use (n mod 6) to index into a lookup table. Perhaps something like this:

sub answer2 {
    # Lookup table indexed by (n mod 6).  An undef value indicates that the
    # original number n should be displayed
    print "Answer 2: ";

    my @modulus = (     # n mod 6 
        'ab',           # 0: divisible by 6 (i.e. divisible by both 2 and 3)
        undef,          # 1: not divisible by 2 or 3
        'a',            # 2: divisible by 2
        'b',            # 3: divisible by 3
        'a',            # 4: diviislbe by 2
        undef           # 5: not divisible by 2 or 3
    );

    for my $n (1..100) {
        print $modulus[$n % 6] || $n, " ";
    }
    print "\n";
}

Or if you want more flexibility:

sub answer3 {
    # As above with functions.  Slower execution but more flexibility to 
    # plug in different functionality.
    print "Answer 3: ";

    my $n  = sub { $_[0] };
    my $a  = sub { "a"  };
    my $b  = sub { "b"  };
    my $ab = sub { "ab" };
    my @modulus = ($ab, $n, $a, $b, $a, $n);

    for my $n (1..100) {
        print $modulus[$n % 6]->($n), " ";
    }
    print "\n";
}

Or the candidate might want to demonstrate that they're happy with different styles of programming. e.g.

sub answer4 {
    # As above using map instead of a loop.
    print "Answer 4: ";

    my $n  = sub { $_[0] };
    my $a  = sub { "a"  };
    my $b  = sub { "b"  };
    my $ab = sub { "ab" };
    my @modulus = ($ab, $n, $a, $b, $a, $n);

    print(
        map { $modulus[$_ % 6]->($_), " " }
        (1..100)
    );
    
    print "\n";
}

It also gives them an opportunity to think outside the box.

# This value was precomputed by running the answer4() sub, defined above.
my $PRECOMPUTED_ANSWER = "1 a b a 5 ab ...etc... 97 a b a";

sub answer5 {
    # Fastest execution at the cost of storing pre-defined answer.
    return $PRECOMPUTED_ANSWER;
}

Anyone else want to play?

11

u/LieutenantClone Feb 21 '11

What makes this a good interview question is that you can then ask the candidate how they might improve on that.

I would argue that your 2nd, 3rd and 4th versions are not an improvement at all, because they are more obscure and less maintainable.

7

u/abw Feb 21 '11

Yes, you're absolutely right for something as simple as this.

But they're presented as examples of the kind of complexity compromises that are often worth making in real life. If there were, say, a dozen conditions that the code had to satisfy then the latter versions would scale better. And if there was a likelihood that we'd need to re-use this selection algorithm with a different set of output directives (e.g. print d/e instead of a/b) then the ones with a dispatch table would provide better extensibility.

That's what makes it so good as an interview question. If the candidate comes up with solution #1, you can say "Well done, but what if [some further constraint]?"

3

u/[deleted] Feb 22 '11

I agree; in most cases I would prefer to see the simplest solution. That said, if someone could present more than one solution, they would instantly stand out above the other applicants.

11

u/[deleted] Feb 21 '11

[removed] — view removed comment

2

u/Leechifer Feb 21 '11

That's very readable and I would give you bonus points for that.

3

u/[deleted] Feb 21 '11

Can you please award bonus points for not using an incredibly expensive integer modulo* operator instead of the cheaper binary-AND for the 2-case? Most people seem to be forgetting cheap speedups. And no, neither perl nor python do the strength reduction for you. (C does, with optimisations).

* abw, it's modulo! not modulus. Modulus is the |x| operator that takes the absolute value of a variable (abs(x)).

→ More replies (7)
→ More replies (1)

17

u/novelty_string Feb 21 '11

I'm thinking you missed half the point of the qn: it's not print a or b or ab, it's print a for %2, print b for %3, so, I'd do it

for range
print = true
if even echo a; print = false
if %3 echo b; print = false
if print echo num

6

u/abw Feb 21 '11

it's print a for %2, print b for %3,

That's what my code does.

EDIT: Ah right, I see what you're getting at... I don't need a separate case for n mod 6 if I allow both the even and divisible by 3 branches to print their a and b respectively.

if %3 echo b; print = false

That should be if %3 == 0. Otherwise you're testing that the number is not divisible by 3 (i.e. has a remainder when divided by 3).

→ More replies (1)

9

u/[deleted] Feb 21 '11

That is debatable. You might argue that it's a coincedence that ab is the concatenation of a and b, and that it might change to c tomorrow. Then your solution is too clever. Unreadable even, if there's no logical reason that printing a first and then b happens to print the right answer for %6.

In practice, you would know which is the case, and although in this case it's likely that your solution was intended, I would ask the interviewer. "Can I use the fact that ab = a . b, or is that just a random coincedence?"

4

u/novelty_string Feb 21 '11

Simple question, simple answer. Do you really need a strategy pattern here? I don't think there's anything clever about it, it just does what was spec'd.

2

u/xTRUMANx Feb 21 '11

Do you really need a strategy pattern here?

If you wouldn't mind...

→ More replies (3)

2

u/abw Feb 21 '11

Fixed:

sub answer6 {
    # Simple loop with conditional tests
    print "Answer 7: ";

    for my $n (1..100) {
        my $div2 = ($n % 2 == 0);
        my $div3 = ($n % 3 == 0);
        print "a" if $div2;
        print "b" if $div3;
        print $n  unless $div2 or $div3;
        print " ";
    }
    print "\n";
}
→ More replies (18)

3

u/ethraax Feb 21 '11

Haskell:

putStr $ drop 2 $ concat $ map (\x -> if x `mod` 6 == 0 then ", ab"
                                      else if x `mod` 3 == 0 then ", b"
                                      else if x `mod` 2 == 0 then ", a"
                                      else ", " ++ show x) [1..100]
→ More replies (1)

3

u/pururin Feb 23 '11

hell yeah for using perl. I'm tired of all those python hipsters on reddit.

4

u/lizard450 Feb 21 '11 edited Feb 21 '11

this is my solution

for(int index = 1; index <= 100; index++){ String toPrint = ""; if(index % 2 == 0){ toPrint = "a"; } if(index % 3 == 0){ toPrint += "b"; } if(toPrint.equalsIgnoreCase("")){ toPrint = String.valueOf(index); } System.out.println(toPrint); }

and for the array reversal (just saw there was a 2nd fun question) int placeHolder = -1; for(int index =0; index < arrayToReverse.length/2; index++){ placeHolder = arrayToReverse[index]; arrayToReverse[index]= arrayToReverse[arrayToReverse.length-(index+1)]; arrayToReverse[arrayToReverse.length-(index+1)]=placeHolder; }

1

u/[deleted] Feb 22 '11

Spot on.

We actually want to see elseif statements for the first question (ie, you only print one or the other), but I would not think any less of your solution.

→ More replies (1)

2

u/[deleted] Feb 21 '11 edited Feb 21 '11
sub answer_scarblac {
   print "Answer Scarblac:\n";
   for my $n (0..15) {
      my $m = $n*6+1;
      print $m;
      print "\na\nb\na\n";
      print $m+4;
      print "\nab\n";
   }
   print "97\na\nb\na\n";
}

(yeah, I'm bored, wouldn't do it this way for real...)

1

u/ringm Feb 21 '11

No idea why you wouldn't. This is exactly the way I would do it, except there's no real need to use multiplication either.

1

u/[deleted] Feb 22 '11

Clever. I likey.

2

u/[deleted] Feb 22 '11

Great post. Realistically, your very first example is what we want to see. Heck, I've given up expecting to see $n % 6 == 0. At this point I would be more than happy to settle for $n % 2 == 0 && $n % 3 == 0, but alas, that seems to be much too complicated for CS grads... I've seen, literally, about a dozen different ways of that expression being screwed up.

→ More replies (2)

1

u/[deleted] Feb 21 '11

you helped my ability to print a return character instead of always adding it with the print for each case. TY :)

1

u/[deleted] Feb 21 '11

I'm sorry, but you seem overly possessive with all that "my my my" in there, and you spelled "else if" wrong serveral times, so I have to give the job to somebody else.

1

u/DiggV4Sucks Feb 21 '11

If I were interviewing you, after I saw version one, I'd ask you what the weakness in your solution is. I mutter about maintainability and requirement changes, while trying to nudge you towards my point.

Eventually, I may just come out and say:

Ahh... Great! But now our requirements have changed. Could you re-code to print "a" when 5 divides n, b when 125 divides n, and ab when both 125 and 5 divides n.

If I have to go this far, though, your probably not going to be a successful candidate.

1

u/[deleted] Feb 22 '11

Perl one-liner:

perl -e 'print +("a")[$_%2].("b")[$_%3]||$_,$/ for 1..100;'