1 of 2

Optimizing the telephone keypad

There seems to be this ongoing craze about people tediously learning new keyboard layouts like Dvorak or Neo because it supposedly makes them more productive. I argue that switching keyboard layouts is a bad idea, because it can take you months to get up to speed, and when you're finially 5% faster than the rest, you're screwed if you need to type on a computer that isn't your own.

Also, all these people seem to forget where the real bottleneck in modern communication lies - the telephone keypad.

This is how your average telephone keypad looks like:

The telephone keypad

Letter 'r' is the third letter on button 7; so if you were to type the letter 'r' on a mobile phone, you would press button 7 three times, for 's' you'd press it 4 times, and for 'a' you'd press button 2 once.

Considering this, putting 'e' after 'd' was probably a bad decision - 'e' is the most commonly used letter in the english alphabet, so, if you were to label button 3 "EDF" instead of "DEF", you would save quite a lot of keystrokes.

Moreover, you've probably experienced yourselves that typing 2 letters that share the same button is a nuisance - if you want to write "TU", you can't just hit 8 three times, because that would result in 'V'. So usually you'd write 'T', then hit space, then hit backspace, and then write 'U', which equals 5 button presses instead of 3.


Given these two rules:

  • A letter is typed by pressing a button n times, where n is the position of where the letter is at on the button's label
  • Writing two letters that are typed using the same button requires an additional 2 button presses

What's the telephone keyboard layout that requires the least amount of button presses, given a specific text? You should only use the buttons 2-9, 1 and 0 are reserved for special symbols.


The text which you should find the optimal layout for is supplied via stdin. You don't need to handle anything other than the lowercase alphabet and can assume that the input consists of only that. You can also assume that the input text is reasonably large and every letter is in there at least once, if that helps.


I don't want to put too many constraints on the output, since that sometimes gives some languages advantages over others; so however your language shows arrays is fine, alternatively you can seperate each label with a newline.

There may be multiple possible optimal layouts, you can print any one of them. Here's a simple example:

>> echo "jackdawslovemybigsphinxofquartz" | foo.sh

Bonus Points

-35 if your algorithm is not brute-forcing all possible layouts (I'm looking at Haskell's `permutations' here)

-3 if your code fits inside a text message (140 chars) and you post a pic of you sending your code to a friend.

This is my first challenge on StackExchange. I'd be happy to hear whether you like it, or have any other feedback about it!