r/programming • • May 08 '15

Five programming problems every Software Engineer should be able to solve in less than 1 hour

https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour
2.5k Upvotes

2.1k comments sorted by

View all comments

Show parent comments

180

u/youre_a_firework May 08 '15

#5 is probably NP hard since it's kinda similar to the subset-sum problem. So there's probably no way to do it that's both simple and efficient.

161

u/Oberheimz May 08 '15

I actually went ahead and tried solving them, it took me 42 minutes to write a solution for the first 4 problems and I was unable to finish the fifth within one hour.. Am I a bad software engineer?

378

u/mariox19 May 08 '15

If it's on the Internet, it must be true. Every good software engineer knows that.

→ More replies (2)

100

u/gizzardgullet May 08 '15

Now you write your own quiz based on logic tricks that you are comfortable with and challenge the author complete your quiz in an hour.

→ More replies (6)

29

u/akshay2000 May 08 '15

Nah, you're just fine. It's the implementation that took time. The hour criteria is rough since one might just go on and on.

→ More replies (2)

16

u/ours May 08 '15 edited May 08 '15

Are you able to solve the problems that present themselves at work? If so, then no you are not a bad engineer.

Edit: if(solvesProblems) not if(!solvesProblems)

4

u/Oberheimz May 08 '15

Well, of course, wouldn't have a job otherwise ;)

11

u/ours May 08 '15

of course

I've worked with enough people to learn that sadly some that can't/don't want to code can coast surprisingly long in a sufficiently shitty environment.

Best one was a new hire who was supposed to be my senior ask me the most basic question about how to make a "if" condition. I chalked it of to one of those "doh I forgot something super basic" that can happen to any of us.

They realised the dude didn't know how to code at all only because I left for a month-long sabbatical and noticed nothing was done during my absence.

→ More replies (2)

11

u/Dakarius May 08 '15

You're looking at it the wrong way. It takes 5 hours to do 5 problems. You got the first 4 knocked out in 42 minutes leaving you 4 hours and 18 minutes for the last. You've still got 3 hours and 18 minutes left!

6

u/s-mores May 08 '15

Did you just write code to solve them, or put the code in action and tested it?

The only one I tested out was #4 and some syntax parts of #5. Since this is an interview question, it should mostly be measuring the approach and that you know how to do something or at least have some idea how to approach the problem instead of the actual result, which is pretty uninteresting, and in the case of #1-#4, trivial.

I mean, I'm not going to use 5-10 minutes per task in figuring out where I'm missing a semicolon, or where I've misremembered argument order and the code would fail because of that, that's what the compiler is for.

4

u/secondchimp May 08 '15

It's ok, the author's first solution to the 4th problem was incorrect.

→ More replies (26)

25

u/[deleted] May 08 '15 edited May 08 '15

In prolog #5 looks something like this:

sum([Head|Tail],Signs,Result):-sum(Head,Tail,Signs,Result).

sum(X,[],[],X).

sum(First,[Second|Tail],['+'|Signs],Result):-Head is First + Second, sum(Head,Tail,Signs,Result).

sum(First,[Second|Tail],['-'|Signs],Result):-Head is First - Second, sum(Head,Tail,Signs,Result).

sum(First,[Second|Tail],[''|Signs],Result):-Head is First*10 + Second, sum(Head,Tail,Signs,Result).

sum(First,[Second|[Third|Tail]],['+'|[''|Signs]],Result):- C is Second*10+Third, Head is First + C, sum(Head,Tail,Signs,Result).

sum(First,[Second|[Third|Tail]],['-'|[''|Signs]],Result):-C is Second*10+Third, Head is First - C, sum(Head,Tail,Signs,Result).

edit: minor correction as others have pointed out I messed up the grouping slightly. further correction to follow

7

u/eelvex May 08 '15

In J one could solve it with:

L {~ I. 100 = +/"1 L=:([:".'9',~[:;(;/":"0>:i.8),.])"1 ('';',';',_') {~"1 (3&#.)^:_1 i.3^8

6

u/floccinaucin May 09 '15

I've been programming for a couple years now... what the heck am I looking at here?

5

u/eelvex May 09 '15

It's J, an array, functional-level tacit language. It's really cool and makes you think in completely new ways because a) you'll be thinking in array transformations [especially instead of loops] and b) you'll avoid variables.

For example, where in C you write y = function1(function2(x), function3(x)) in J you write y =: (function2 function1 function3) x

→ More replies (17)

23

u/whydoismellbacon May 08 '15

What you could do is create a 3 state class that represents the points between the digits. 1 would be add (+), 2 minus (-), and 3 append/group. Then you have a recursive function that tries every combination and the moment it gets above 100 it returns 0 (or if it adds to 100 it prints the combination that works on a new line).

