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

2

u/arocketman May 08 '15

This is how I solved the first 4 problems in Java. Fifth one is ... not that easy really :/ .

https://gist.github.com/arocketman/8c4bb3415aec97176e48

1

u/jpapon May 08 '15

The fifth one isn't too hard, just think of it as a graph. Each edge can be either "connect", +, or -. Starting with 1, you build a graph with the integers as nodes, and each node having all three edge possibilities connecting it to a node with the next integer.

Finding all possible paths in the graph that sum to 100 is easy using an exhaustive recursive search. The full graph is a tree with ~30k nodes, which isn't that bad really, especially since it's a very wide tree - the max path length is just 9.

1

u/grimskin May 08 '15

Brute-forcing will give you only 6.5K combinations to check with much less memory usage.

1

u/jpapon May 08 '15

Brute forcing it? Isn't that an exhaustive search of the graph?

I think what you're calling "brute force" is a depth first search of the graph, and the only way I can see of doing much better is a dynamic programming solution, but it's going to be much more complicated.

The graph is a tree with ~30k nodes, depth of 9, and max number of edges per node of 3. 6.5k paths seems reasonable.

1

u/grimskin May 12 '15

Here's what I've meant.

Think about combination of operands and spaces like the 8-digit number in number system based on 3. You'll just need a routine that evaluates f(combinationNumber, [1..9]) and a cycle that walks combinationNumber from 00000000 to 22222222 calculating f() on each iteration, thats all and no need to keep graph with ~30k nodes in memory.

p.s. sorry for my crappy English, it's my second language, but I hope you'll understand what I mean.

1

u/jpapon May 12 '15

There's no need to keep the full graph in memory - and even if you did, 30k nodes is not all that much.

But yes, your point is well taken. Base-3 counting gives you all paths in the graph, so there's no need to use the graph at all =)