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

5

u/[deleted] May 08 '15

Write a function that given a list of non negative integers, arranges them such that they form the largest possible number. For example, given [50, 2, 1, 9], the largest formed number is 95021.

Is the solution to this one simply concatenate the numbers in descending order by the first digit (e.g. [9] [5]0 [2] [1]) plus the cases where there are multiple numbers that begin with the same digit, where you would move to the 2nd, 3rd etc digit in that number?

37

u/wgunther May 08 '15

You have to be careful: {9295,92,7} requires the choice 9295 92 7, {9265,92,7} requires the choice 92 9265 7. There's some decision making that needs to happen with ties where one is an initial substring of the other.

45

u/Boojum May 08 '15

Nice. I don't have a proof for this, but I believe that you can determine the proper ordering of any two numbers by concatenating them both ways and then taking the larger of two. Given that, here's my O(n log n) solution in python:

def prob4(l):
    l = map(str, l)
    l.sort(lambda i, j: cmp(j + i, i + j))
    return map(int, l)

Lots of random testing against a brute-force permuting solution has yet to turn up a case where this fails.

5

u/wgunther May 08 '15

Yeah, that seems like a more clever comparison than what I was thinking.

3

u/crashorbit May 08 '15

This is why small problems are sometimes fun to work on. You sometimes stumble on an insight that makes the problem so much easier.

2

u/psymunn May 08 '15 edited May 08 '15

That's a smart observation, and one I believe is correct. First, we can make some observations:

  • The operation is transitive. You can sort you numbers in any order and end with the correct result.

  • 5 and 55 are a tie. Their order doesn't matter, which is indeed true. An unbroken string of numbers can be considered equal. your sort preserves this.

  • 9 or a string of 9s will never be lower than another number. 1 or a string of 1s will never be higher.

  • For a digit starting with 9, we can always sort using the second digit, if there is one. If there's not the 9 is the higher number. So, 9 beats a 9 followed by anthything, and a 97 will beat a 96 but lose to a 98 regardless of following digits. For 1, this is the opposite.

Okay. What about numbers in the middle. Well it starts to emerge that, when the first digit ties, you go to the second digit. If the second digit is greater than the previous digit, the number is considered higher. What about a number missing a digit. Well lets look:

5, 56, 54

It becomes obvious pretty quickly, that 56 beats 5, but 54 loses to it. This will incidentally sort exactly the same way as 55, 56, 54. You can effectively pad your number by adding as many copies of the last digit as needed. 565 will be lower than 56, because 56 will sort the same as 566. repeating the string of numbers over and over. 56 loses to 566, and beats 564 because it's the equivalent of 565.

Your sorting method implicitly obeys all these rules, and rather succinctly!

EDIT: Ugh, I was wrong about the padding. luciusplc has data that shows that that is incorrect. I missorted: 45456, 45, 45452, because I treated 45 as 45555. Treating it as 45454 makes the sorting more obvious. You pad a number by repeating it. so 123 padded to 8 digits will be 12312312.

3

u/Boojum May 08 '15

Yes, it seems like my predicate defines a total order (and therefore is valid in any comparison sort) and I was trying to think before bed last night about how I would prove it. That it's antisymmetric and total is pretty clear, but transitivity is less than obvious, I think.

The string repetition thing is interesting. I think you can show that the two give equivalant results. Basically, if we want to compare XYZ and AB, then with the repetition approach you'd compare

ABABAB...
XYZXYZ...

If A != X then you return the one and you're done. Otherwise, A == X so you can substitute one for the other:

ABXBAB...
XYZAYZ...

Similarly, if B != Y then you're done. Otherwise, B == Y so you can substitute one for the other:

ABXYAB...
XYZABZ...

Now we compare X and Z. If they differ then we're done. Otherwise, X, Z, and A are all equivalent (since earlier we established that X == A). So:

ABXYZB...
XYZABZ...

And now we've got my original comparison between ABXYZ and XYZAB.

Regarding your observation that 5 and 55 are tie, that's actual a special case of a more general class. During random testing, one pair within a list that initially broke my test harness was 8181 and 81. Initially I was checking whether my sort produced the same list as the brute force permutation approach. They differed in the order of those two and so it reported a failure. Easy enough to fix, but an interesting case I hadn't thought of. So the more general rule is that it's a tie when one number repeats the digits of the other some whole number of times.

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

