skip to Main Content

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
solution(inputArray) = ["aba", "vcd", "aba"].

[execution time limit] 4 seconds (dart)

[input] array.string inputArray

[input] array.string inputArray

A non-empty array.

Guaranteed constraints:
1 ≤ inputArray.length ≤ 10,
1 ≤ inputArray[i].length ≤ 10.

[output] array.string

[output] array.string

Array of the longest strings, stored in the same order as in the inputArray.

I know that the javascript code answer of the above question but did’t know how to write it into dart.
this is the javascript //

  var maxLength = Math.max(...inputArray.map(s => s.length));
    return inputArray.filter(s => s.length === maxLength);

2

Answers


  1. You can sort the list by its item’s length and then search for items that have equal length to the longest item in sorted list. like this:

    var inputArray = ["aba", "aa", "ad", "vcd", "aba"];
    inputArray.sort(
      (a, b) => b.length.compareTo(a.length),
    );
    var result = inputArray
        .where((element) => element.length == inputArray.first.length)
        .toList();
    print("inputArray = $result"); //[aba, vcd, aba]
    

    or use reduce instead of sort, like this:

    var maxString = inputArray.reduce(
        (value, element) => element.length > value.length ? element : value);
    
    var result = inputArray
        .where((element) => element.length == maxString.length)
        .toList();
    print("inputArray = $result"); //[aba, vcd, aba]
    
    Login or Signup to reply.
  2. This is pretty easy.

    final inputArray = ["aba", "aa", "ad", "vcd", "aba"];
    
    final lenArr = inputArray.map((e) => e.length).toList()..sort();
    final finalArr = inputArray.where((el) => el.length == lenArr.last);
    
    log(finalArr.toString()); // [aba, vcd, aba]
    

    Output:

    [aba, vcd, aba]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search