Woe is me, I am a terrible programmer. Spoiler alert: Scroll down for terrible code followed by elegant code.

#### Question

You are given an array
strarr of strings and an integer
k. Your task is to return the **first** longest string consisting of k **consecutive** strings taken in the array.

**Example:**

longest_consec([“zone”, “abigail”, “theta”, “form”, “libe”, “zas”, “theta”, “abigail”], 2) –> “abigailtheta”

n being the length of the string array, if n = 0 or k > n or k <= 0 return “”.

**My answer**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
def longest_consec(strarr, k): n = len(strarr) print("strarr: ", strarr) print("index: ", k) if k > n or k > n or k <= 0: return "" elif n == k: return "".join(strarr) else: lenarr = [] for i in range(len(strarr)-(k-1)): current_len = 0 for j in range(k): current_len += len(strarr[i+j]) lenarr.append((current_len,i)) print("lenarr: ", lenarr) lenarr = sorted(lenarr) print("sorted lenarr: ", lenarr) index = -1 while lenarr[index - 1][0] == lenarr[-1][0]: index = index - 1 start_index = lenarr[index][1] print("index: ", index) return "".join(strarr[start_index:start_index + k]) |

And then I saw these three upvoted solutions:

1 2 3 4 5 6 7 8 9 10 11 |
# Solution 1 def longest_consec(strarr, k): result = "" if k > 0 and len(strarr) >= k: for index in range(len(strarr) - k + 1): s = ''.join(strarr[index:index+k]) if len(s) > len(result): result = s return result |

Instead of storing the combinations in an array and then sorting them, this algorithm dynamically updates `result`

as it goes through the array of strings.

The main reason my solution is so much uglier than these is because I translated the array of strings into an array of tuples with lengths and then did things with the translated list when that list didn’t have to be created in the first place. So **don’t create unnecessary temp things**.

1 2 3 4 5 6 |
# Solution 2 def longest_consec(strarr, k): if (len(strarr) == 0 or k <= 0) or len(strarr) < k: return "" lst = [''.join(strarr[i:i+k]) for i in xrange(len(strarr))] return max(lst, key= lambda x: len(x)) |

This solution uses a list comprehension to store all combinations in a list and then takes the max. It takes the max length elegantly using a lambda function and the key attribute of `max()`

.

1 2 3 |
# Solution 3 def longest_consec(s, k): return max(["".join(s[i:i+k]) for i in range(len(s)-k+1)], key=len) if s and 0 < k <= len(s) else "" |

This final solution condenses code into one row. I’d argue it’s less readable, but hey one-row solutions are neat for competition purposes.