Find longest word in a given string

abhidon profile image Abhinay Donadula ・1 min read

Photo by Magdalena Kula Manchee on Unsplash


  1. Create a function that takes a parameter and returns longest word in that parameter
  2. Let's assume that this function will always get's a string as it's parameter

My Solution

code snippet


markdown guide

Same thing, but using a reducer instead of sorting.

const getLongestWordOf = (sentence = '') => {
  return sentence
    .split(' ')
    .reduce((longest, current) => {
      return current.length > longest.length ? current : longest;


getLongestWordOf('I am just another solution to the same problem');

EDIT: This approach seems to be faster than the sorting one! jsperf.com/longestwordjs/1


This is what I thought to do as well 😄


Good one, didn't think of reduce 👏

DECLARE longest_word TEXT;
  SELECT strs INTO longest_word
  FROM regexp_split_to_table(val, '\s+') AS strs
  ORDER BY char_length(strs) DESC
  LIMIT 1;

  RETURN longest_word;
$$ LANGUAGE plpgsql;

SELECT get_longest_word('a bc def ghij klm no p');

I know one of the tags is 'Javascript' but here is how I would do it in Python:

def get_longest_word(sentence):
    return max(sentence.split(' '), key=lambda x: len(x))

get_longest_word('Iam a verrrrry loooongggg sentence')
# result: loooongggg


Can I chime in with a quick C# and LINQ one liner?

private Longest(string sentance) 
     return sentance.Split(' ').OrderByDescending(l => l.Length).FirstOrDefault();

Well, the return statement is a one liner :)


Recently started digging my way through GHC libraries

import Data.List

cmpLength :: String -> String -> Ordering
cmpLength l r = compare (length r) (length l)

findLongest :: String -> String
findLongest s = head . sortBy (cmpLength) . words $ s

main :: IO ()
main = do
  putStrLn (findLongest "Iam a verrrrry loooongggg sentence")
import Data.List

longerString :: String -> String -> String
longerString l r = if length l > length r then l else r

findLongest :: String -> String
findLongest s = foldr (\longest w -> longerString longest w) "" (words s)

main :: IO ()
main = do
  putStrLn (findLongest "Iam a verrrrry loooongggg sentence")


$_=qq|Iam a verrrrryyy longggggggg sentence|;
print( (sort{length($b) <=> length($a)} split(qq|\s|))[0])


package main

import (

func main() {
    s := "Iam a verrrrryyy longggggggg sentence"
    b := ""
    for _, w := range strings.Split(s, " ") {
        if len(w) > len(b) {
            b = w



When used according to the specification, this function has O(1) complexity*.

/** @function getLongestWord
 * @param {String} s a string of words with the longest word in the first position.
 * @returns the longest word in a string, if it is the first word in the string, or a random word that occupies the first position in the string otherwise.
const getLongestWord => (s = '') => s.split(' ')[0]

getLongestWord('loooongggg sentence very Iam') // 'loooongggg'

* It doesn't because split probably has complexity O(n) or something.


It may not be the most eye perfect code however the perf are close to the reducer solution jsperf.com/longestwordjs/11


I would still go to with the reducer solution, but sometimes doing 'old' things works very nice

I also try with for loop / for of, I expected it to be way more faster than everything else but it didn't.

from jsperf.com/foreach-vs-reduce-vs-fo...


Learned something new regarding jsperf, thank you. 🙏


Ignoring punctuation and only considering spaces... ruby solution:

def longest_word(str)