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
62 Upvotes

129 comments sorted by

View all comments

1

u/Freded21 Jun 18 '13

Hey, so normally I can do the easy ones, well quite easily. This one though, stumped me. It was really hard for me, I ended up using a crazy convoluted answer that I don't really understand, but it works. I'm gonna put comments all over trying to get my head all the way around it, but here's the solution(It's in python):

def longesttwo(string):
    longest = ""
    checking = ""
    ok = []
    ok.append(string[0])
    newchecking = ""



    for n in range(len(string)):
		if len(ok) ==  1:
			if string[n] not in ok:
				ok.append(string[n])
		elif len(ok) == 2:
			if string[n] == ok[0]:
				ok[0], ok[1] == ok[1], ok[0]
	
		if string[n] in ok:
				checking = checking + string[n]
		else:
			ok.remove(ok[0])
			ok.append(string[n])
			for i in range(len(checking)):
				if checking[i] not in ok:
					newchecking = checking[i+1:]
			checking = newchecking + string[n]
		if len(checking) >= len(longest):
			longest = checking
    return longest