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

8

u/iqtestsmeannothing May 09 '15

Almost all non-brute force solutions posted here fails.

Right, and I've not seen a single person try to prove that their non-brute-force solution is correct. (I've tried to make such a proof and failed.) This problem is way harder than the others, and the author really cocked up by including this problem, with an incorrect solution and no attempt at a proof, on a list of "ridiculously simple" problems.

1

u/myxie May 12 '15

I have a really simple solution, just sorting with a given comparison operator. It relies only on one thing, that the empty string is not one of the inputs. Well, numbers are never written as the empty string.

To prove the solution correct, the pairwise comparisons need to imply a global ordering. So the comparison needs to give an equivalence relation on non-empty strings (easy) and a total order on the equivalence classes (I've not found a simple proof).

compare(a, b) = string_compare(ab, ba)

Proofs welcome.

1

u/iqtestsmeannothing May 12 '15

Well, it took me 10 minutes to show that it is an equivalence relation on non-empty strings, but I found it easier to prove (by induction) that it is a total order on equivalence classes. How does this help us show that the algorithm is correct?

(Basic idea of the proof is to show that if compare(A, B) = compare (A * n, B), then compare(A, B) = compare(A * (n + 1), B), and induct on n, where * is the string repeat operator.)

1

u/myxie May 12 '15 edited May 12 '15

It tells us that if we sort the numbers using that ordering then we will have a well-defined total order, unique up to runs of equivalent items. Equivalent items p and q satisfy pq = qp, so reordering them (any permutation decomposing into a combination of swaps) makes no difference to the resulting number.

Suppose we have a maximal (and clearly at least one exists) ordering of numbers x1, x2, ..., xn, then it follows that xi x(i+1) >= x(i+1) xi. Ignoring equivalent items, the sorting method finds the unique such sequence, therefore it is the maximal one.

→ More replies (5)