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

IFS=$'\n';egrep -m1 .{wc -L<<<"$*"}<<<"$*"  Try it online! # dc, 3938 36 bytes 0sl[slssdd]sG[dZdll!>Gooz0<M]dsMxlsp  Try it online! Edit: -1 byte, filling up empty space by 'd' instead Edit: -2 bytes, thanks @brhfl for suggestion! • Looks like you can shave off a byte by moving the ? input behind (or in front of) your initial 0sl instead (or, typically it is allowed to just assume the stack is input, ? can likely be omitted for another byte), and then changing sMlMx to dsMx. – brhfl Mar 23 '18 at 20:47 • @brhfl thanks for suggestion! – cab404 Mar 24 '18 at 7:07 # APL+WIN, 11 bytes s[↑⍒∊⍴¨s←⎕]  Prompts for screen input in the form 'abc' 'defg' hijklm' # Perl 5, 38 bytes say((sort{$a=~y///c<=$b=~y///c}<>)[0])  Try it online! # C++, 125 bytes Accepts input as a pair of iterators; returns an iterator to the longest string. The array must not be empty (i.e. the iterators must be different). #include<algorithm> template<class I>I f(I a,I b){return std::max_element(a,b,[](auto&a,auto&b){return a.size()<b.size();});}  # Demo #include <string> #include <iostream> #include <iterator> int main() { std::string strings[] = { "Programming", "Puzzles", "and", "Code", "Golf" }; std::cout << *f(std::begin(strings), std::end(strings)) << std::endl; }  The definition of std::max_element() guarantees that If several elements in the range are equivalent to the greatest element, returns the iterator to the first such element. • If you're using GCC, you can use #import<regex>. – user202729 Dec 24 '17 at 3:36 # Jelly, 4 bytes LÐṀḢ  Try it online! Maximum (ÐṀ) by length (L). Take Head (Ḣ). # Jelly, 4 bytes ṚLÞṪ  Try it online! Reverse. Sort by length. Take tail (last element). # Javascript ES5, 41 bytes Since there was already a solution using sort... Try it online a=>a.reduce((x,y)=>x.length>=y.length?x:y)  # Coconut, 15 13 bytes max$(key=len)


Try it online!

L,bU«bL


Try it online!

More interesting, 32 byte version:

L,vbU§bLdbLBkÞ{g}@
D,g,@,bLBK=


Try it online!

## How they work

L,	; Create a lambda function
; Example argument:         		[["two" "one" "abc" "no"]]
bU	; Evaluate as list; 			STACK = ['two' 'one' 'abc' 'no']
«bL	; Take the value with the max length;	STACK = ['two']


And the 32 byte version:

L,		; Create a lambda function
; Example argument: 		['["two" "one" "no"]']
vbU	; Evaluate;		STACK = ['two' 'one' 'no']
§bL	; Sort by length;	STACK = ['no' 'two' 'one']
dbLBk	; Save length;		STACK = ['no' 'two' 'one']	REGISTER = 3
Þ{g}	; Filter by 'g';	STACK = ['two' 'one']
@	; Reverse;		STACK = ['one' 'two']
; Implicitly return the top element:   'two'

D,g,@,		; Create a function 'g'
; Example argument:		['two']
bL	; Length;		STACK =	[3]
BK=	; Equal to register;	STACK = [1]


# jq-r, 19 15 bytes

Golfed 4 bytes after learning min_by is a builtin.

min_by(-length)


Try it online!

