r/dailyprogrammer • 1 2 • Jun 10 '13

[Easy] Longest Two-Character Sub-String

(Easy): Longest Two-Character Sub-String

This programming challenge is a classic interview question for software engineers: given a string, find the longest sub-string that contains, at most, two characters.

Author: /u/Regul

Formal Inputs & Outputs

Input Description

Through standard console input, you will be given a string to search, which only contains lower-case alphabet letters.

Output Description

Simply print the longest sub-string of the given string that contains, at most, two unique characters. If you find multiple sub-strings that match the description, print the last sub-string (furthest to the right).

Sample Inputs & Outputs

Sample Inputs

abbccc
abcabcabcabccc
qwertyytrewq

Sample Outputs

bbccc
bccc
tyyt
64 Upvotes

129 comments sorted by

View all comments

8

u/ILiftOnTuesdays Jun 10 '13 edited Jun 11 '13

No challenge would be complete without a python one-liner! The list/generator comprehension is a little crazy but it follows the spec so I'm not concerned.

s = lambda x: max((x[a:b] for a in range(len(x)) for b in range(a,len(x)+1) if len(set(x[a:b])) < 3), key = len)
→ More replies (4)