You cannot find a solution that is less complex than O (n), because you need to go through each character in the worst case with an input line that contains no more than 0 or 1 consecutive spaces, or a complete space.
However, you can do some optimizations, but it will still be considered O (n).
For example:
Let M be the longest match as you go through your list. Also suppose you can access the input elements in O (1), for example, you have an array as input.
When you see spaces without spaces, you can skip M elements if current + M not a space. Of course, there cannot be spaces inside M.
And when you see a white character, if current + M-1 not a space, you know that you do not have the longest runs, you can also skip in this case.
Brian R. bondy
source share