2

u/[deleted] May 08 '15

Nice!! I wrote up a solution in java by sorting it in descending order lexicographically using compareTo(), worked well for a few cases and then I tried yours, it didn't work.

→ More replies (9)

19

u/BlueRenner May 08 '15

I get the feeling a couple of these are deeper than he thinks and could stand substantial mathematical analysis beyond anything available in a 1-hour interview window. In the best case scenario, the interviewer just wants you to take a reasonable shot and be able to explain yourself; in the worst case the interviewer is just looking to show off how smart they are in their pet problem field.

30

u/[deleted] May 08 '15

The first three seemed simple to me. The fourth and fifth struck me as a solid order of magnitude more difficult than the rest.

11

u/thirdegree May 08 '15

The fourth was interesting enough to hold my attention, the fifth was more involved than I was willing to be for an impromptu internet programming challenge.

10

u/erewok May 08 '15

Same here. I looked at the last one and wondered if I really could code a solution in an hour. "Maybe it's not like the others and there's a trick to it?" I wondered.

→ More replies (1)
→ More replies (5)

3

u/entumba May 08 '15

I would just convert these all to strings, run every possible combination through a concatentator, then (INT) all the results and look for the largest. Super easy to code. It is a wasteful implementation, in terms of cycles, but for an interview, who cares?

2

u/0pyrophosphate0 May 08 '15

for an interview, who cares?

Not the interviewer, you hope.

→ More replies (1)

6

u/LOOKITSADAM May 08 '15

My first instinct is to just treat them like strings and sort by reverse alphabetical order, then join them all together.

But then again, I'm close to half dead and fairly delirious at the moment, I could be way off.

2

u/[deleted] May 08 '15

Heh yeah, that is pretty much what I was describing I hope! I wasn't sure how to describe the behavior of alphabetizing where you "tie-break" with the next letter/digit

2

u/gee_buttersnaps May 08 '15

?If the second digit on the tie is bigger than the first digit of the other number, swap.

→ More replies (1)

2

u/cloakrune May 08 '15

My question is generally on what scale do I need this to work on? 100,000 numbers? 10? 4? And what is a reasonable runtime?

At 4 you can reasonably walk through all the permutations and just check all the possible values. At 1000+, you need some heuristic/mathmatical setup and possibly map reduce.

→ More replies (5)
→ More replies (2)

2

u/Ununoctium118 May 08 '15

Dynamic programming can probably do this a bit better than brute force, but I'm not sure how much faster.

1

u/thirdegree May 08 '15 edited May 08 '15

Pretty much. My solution was

def test(li):
    return int("".join(i for i in reversed(sorted(map(str, li)))))

which is probably a good deal more elaborate than it needs to be.

Edit: this doesn't work, it fails on the [9295, 92, 7] that another poster suggested.

→ More replies (1)

1

u/Gotebe May 08 '15

extract digits into a container, sort the container

1

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

This is a good recursive problem. Go one digit at a time. Start out as if you just need the first digit of all the numbers and the solution is just a single digit.

  • If you have a single clear winner, move on to the second digit by picking another number whose first digit will be the second digit of the solution.

  • If you have a n-way tie for highest first digit, you need to check the next digit of that number or grab a new number from the pile:

    • Choose the second digit of all possible winners that have a second digit.

    • If one possible winner doesn't have a second digit, then choose one of the remaining numbers to be the second digit.

    • If neither possible winners have another digit, they are the same. Choose the first one and move on.

    • Keep going until you have a single clear winner.

Once you have a winner for the second digit, move onto the third and continue until you have all the digits selected.

1

u/pointy May 08 '15 edited May 08 '15

Here's what I got (JavaScript):

function order(list) {
    return list.sort(function(e1, e2) {
        return +(e2 + '' + e1) - +(e1 + '' + e2);
    }).join('');
}

console.log(order([2, 3, 45, 4, 8, 62, 31]));

Note that 45 correctly goes before 4, but 31 goes after 3. The code just compares which concatenation order is largest between pairs (in the sort comparator callback).

edit — this is the same approach as @Boojum's Python version.

1

u/sparafucilee May 08 '15

I sorted by the value of the first digit and then by length when the first digits were equal. When lengths are equal, pick the largest.

→ More replies (1)