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

129 comments sorted by

View all comments

Show parent comment

1

u/Urist_Mc_George Jun 13 '13 edited Jun 13 '13

Your Solution would work as well. But the break does not go out of the if structure, it ends the whole for loop. It is an optimisation, because we don't need to iterate over the remaining chars, after we found the first not matching char. We can't find a longer substring here.

I hope my explanation helps.

Edit:

Your code would not work in all cases:

Take abbbcb for example. abbb is clear, now the c my code would breake, and stop iterating over the chars. Without the break you would not increase the counter at the c, but go on to the last char b. Now the counter would get incremented as well.

1

u/iche0815 Jun 13 '13

Ahh, thanks for the explanation. I thought because the break is inside the if/else structure it only ends this. Now it makes much more sense :)