25
\$\begingroup\$

Your challenge is to take an array of strings and output the longest string in the array. So for

["tiny", "small", "bigger", "biggest"]

the output would be biggest.

If two elements of the array have the same length, you should choose the one that appears first in the array. That means if the array looks like this:

["one", "two", "no"]

the output is one, but if the array looked like this:

["two", "one", "no"]

the output is two.


As this is , the shortest code in bytes wins.

\$\endgroup\$
8
  • 4
    \$\begingroup\$ 2 notes: 1 It's heavily discouraged if the question is changed and invalidates existing answer, and 2 the Sandbox exists for exactly that reason (make sure challenges are good before posting) \$\endgroup\$
    – DELETE_ME
    Dec 20, 2017 at 10:54
  • 4
    \$\begingroup\$ Since I don't think anyone else has mentioned it -- Hi, and welcome to PPCG! \$\endgroup\$ Dec 20, 2017 at 14:21
  • 1
    \$\begingroup\$ No you don't have to handle the case where the array is empty. But if you want you can. \$\endgroup\$
    – Doggo
    Dec 20, 2017 at 14:25
  • 5
    \$\begingroup\$ 2 hours? That's far, far too quick to be accepting an answer. \$\endgroup\$
    – Shaggy
    Dec 20, 2017 at 15:05
  • 7
    \$\begingroup\$ Normally you wait a week \$\endgroup\$
    – user63187
    Dec 20, 2017 at 16:43

63 Answers 63

32
\$\begingroup\$

Imperative Tampio, 168 bytes

Listan x on riippuen siitä,onko sen ensimmäisen alkion pituus suurempi tai yhtä suuri kuin sen jokaisen alkion pituus,joko sen ensimmäinen alkio tai sen hännän x.

Online version

Ungolfed:

Listan pisin alkio on riippuen siitä, onko sen ensimmäisen alkion pituus suurempi tai yhtä suuri kuin sen jokaisen alkion pituus, joko

  • sen ensimmäinen alkio tai
  • sen hännän pisin alkio.

Online version

The only golfing opportunity this has is to replace pisin alkio (meaning "the longest element") with x.

Translation:

The longest item in a list is, depending on whether the length of the first item is greater or equal to the length of each element in the list, either

  • the first item in the list, or
  • the longest item in the tail of the list.
\$\endgroup\$
8
  • 22
    \$\begingroup\$ Is this a-... Does thi-... How do you-.... What?! \$\endgroup\$
    – auhmaan
    Dec 20, 2017 at 12:39
  • 3
    \$\begingroup\$ Google Translate from Finnish: List of x is dependent on whether the length of the first element greater than or equal to the length of each element, either the first item or the tail of x. \$\endgroup\$
    – Adám
    Dec 20, 2017 at 12:44
  • 2
    \$\begingroup\$ @Adám I used to think APL is hard to read. Apparently all you need to beat that is to move the gamefield to a language where English is a rare commodity. \$\endgroup\$
    – Uriel
    Dec 20, 2017 at 16:32
  • 3
    \$\begingroup\$ Who needs COBOL, AppleScript or Inform 7? Who needs Arnold Chef or Shakespeare? You have Imperative Tampio! Oh my flying spaghetti monster, Finnish of all languages? I'm not learning that one any time soon... \$\endgroup\$
    – fede s.
    Dec 22, 2017 at 1:59
  • 1
    \$\begingroup\$ @fedes. You could say "Olkoon suomalainen suudelma uusi suudelma." (Let the Finnish kiss be a new kiss, it creates a new kiss object) \$\endgroup\$
    – fergusq
    Dec 22, 2017 at 7:58
20
\$\begingroup\$

Python, 23 bytes

lambda a:max(a,key=len)

Try it online!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ I'm sorry that I didn't convert this right. \$\endgroup\$
    – Doggo
    Dec 20, 2017 at 10:24
  • 1
    \$\begingroup\$ I updated the code snippet, but as it is written, it already achieves this functionality. \$\endgroup\$
    – Neil
    Dec 20, 2017 at 10:38
  • 1
    \$\begingroup\$ This will also work unchanged in Python 3. \$\endgroup\$
    – anonymoose
    Dec 21, 2017 at 21:48
