DEV Community

Discussion on: Find longest word in a given string

Collapse
 
avalander profile image
Avalander • Edited

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.