DEV Community

dev.to staff
dev.to staff

Posted on

4

Daily Challenge #298 - Find the Shortest Word

Given a string of words, return the length of the shortest word in the string.

Examples

find_short("bitcoin take over the world maybe who knows perhaps"), 3)
find_short("turns out random test cases are easier than writing out basic ones"), 3)

Tests

find_short("let us talk about javascript")
find_short("i want to travel the world writing code one day")
find_short("Lets all go on holiday somewhere very cold")

Good luck!


This challenge comes from A.Partridge on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Warp.dev image

Warp is the #1 coding agent.

Warp outperforms every other coding agent on the market, and gives you full control over which model you use. Get started now for free, or upgrade and unlock 2.5x AI credits on Warp's paid plans.

Download Warp

Top comments (8)

Collapse
 
alvaromontoro profile image
Alvaro Montoro

Here is a silly answer in the same spirit as the sorting by using time outs. The idea is, instead of trying to calculate/compare sizes, setting a timeout for each word with a delay equal to its length. The timeout callback will show the result and cancel the other timeouts.

Here is the code (demo with the code running on Codepen):

function find_short(str) {
  let timers = {};

  const removeTimers = () => {
    Object.keys(timers).forEach(el => clearTimeout(timers[el]));
  }

  const setTimer = word => {
    timers[word] = setTimeout(
      function() { 
        alert(`The shortest word has ${word.length} characters`);
        removeTimers();
      }, 
      word.length
    );
  };

  str.split(" ").forEach(word => setTimer(word));
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bugb profile image
bugb • Edited

nice, you are so creative!

Collapse
 
lizard profile image
Lizard

Here is an answer in python

def find_short(s: str) -> int:
    """
    Returns the length of the shortest word in the string s
    """
    lengths = map(lambda w: len(w), s.split())
    return min(lengths)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ruudgianesini profile image
Ruud Gianesini

Here is an answer in node (first time I write something in node :) ) :

function find_short(phrase: string) { 
 return phrase.split(' ').reduce( (p, c, i) => (i==0 || c.length < p.length) ? c : p)
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
celyes profile image
Ilyes Chouia • Edited

Here's the solution in PHP

Note: works only on 7.4+

function find_short(string $str): int
{
    $str = explode(' ', $str); // you can use preg_split('/\s/', $str);
    usort($str, fn($a, $b) => strlen($a) > strlen($b));
    return strlen($str[0]);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
peter279k profile image
peter279k

Here is the simple solution with PHP:

function findShort($str) {
  $freqLen = [];
  $strs = explode(' ', $str);
  foreach ($strs as $str) {
    $freqLen[] = strlen($str);
  }

  return min($freqLen);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
aminnairi profile image
Amin

Elm

import String exposing (words, length)
import List exposing (foldl)


shortestLength : String -> Length
shortestLength text =
    text
        |> words
        |> foldl (\a b -> if length a < length b then a else b) text
        |> length
Enter fullscreen mode Exit fullscreen mode
Collapse
 
bugb profile image
bugb • Edited

My js solution:

find_short=s=>Math.min(...s.split` `.map(v=>v.length))|0
Enter fullscreen mode Exit fullscreen mode

Tiger Data image

🐯 🚀 Timescale is now TigerData: Building the Modern PostgreSQL for the Analytical and Agentic Era

We’ve quietly evolved from a time-series database into the modern PostgreSQL for today’s and tomorrow’s computing, built for performance, scale, and the agentic future.

So we’re changing our name: from Timescale to TigerData. Not to change who we are, but to reflect who we’ve become. TigerData is bold, fast, and built to power the next era of software.

Read more

👋 Kindness is contagious

Discover fresh viewpoints in this insightful post, supported by our vibrant DEV Community. Every developer’s experience matters—add your thoughts and help us grow together.

A simple “thank you” can uplift the author and spark new discussions—leave yours below!

On DEV, knowledge-sharing connects us and drives innovation. Found this useful? A quick note of appreciation makes a real impact.

Okay