17
\$\begingroup\$

Haskell, 35 bytes

-3 bytes thanks to Zgarb.

foldl1(!)
a!b|(a<$a)<(a<$b)=b|1<2=a

Try it online!

I like this code. You know why? Because Haskell supports much more elegant solutions with functions from random libraries.

maximumBy(compare`on`length).reverse

That's friggin' readable! Except, it's not valid.

import Data.List
import Data.Function
maximumBy(compare`on`length).reverse

If it weren't for the imports, this would've been a perfect submission to get all the upvotes. :P

(Also, this uses one golfing tip and it uses a fold.)

\$\endgroup\$
7
  • 2
    \$\begingroup\$ With out the added "first-occurence-in-case-of-tie"-requirement, this beauty would work: snd.maximum.map((,)=<<(0<$)) Try it online!. \$\endgroup\$
    – Laikoni
    Dec 20, 2017 at 13:49
  • 1
    \$\begingroup\$ Just for reference: there's the boring 29 byte built-in import Data.Lists;argmax(0<$). \$\endgroup\$
    – nimi
    Dec 20, 2017 at 23:27
  • 1
    \$\begingroup\$ Woah, how is the l not a part of fold? How does it distinguish between that and a function named foldl? \$\endgroup\$
    – 12Me21
    Dec 21, 2017 at 0:10
  • 1
    \$\begingroup\$ @12Me21 It is part of the function name foldl1. I thought that part of the explanation might be confusing, sorry... \$\endgroup\$ Dec 21, 2017 at 0:19
  • 1
    \$\begingroup\$ 35 bytes with a function instead of lambda. Interestingly, you must replace 0 with a or something else, otherwise GHC complains about an ambiguous numeric type. \$\endgroup\$
    – Zgarb
    Dec 21, 2017 at 22:52
9
\$\begingroup\$

R + pryr, 31 bytes

[-2 bytes thanks to Scrooble]

pryr::f(x[order(-nchar(x))][1])

Try it online!


R, 33 bytes

function(x)x[order(-nchar(x))][1]

Try it online!

\$\endgroup\$
3
  • 3
    \$\begingroup\$ Also 33 bytes: x[which.max(nchar(x))] \$\endgroup\$
    – Giuseppe
    Dec 20, 2017 at 11:25
  • \$\begingroup\$ @Scrooble from your link I see a 33 bytes solution. \$\endgroup\$
    – NofP
    Mar 5, 2018 at 10:19
  • 1
    \$\begingroup\$ @NofP Haha, silly me. 31 bytes. \$\endgroup\$ Mar 5, 2018 at 12:19
8
\$\begingroup\$

EXCEL, 36 42 bytes

=INDEX(A:A,MATCH(MAX(LEN(A:A)),LEN(A:A),))

Entered as an array formula (ctrl-shift-enter). The input array should be entered in column A.

The formula returns the first match with maximum length.

Depending on your region settings, substitute , with ;; the code length remains unchanged. Of the 16 languages listed here, English function names are the shortest for this formula.

Explanation:

=                                          - return
 INDEX(                                  ) - the item of
       A:A                                 - the input
          ,                                - at
           MATCH(                       )  - the position of
                                       ,   - the first exact match of
                 MAX(        )             - the maximum of
                     LEN(   )              - the array of lengths of
                         A:A               - the input
                              ,            - in
                               LEN(   )    - the array of lengths of
                                   A:A     - the input