Definitely possible, however it would probably take the whole hour (or more) to complete.

42

u/gryftir May 08 '15 edited May 08 '15

It's still possible that a number is above 100 before the end of the digits can still work.

example 123 - 4 - 5 - 6 - 7 + 8 - 9

You could however test that a number is either greater then 100 or less than 100 by the remaining combined digits. that said, it's 38 possibilities, so 81 * 81 so 6561 options, of which you can eliminate a number with the test function.

→ More replies (4)

28

u/WeAreAllApes May 08 '15 edited May 08 '15

It takes a few minutes if you approach it this way.

Edit:updated to point to the working version... also note that it runs in a split second because 6561 iterations is not that much for a computer these days.

8

u/[deleted] May 08 '15

c = Math.floor(c / 3);

I feel like I should intuitively know why this works, but it still feels like magic.

→ More replies (5)
→ More replies (4)

28

u/AcidDrinker May 08 '15

This wouldn't work. If the sum goes above 100, I can still subtract and get my desired answer to 100.

Eg:

(1+23-4+5+6+78)-9
(109)-9  
//Your program returns 0 because sum exceeded 100, but the solution is correct.

37

u/youre_a_firework May 08 '15

Yeah, that's the "simple" and not "efficient" solution. :)

96

u/nkorslund May 08 '15 edited May 08 '15

Um no the simple solution is just try all 3**8 = 6561 possibilities. Which should run in tenths of a second (at most) on any modern hardware.

→ More replies (23)
→ More replies (2)

15

u/kinmix May 08 '15 edited May 08 '15

I think one could approach it dynamically. You can start building a tree of different subsets with all possible values in it's nodes. In this case in order to compute the next node you will not have to recalculate all the previous ones. Once done all you have to go is to go depth first down the 100 branch and print out the results.

And you can't just stop and return 0 once it goes over 100. what if you get to 109 and you put a - before the 9 at the end or -89.

EDIT: Here's my solution. Runs in 20ms but requires around 48MB of RAM. And no trees needed because we only ever go 1 level deep so two arrays do the trick. I don't think you can do any better.

<?php
ini_set('memory_limit','48M');

$values = [2,3,4,5,6,7,8,9];

$results = [['string'=>'1', 'value'=>1, 'prevNumber'=>1, 'prevSign'=>1]];
$newResults = [];

foreach ($values as $value){
    $newResults = [];
    foreach ($results as $result){
        $newResults[]=[
			'string'=>$result['string'].'+'.$value, 
			'value'=>$result['value']+$value, 
			'prevNumber'=>$value, 
			'prevSign'=>1
		];
        $newResults[]=[
			'string'=>$result['string'].'-'.$value, 
			'value'=>$result['value']-$value, 
			'prevNumber'=>$value, 
			'prevSign'=>-1
		];

        $newResults[]=[
			'string'=>$result['string'].$value, 
			'value'=>$result['value']
						-($result['prevSign']*$result['prevNumber'])
						+($result['prevSign']*(($result['prevNumber']*10)+$value)), 
			'prevNumber'=>($result['prevNumber']*10)+$value, 
			'prevSign'=>$result['prevSign']
		];

    }
    $results = $newResults;
}

foreach ($results as $result){
    if ($result['value']==100)
        echo $result['string']."\n";
}

A quick explanation: for every value I go through all current results and shove this value at the end. with plus, minus and without a sign. do it for all the values and at the end I just look trough all results and output those which has value of 100.

So initially my result just consists of [1]. I'm getting new value "2". so now I have 3 results: [1+2, 1-2, 12]. I log both strings as well as actual result values [3, -2, 12] so I don't need to go back and re-evaluate. It is easy to just add and subtract things. However in order to "append" a number (without re-evaluating the whole expression from scratch) I need to know the previous number and previous sign. if it was a + I can just subtract the previous number and then add (old number * 10 + new number). same thing happens with -.

The thing that makes this algorithm faster then brute-force is that we never recalculate things we already calculated before. Dynamic Programming rules!

Aaand I had a bug in a code. Fixed it now, proper results:

1+2+3-4+5+6+78+9
1+2+34-5+67-8+9
1+23-4+5+6+78-9
1+23-4+56+7+8+9
12+3+4+5-6-7+89
12+3-4+5+67+8+9
12-3-4+5-6+7+89
123+4-5+67-89
123+45-67+8-9
123-4-5-6-7+8-9
123-45-67+89
→ More replies (16)

3

u/snkscore May 08 '15

Because you can have subtraction operators, you couldn't exit when you get above 100, the upper limit would need to be dynamic based on how many items are left. You could say -789 for the last one for example.

→ More replies (3)
→ More replies (7)