# Find the longest word in an array

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.

• 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) Dec 20, 2017 at 10:54
• Since I don't think anyone else has mentioned it -- Hi, and welcome to PPCG! Dec 20, 2017 at 14:21
• No you don't have to handle the case where the array is empty. But if you want you can. Dec 20, 2017 at 14:25
• 2 hours? That's far, far too quick to be accepting an answer. Dec 20, 2017 at 15:05
• Normally you wait a week
– user63187
Dec 20, 2017 at 16:43

# 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.
• Is this a-... Does thi-... How do you-.... What?! Dec 20, 2017 at 12:39
• 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.
Dec 20, 2017 at 12:44
• @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. Dec 20, 2017 at 16:32
• 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... Dec 22, 2017 at 1:59
• @fedes. You could say "Olkoon suomalainen suudelma uusi suudelma." (Let the Finnish kiss be a new kiss, it creates a new kiss object) Dec 22, 2017 at 7:58

# Python, 23 bytes

lambda a:max(a,key=len)


Try it online!

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

-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(compareonlength).reverse


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

import Data.List
import Data.Function
maximumBy(compareonlength).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.)

• With out the added "first-occurence-in-case-of-tie"-requirement, this beauty would work: snd.maximum.map((,)=<<(0<$)) Try it online!. Dec 20, 2017 at 13:49 • Just for reference: there's the boring 29 byte built-in import Data.Lists;argmax(0<$).
– nimi
Dec 20, 2017 at 23:27
• Woah, how is the l not a part of fold? How does it distinguish between that and a function named foldl? Dec 21, 2017 at 0:10
• @12Me21 It is part of the function name foldl1. I thought that part of the explanation might be confusing, sorry... Dec 21, 2017 at 0:19
• 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. Dec 21, 2017 at 22:52

# R + pryr, 31 bytes

[-2 bytes thanks to Scrooble]

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


Try it online!

# R, 33 bytes

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


Try it online!

• Also 33 bytes: x[which.max(nchar(x))] Dec 20, 2017 at 11:25
– NofP
Mar 5, 2018 at 10:19
• @NofP Haha, silly me. 31 bytes. Mar 5, 2018 at 12:19

# 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

• What for the , in the latter? The formula still works without it Dec 21, 2017 at 6:57
• 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. Dec 21, 2017 at 8:22
• Are sure? I've compared those two formulas and both come with the exact same result Dec 21, 2017 at 8:40
• 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) Dec 21, 2017 at 8:49
• 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! Jan 2, 2018 at 19:24

# 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

# Prolog (SWI), 989272 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.

• I'd be interested in seeing an explanation on how it works Jan 8, 2018 at 18:09
• @Cowsquack: I've added a short explanation. Jan 8, 2018 at 19:50

# 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

• ou nice you beat the Pyth answer with 6 bytes nice. Dec 20, 2017 at 13:52
• elD_ and ho_l achieve the same length. Dec 20, 2017 at 19:55
• @hakr14 Thank you very much for the edit! Mar 25, 2018 at 19:44

# PowerShell, 24 bytes

($args|sort l* -d)  Try it online! Takes input $args, pipes that to Sort-Object based on length in -descending order. Then takes the th one thereof. Since sort is stable, this takes the first element in case of a tie.

• Nice name wuff wuff :D Dec 20, 2017 at 14:39

# 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.

# JavaScript (Node.js), 38 bytes

Try it online!

a=>a.sort((a,b)=>a.length<b.length)

• @Doggo It does return the first element in the case of a tie. Dec 20, 2017 at 10:53
• 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. Dec 20, 2017 at 15:38
• but if it chooses it consistently in node.js on TIO isn't that good enough?\ Dec 21, 2017 at 6:19
• You should be using - instead of < in the comparator function. Dec 21, 2017 at 15:58
• @LiefdeWen Yes, but it addresses the problems in the comments. Dec 22, 2017 at 5:59

# 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!

• 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?
– mkst
Dec 20, 2017 at 12:15
• @streetster - Thanks! I just realised that. I'm going to try it now, it sould be much shorter. Dec 20, 2017 at 12:17
• No parentheses beyond this point: 0{::]\:#@> Dec 21, 2017 at 17:29
• Would {.@ instead of 0{:: work? Dec 21, 2017 at 18:46
• 8 bytes: 0{>\:#@> Dec 22, 2017 at 22:50

# C#, 43 + 18 = 61 bytes

Try it online!

a=>a.OrderByDescending(x=>x.Length).First()

• @Doggo It does return the first element in the case of a tie. Dec 20, 2017 at 10:53
• @LiefdeWen OrderBy is stable so this will in fact return last element in case of a tie. Example: tio.run/##TY7BCsIwDIbvfYqwUwvaF5jbQcHTRMGDB/… Dec 20, 2017 at 11:57
• @GrzegorzPuławski Oh, I see, fixed. Dec 20, 2017 at 12:17
• 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 Dec 20, 2017 at 20:54
• @MrLore That was my first solution but then in a tie it returns the last one, because order is unaffected. Dec 21, 2017 at 10:26

# Perl 6,  14  13 bytes

*.max(*.chars)


Try it

*.max(&chars)


Try it

array_reduce($a,function($c,$i){return (strlen($i)>strlen($c))?$i:$c;});  • Hello, and welcome to PPCG! :) Dec 20, 2017 at 21:51 # Japt -h, 5 3 bytes ÔñÊ  Try it Reverse, sort by length and output the last element. # Swift, 54 bytes {($0 as[String]).reduce(""){$1.count>$0.count ?$1:$0}}


Try it online!

# 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}).

# 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.length())w=y;return w;}


Ungolfed

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


Try it online!

# 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

• 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.
– cole
Dec 20, 2017 at 19:13
• Oh huh. Thank you for pointing that out. I can't believe that I didn't test that. Dec 21, 2017 at 13:56
• You can also change the define(m a) to λ(a) Dec 22, 2017 at 21:01
• Also check the tips if you haven't! Dec 22, 2017 at 21:06

# Bash, 45 bytes

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


Try it online!

• Welcome to PPCG, nice first post! Dec 22, 2017 at 22:51

# Scratch27 17 170 160 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(itemof[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.

• Is it necessary to stop[all here? Dec 22, 2018 at 5:25

# 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|[_]}


Try it online!

• Writing up my jq answer made me realise that enum can be dropped, and instead the minimum from [[-#_,_1]] can be selected, tio.run/… Dec 21, 2018 at 19:24
• @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... Dec 21, 2018 at 22:38

# 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)

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

# 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! # Julia 0.6, 24 bytes !s=s[indmax(length.(s))]  Try it online! # 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!

# Ruby, 21 20 bytes

->s{s.max_by &:size}


Try it online!

Trivial solution, thanks Snack for -1 byte

• Take the &:size out of the parentheses for -1 Dec 22, 2017 at 18:48

# Perl, 24 bytes

Includes +1 for p

Give words as lines on STDIN

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


# 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