\$\endgroup\$
6
  • \$\begingroup\$ What for the , in the latter? The formula still works without it \$\endgroup\$ Dec 21, 2017 at 6:57
  • \$\begingroup\$ The final , is a parameter for MATCH that returns the first exact match, as required by the (revised) question. If it is left out, then MATCH expects an array in ascending order, and returns the last match instead of the first if there are multiple elements with the same length. \$\endgroup\$
    – pbeentje
    Dec 21, 2017 at 8:22
  • \$\begingroup\$ Are sure? I've compared those two formulas and both come with the exact same result \$\endgroup\$ Dec 21, 2017 at 8:40
  • \$\begingroup\$ Are you using an input array that has two (different) strings of the same length? Leaving out the comma (semicolon) gives me the last string of maximum length, as expected... (Excel 2016, 64-bit) \$\endgroup\$
    – pbeentje
    Dec 21, 2017 at 8:49
  • \$\begingroup\$ Unfortunately the community has decided that using named ranges in this manner is invalid so I suggest that for this particular case you switch to using A:A and make it an array formal with {...}, otherwise great post! \$\endgroup\$ Jan 2, 2018 at 19:24
7
\$\begingroup\$

APL (Dyalog Unicode), 9 bytesSBCS

⊢⊃⍨∘⊃∘⍒≢¨

Try it online!

 from the argument,

⊃⍨ pick the element with the index which is the

 first of the

 indices in descending order of the

≢¨ lengths of each

\$\endgroup\$
7
\$\begingroup\$

Prolog (SWI), 98 92 72 69 bytes

The top level predicate is *.

X/Y:-atom_length(X,Y).
[A]*A.
[A,B|L]*Z:-A/X,B/Y,Y>X,[B|L]*Z;[A|L]*Z.

Try it online!

Explanation

The first row defines the dyadic predicate / to be a short for atom_length/2which is true if the first argument's length is the second argument. This saves us 3 bytes over using atom_length twice.

Our main predicate is defined as the dyadic * where the first argument is a list and the second argument the longest element of that list.

The second row is our base case which states that the longest element of a one element list is that element.

The third row states that for a list with at least 2 elements, the longest element is:

If the length of the second element is longer than the first element, the longest element is in the list without the first element.

Otherwise the longest element is in the list without the second element.

\$\endgroup\$
2
  • \$\begingroup\$ I'd be interested in seeing an explanation on how it works \$\endgroup\$
    – user41805
    Jan 8, 2018 at 18:09
  • \$\begingroup\$ @Cowsquack: I've added a short explanation. \$\endgroup\$
    – Emigna
    Jan 8, 2018 at 19:50
7
\$\begingroup\$

Pyth, 4 bytes

h.Ml

Test suite.

Explanation
h.Ml   | Program
h.MlZQ | With implicit variables filled in
-------+--------------------------------------------------------------------
h      | First element of
 .M  Q | The list of elements from the input list with the maximal value for
   lZ  | The length of the element
\$\endgroup\$
3
  • \$\begingroup\$ ou nice you beat the Pyth answer with 6 bytes nice. \$\endgroup\$
    – Doggo
    Dec 20, 2017 at 13:52
  • \$\begingroup\$ elD_ and ho_l achieve the same length. \$\endgroup\$
    – isaacg
    Dec 20, 2017 at 19:55
  • 1
    \$\begingroup\$ @hakr14 Thank you very much for the edit! \$\endgroup\$
    – Mr. Xcoder
    Mar 25, 2018 at 19:44
6
\$\begingroup\$

PowerShell, 24 bytes

($args[0]|sort l* -d)[0]

Try it online!

Takes input $args[0], pipes that to Sort-Object based on length in -descending order. Then takes the [0]th one thereof. Since sort is stable, this takes the first element in case of a tie.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Nice name wuff wuff :D \$\endgroup\$
    – Doggo
    Dec 20, 2017 at 14:39
6
\$\begingroup\$

Octave, 33 bytes

@(x)x{[~,p]=max(cellfun(@nnz,x))}

Input is a cell array of strings.

Try it online!

Explanation

cellfun(@nnz,x) applies the nnz function (number of nonzeros) to each string in the input array x. For ASCII strings, nnz is equivalent to numel (number of elements), but shorter. The result is a numeric array with the string lengths.

Then, [~,]=max(...) gives the index of the first maximum in the array of string lengths. The result is used as a curly-brace index into x to obtain the corresponding string.

\$\endgroup\$
6
\$\begingroup\$

JavaScript (Node.js), 38 bytes

Try it online!

