Skip to content

All Longest Strings

Given an array of strings, return another array containing all of its longest strings.

Example

For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be

all_longest_strings(inputArray) = ["aba", "vcd", "aba"]

Solution

py
def all_longest_strings(input_array):
    # solution 1
    # longest = len(max(input_array, key=len))
    # return [i for i in input_array if len(i) == longest]

    # solution 2
    # return [i for i in input_array if len(i) == len(max(input_array, key=len))]

    # solution 3
    longest = 0
    longest_array = []

    # find the longest string
    for i in input_array:
        if len(i) > longest:
            longest = len(i)

    # find all strings that are the longest
    for i in input_array:
        if len(i) == longest:
            longest_array.append(i)

    return longest_array


print(all_longest_strings(["aba", "aa", "ad", "vcd", "aba"]))
js
function allLongestStrings(inputArray) {
  let longest = 0;
  let longest_strings = [];

  // find the longest string
  for (let i = 0; i < inputArray.length; i++) {
    if (inputArray[i].length > longest) {
      longest = inputArray[i].length;
    }
  }

  // find all strings that are the longest
  for (let i = 0; i < inputArray.length; i++) {
    if (inputArray[i].length === longest) {
      longest_strings.push(inputArray[i]);
    }
  }

  return longest_strings;
}

console.log(allLongestStrings(['aba', 'aa', 'ad', 'vcd', 'aba']));

my thoughts are neither my employer's nor my wife's