(Without -r the output string is surrounded with "s.)

# Lua, 70 64 bytes

function f(a,...)x=...and f(...)return x and#x>#a and x or a end


Try it online!

x is set to the second argument if that is falsy, otherwise the longest of the second argument and up. The function returns x if it is truthy and longer than the first argument, else the first argument.

No type-checking, so works not only for a sequence of strings, but for sequences containing tables, or anything with a __len metamethod that returns a number. For instance f("tiny", {1, 2, 3, 4, 5}, debug.setmetatable(6, { __len = function (self) return self end })) returns 6.

This technically breaks the rule of operating on an array (in Lua, a table) because it operates on an argument list, but operating on a table seemed more complicated (table.sort is not stable). A table can be unpacked into the function: f(table.unpack { 'oh', 'one', 'two' }).

# Mathematica, 29 bytes

#&@@#~MaximalBy~StringLength&


Pure function. Takes a list of strings as input and returns a string as output. #~MaximalBy~StringLength finds the longest strings in the list and #&@@ selects the first instance.

• I've been trying to find an improvement on StringLength, which is pretty long. Sadly ByteCount doesn't grow one-to-one with the length of the string. Is there anything clever in this area? – Patrick Stevens Dec 21 '17 at 8:56

# Rust, 73 bytes

|mut x:Vec<String>|{x.sort_by(|a,b|b.len().cmp(&a.len()));x[0].clone()}


Very simple code, that can probably be golfed at least a little more. The fact that i had to use String instead of &str, just for the return value, bugs me alot. (I could have used a .to_string() method, but that wouldve added 2 bytes.)

Try it online!

# MY, 24 bytes

1ω74ǵ'ƒ⇹(ω74ǵ'ƒ⇹(⍐=⍸@ω@←


Try it online!

## How?

1ω74ǵ'ƒ⇹(ω74ǵ'ƒ⇹(⍐=⍸@ω@←
← = Output ...
ω  = ... the input ...
@ = ... at ...
1                    @   = ... the first ...
⍸     = ... truthy index of ...
ω74ǵ'ƒ⇹(                = ... the length of each element of the input's ...
=      = ... equality with ...
ω74ǵ'ƒ⇹(⍐       = ... the maximum length.



# Java 8, 57 bytes (70 bytes)

By the power of streams, my java answer shall be the shortest

Arrays.stream(a).max(Comparator.comparing(String::length))


Honestly I don't know if I cheated with that answer because I don't return anything but you could use that line of code. If we really want to return stuff then it's a bit longer.

Thanks to LukeStevens for pointing out to use lambdas to be more golfy.

w->Arrays.stream(w).max(Comparator.comparing(String::length)‌​).get()

• Welcome to PPCG! An answer needs to be either a program or a function, a snippet of code is not enough. Also, input needs to be taken in some allowed way. Assuming that the input is stored in a predetermined variable is not allowed. You can take input for example from STDIN or as an argument to a function. – Steadybox Dec 21 '17 at 7:32
• Hi @Steadybox I changed my program to a function(method). Is it ok now? – ChristophE Dec 21 '17 at 7:42
• @ChristophE Unfortunately you need to include the byte cost of imports aswell :( which would add another 19 bytes to this, otherwise it's a really good solution! You should also have a look at using lamdbas which would reduce the code to w->Arrays.stream(w).max(Comparator.comparing(String::length)).get() – Luke Stevens Dec 21 '17 at 8:31
• I think I don't understand completely, my code already uses lambdas :D but just the lambda expression counts as 'function' in codegolf? thats good to know then I'll change my answer – ChristophE Dec 21 '17 at 8:58
• By the power of streams, my Java answer shall be the shortest: s->s.max((a,b)->a.length()-b.length()).get() (44 bytes). – Olivier Grégoire Dec 21 '17 at 9:35

# F# (.NET Core), 29 bytes

 Seq.maxBy <| fun s->s.Length


Try it online!

# Explanation

Through partial application of Seq.maxBy, returns a function (string seq -> string)

# Stacked, 19 bytes

[:$#'"!:MAX index#]  Try it online! ## Explanation [:$#'"!:MAX index#]
[                 ]   anonymous function, takes input as list of strings

# Common Lisp, 32 bytes

(elt(sort(read)'> :key'length)0)


Try it online!

# Husk, 3 bytes

►L↔


Try it online!

## Explanation

  ↔  -- reverse the list (such that the first gets picked in case of a tie)
►L   -- find maximum by length


## Scratch 2.0, 22 blocks

Accepts input by pressing see inside on the project page and manually adding and removing items from list.

Project here. Flash required to run and view, apologies.

All blocks were counted including nested ones. Not sure how I'd count bytes with this language unless you want the length of the JSON.

• You might want to check out this question on meta. – Timtech Dec 24 '17 at 6:25
• @Timtech thanks a ton! Didn't even know scoring existed for Scratch. :P Probably should have done it in a "real" language. – MustacheMoses Dec 24 '17 at 20:52

# 05AB1E, 3 bytes

Réθ


Try it online!

Explanation

R     # reverse
é    # sort by length
θ   # get the last element


while($n=strlen($s=$argv[++$i]))$n>$e&&$e=$n+!$r=$s;echo$r;  takes words as separate command line arguments. Run with -nr or try it online. # Google Sheets, 40 Bytes Anonymous worksheet function that takes input from range A:A and outputs to the calling cell =Index(A:A,Match(Max(Len(A:A)),Len(A:A),  # PHP, 69 bytes usort($x,function($a,$b){return strlen($b)<=>strlen($a);});echo\$x[0];


Not a trick or nice golfing, just sorting array by string length and then outputting the first element.

# APL NARS, 10 chars, 24 bytes

{⍵[↑⍒⍴¨⍵]}


note in the test, that: 'uno' it is not one array of array, so the array of correct deep is ,⊂'uno' instead

⎕fmt  ,⊂'uno'
┌1─────┐
│┌3───┐│
││ uno││
│└────┘2
└∊─────┘


so in the test g fail for 'uno'

g←{⍵[↑⍒⍴¨⍵]}
g 'uno'
u


but not fail for the correct type of input

g ,⊂'uno'
uno
g 'uno' 'quattro' 'cinque'
quattro
⎕fmt  g ,⊂''
┌───┐
│┌0┐│
││ ││
│└¯┘2
└∊──┘


if the community think this is one too much big limitation: than there is the 18 chars solution

{1=≡⍵:⍵⋄∊⍵[↑⍒⍴¨⍵]}


that evade the problem in the first test calculate the deep of input

f←{1=≡⍵:⍵⋄∊⍵[↑⍒⍴¨⍵]}
f 'uno'
uno
f 'uno' 'quattro' 'cinque'
quattro


The problem of the input type of one Char in Apl as 'a' (it is consider from interpreter one char). We can transform that in one array of array of char, or one type list of arrays of deep 2 write ,⊂,'a'; so g ,⊂,'a' should return the correct answer of type array of array length 1

• Please try not to make spelling and grammar error... – user202729 Jan 8 '18 at 11:01
• @user202729 for the spelling error this computer seems sufficient, for grammar error nothing – user58988 Jan 8 '18 at 11:23
• My computer clearly shows the warning. – user202729 Jan 8 '18 at 11:35
• @user202729 ok, I use one different phrase (for eccessive); thank you very much, and a good year – user58988 Jan 8 '18 at 11:51

# V, 272321 20 bytes

Í./_
ÚGYu/"
uYHVGp


Try it online!

Explanation:

Í./_         In every line, replace every character by _
Ú            Sort alphabetically. Cursor ends up in first line
GY          Go to last line, copy it
u         Undo sort
/"       Search for string in register " (the one that was just copied). Non-printable character is <C-r>
u            Undo replace, go to last cursor position. Non-printable character is <C-o> (thanks, Cows quack)
Y          Copy line
HVG       Go to first line, select all lines until last line
p      Paste copied line into selection


Hexdump:

00000000: cd2e 2f5f 0ada 4759 752f 1222 0a75 0f59  ../_..GYu/.".u.Y
00000010: 4856 4770                                HVGp


# C++ (gcc), 65 63 bytes

Accepts any container of std::string and returns via reference.

[](auto&c,auto&r){r=c[0];for(auto x:c)r=x.size()>r.size()?x:r;}


Try it online!

If you are tolerant to output, there is a 58 byte solution which alters the input list and copies the longest string to the first element:

[](auto&c){for(auto x:c)c[0]=x.size()>c[0].size()?x:c[0];}


# Attache, 9 bytes

MaxBy&:#


Try it online!

This is simply bonding the size operator (#) to the left of MaxBy. This is equivalent to:

f[x] := MaxBy[Size, x]


...which selects the first element with the largest size in x.

# sed 4.2.2-rz, 71 7283 bytes

h
:
s/^.//gm
/[^\n]{2}/t
:b
/^\n/{s/.//
x
s/^[^\n]*.//
x}
tb
x
s/\n.*//


Try it online!

• -r uses extended regular expressions, in other words, allows golifer syntax as we are able to save several \s

• -z puts all lines of input into one "line", so that they would be processed at the same time rather than the normal cyclic processing.

This was a fun challenge seeing as sed did not have any builtin sort functions. The program works as follows:

• copy the pattern space into the hold space
• find the position of the longest line by repeatedly removing the first character from every line until we are remaining with line(s) with only a single character, this first of these is at the position of the longest line
• to find which line this position corresponds to, we repeatedly

• remove the first line of the pattern space and hold space until we encounter a non-newline character on the first line of the pattern space
• now that the corresponding line is at the top of the hold space, we remove the other lines
• the contents of the buffer is printed at the end of the program

# Kotlin, 21 bytes

{it.maxBy{it.length}}


Try it online!

• I'm afraid that, if you don't count the whole function, it becomes a snippet, so it's invalid. – Erik the Outgolfer Dec 21 '18 at 21:23
• I've seen another kotlin answer somewhere else that did the same thing so I figured it might be valid; I'll switch it to a lambda – snail_ Dec 22 '18 at 4:45