a=>a.sort((a,b)=>a.length<b.length)[0]
\$\endgroup\$
9
  • \$\begingroup\$ @Doggo It does return the first element in the case of a tie. \$\endgroup\$
    – LiefdeWen
    Dec 20, 2017 at 10:53
  • 1
    \$\begingroup\$ Returning a boolean instead of a signed number in the sort() callback doesn't work in all JS engines (e.g. it doesn't work in Edge). Another approach would be something like that, which is 1 byte shorter. Still, there's no guarantee that the first item will be chosen consistently across browsers in case of a tie. \$\endgroup\$
    – Arnauld
    Dec 20, 2017 at 15:38
  • \$\begingroup\$ but if it chooses it consistently in node.js on TIO isn't that good enough?\ \$\endgroup\$
    – LiefdeWen
    Dec 21, 2017 at 6:19
  • 1
    \$\begingroup\$ You should be using - instead of < in the comparator function. \$\endgroup\$
    – kamoroso94
    Dec 21, 2017 at 15:58
  • 1
    \$\begingroup\$ @LiefdeWen Yes, but it addresses the problems in the comments. \$\endgroup\$ Dec 22, 2017 at 5:59
5
\$\begingroup\$

J, 19, 11, 10 8 bytes

0{>\:#@>

Try it online!

Thanks to streetster for the hint!

-1 byte thanks to FrownyFrog!

-2 bytes thanks to Conor O'Brien

How it works:

    (  #@>) - unbox each string and find its length
     \:     - sort down the list of strings according to the lengths
0{::        - take and unbox the first string

Try it online!

\$\endgroup\$
9
  • 1
    \$\begingroup\$ This was my initial approach in K, but then I realised I could just sort the list by the count, descending, and take the first item... Can you do the same thing in J? \$\endgroup\$
    – mkst
    Dec 20, 2017 at 12:15
  • \$\begingroup\$ @streetster - Thanks! I just realised that. I'm going to try it now, it sould be much shorter. \$\endgroup\$ Dec 20, 2017 at 12:17
  • 1
    \$\begingroup\$ No parentheses beyond this point: 0{::]\:#@> \$\endgroup\$
    – FrownyFrog
    Dec 21, 2017 at 17:29
  • \$\begingroup\$ Would {.@ instead of 0{:: work? \$\endgroup\$
    – user41805
    Dec 21, 2017 at 18:46
  • 1
    \$\begingroup\$ 8 bytes: 0{>\:#@> \$\endgroup\$ Dec 22, 2017 at 22:50
4
\$\begingroup\$

C#, 43 + 18 = 61 bytes

Try it online!

a=>a.OrderByDescending(x=>x.Length).First()
\$\endgroup\$
7
  • \$\begingroup\$ @Doggo It does return the first element in the case of a tie. \$\endgroup\$
    – LiefdeWen
    Dec 20, 2017 at 10:53
  • \$\begingroup\$ @LiefdeWen OrderBy is stable so this will in fact return last element in case of a tie. Example: tio.run/##TY7BCsIwDIbvfYqwUwvaF5jbQcHTRMGDB/… \$\endgroup\$ Dec 20, 2017 at 11:57
  • 1
    \$\begingroup\$ @GrzegorzPuławski Oh, I see, fixed. \$\endgroup\$
    – LiefdeWen
    Dec 20, 2017 at 12:17
  • \$\begingroup\$ I've got a few that maybe someone can help shorten a=>a.Aggregate((x,y)=>y.Length>x.Length?y:x) 44 byte base, a=>a.First(x=>x.Length==a.Max(y=>y.Length)) 43 byte base \$\endgroup\$
    – Monso
    Dec 20, 2017 at 20:54
  • 1
    \$\begingroup\$ @MrLore That was my first solution but then in a tie it returns the last one, because order is unaffected. \$\endgroup\$
    – LiefdeWen
    Dec 21, 2017 at 10:26
4
\$\begingroup\$

Perl 6,  14  13 bytes

*.max(*.chars)

Try it

*.max(&chars)

Try it

\$\endgroup\$
4
\$\begingroup\$

PHP, 72 bytes

array_reduce($a,function($c,$i){return (strlen($i)>strlen($c))?$i:$c;});
\$\endgroup\$
1
  • 4
    \$\begingroup\$ Hello, and welcome to PPCG! :) \$\endgroup\$
    – DJMcMayhem
    Dec 20, 2017 at 21:51
4
\$\begingroup\$

Japt -h, 5 3 bytes

ÔñÊ

Try it

Reverse, sort by length and output the last element.

\$\endgroup\$
3
\$\begingroup\$

Swift, 54 bytes

{($0 as[String]).reduce(""){$1.count>$0.count ?$1:$0}}

Try it online!

\$\endgroup\$
3
\$\begingroup\$

K (oK), 9 bytes

*x@>#:'x:

Try it online!

Example:

*x@>#:'x:("edur";"oot";"taht")
"edur"

Explanation

*x@>#:'x: / solution
       x: / store input in variable x
    #:'   / count (#:) each (')
   >      / sort descending
 x@       / apply indices to x
*         / take the first one

Notes:

Undeleted as this is classed as non-trivial, despite being basically 5 steps (would be if written as the function {*x@>#:'x}).

\$\endgroup\$
3
\$\begingroup\$

Java (OpenJDK 8), 67 bytes

Another submission in my favourite language! (read: the only one I know).
This doesn't work with an empty array, but that's fine.

Golfed

w->{for(String y:w)if(y.length()>w[0].length())w[0]=y;return w[0];}

Ungolfed

for(String y:w)                           // Loops through all Strings
    if(y.length()>w[0].length())          // If the String is longer than the first String 
                                w[0]=y;   // Store it as the first string.
return w[0];                              // Return the first String.

Try it online!

\$\endgroup\$
3
\$\begingroup\$

Racket, 160 bytes 110 bytes

Try it online! First time contributing, advice appreciated!

(define(m a)(if(>(length a)1)(if(>=(string-length(car a))(string-length(m(cdr a))))(car a)(m(cdr a)))(car a)))

Ungolfed

(define (m a)
    (if (> (length a) 1)
        (if (>= (string-length (car a)) (string-length (m (cdr a))))
            (car a)
            (m (cdr a))
        )
        (car a)
    )
)

Updated solution based on feedback

\$\endgroup\$
4
  • 4
    \$\begingroup\$ I'd like to say welcome to PPCG on behalf of the community! I noticed that your solution apparently fails for lists where the longest string is at the end. Example here. I don't remember Racket well, but if you can I would recommend changing your algorithm to a foldr-based approach, taking the max by length and carrying that across. \$\endgroup\$
    – cole
    Dec 20, 2017 at 19:13
  • \$\begingroup\$ Oh huh. Thank you for pointing that out. I can't believe that I didn't test that. \$\endgroup\$ Dec 21, 2017 at 13:56
  • \$\begingroup\$ You can also change the define(m a) to λ(a) \$\endgroup\$
    – fede s.
    Dec 22, 2017 at 21:01
  • 1
    \$\begingroup\$ Also check the tips if you haven't! \$\endgroup\$
    – fede s.
    Dec 22, 2017 at 21:06
3
\$\begingroup\$

Bash, 45 bytes

a=;for b;do((${#b}>${#a}))&&a=$b;done;echo $a

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Welcome to PPCG, nice first post! \$\endgroup\$ Dec 22, 2017 at 22:51
3
\$\begingroup\$

Scratch 27 17 170 160

the code picture

It expects a global (attached to all sprites, to be more precise) list of strings called mylist. After clicking the green flag, the longest word will be left in the variable w.

I think this is the link

when gf clicked
set[w]to(item[1]of[mylist
set[i]to[0
repeat(length of[mylist
change[i]by(1
set[m]to(item(i)of[mylist
if<(m)>(w)>then
set[w]to(m
end
end
stop[all

Counting as per this meta.

\$\endgroup\$
1
  • \$\begingroup\$ Is it necessary to stop[all here? \$\endgroup\$
    – ggorlen
    Dec 22, 2018 at 5:25
3
\$\begingroup\$

Röda, 30 bytes

{enum|[[#_,-_,_1]]|max|_|tail}

Try it online!

Explanation:

{
 enum|         /* For each element, push its index to the stream */
 [[#_,-_,_1]]| /* For each element and index, push [length, -index, element] */
 max|          /* Find the greatest element */
 _|            /* Flat the list in the stream */
 tail          /* Return the last item in the stream */
}

Alternative 30 bytes:

{enum|[[#_,-_,_1]]|max|[_[2]]}

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Writing up my jq answer made me realise that enum can be dropped, and instead the minimum from [[-#_,_1]] can be selected, tio.run/… \$\endgroup\$
    – user41805
    Dec 21, 2018 at 19:24
  • \$\begingroup\$ @Cowsquack That doesn't work because then min would compare strings secondarily alphabetically (because arrays are compared secondarily by their second item). For example input ["b", "a"] would give "a" as output. I should probably add a minby function to Röda or something similar... \$\endgroup\$
    – fergusq
    Dec 21, 2018 at 22:38
3
\$\begingroup\$

APL -- 23 16 bytes

a←{((⍴¨⍵)⍳(⌈/(⍴¨⍵)))⌷⍵}

Thanks to everyone for all of your great suggestions and encouragement!

a←{⍵⌷⍨(⍴¨⍵)⍳⌈/⍴¨⍵}

Usage:

a 'duck' 'duck' 'goose'
  'goose'

Explanation:

gets length of each vector of characters (string) then uses maximum as an index. I just started APL 20 min ago so I am sorry if this is a stupid way to do it.

Try it Online!

(edited for clarity)

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Welcome to PPCG! \$\endgroup\$
    – Steadybox
    Dec 21, 2017 at 7:24
  • \$\begingroup\$ The a← is not counted towards your bytecount. \$\endgroup\$
    – user41805
    Dec 22, 2017 at 10:17
  • \$\begingroup\$ Never forget APL is evaluated right-to-left: (⌈/(⍴¨⍵)) => ⌈/⍴¨⍵. Also, (...)⌷⍵ => ⍵⌷⍨... to save one byte \$\endgroup\$
    – Adalynn
    Dec 22, 2017 at 22:44
  • \$\begingroup\$ Other than the parentheses, this actually seems pretty good! \$\endgroup\$
    – Adalynn
    Dec 22, 2017 at 22:46
2
\$\begingroup\$

Standard ML (MLton), 55 bytes

fun&(s::r)=foldl(fn(%,$)=>if size% >size$then%else$)s r

Try it online! Example usage: & ["abc","de","fgh"] yields "abc".

Ungolfed:

fun step (current, longest) = 
    if size current > size longest 
    then current 
    else longest

fun longestString (start :: list) = foldl step start list
  | longestString nil = raise Empty

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Julia 0.6, 24 bytes

!s=s[indmax(length.(s))]

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Funky, 38 bytes

a=>a[(v=a::map@#)::find(math.max...v)]

Explained

a=>a[(v=a::map@#)::find(math.max...v)]
        a::map@#                        $ Create a list of the lengths of the input's strings.
      v=                                $ And assign it to v.
     (          )::find(            )   $ Find the first index in this list that equals...
                        math.max...v    $ The largest value of v, eg. the length of the longest string.
   a[                                ]  $ Get the value at that position.

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Ruby, 21 20 bytes

->s{s.max_by &:size}

Try it online!

Trivial solution, thanks Snack for -1 byte

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Take the &:size out of the parentheses for -1 \$\endgroup\$
    – Snack
    Dec 22, 2017 at 18:48
2
\$\begingroup\$

Perl, 24 bytes

Includes +1 for p

Give words as lines on STDIN

perl -pe '$;[y///c]//=$_}{$_=pop@'
one
two 
no
^D
\$\endgroup\$
2
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 63 57 bytes

I	M =LT(SIZE(M),SIZE(X)) X
	X =INPUT	:S(I)
	OUTPUT =M
END

Try it online!

Input is on stdin and output on stdout.

Roughly translates to the following pseudocode:

while input exists
 x = input
 if length(m) < length(x)
  m = x
end
return m
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.