Find the longest word
Find the longest alphanumeric word in a sentence. If several words tie, return the first one.
Course progress
Problem 60 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
text = "Practice small coding problems daily."
Expected output
Practice
What is happening?
Practice and problems both have eight characters. Because ties return the first longest word, Practice is selected.
Solution strategy
Build the right mental model
Track the start and length of the current word, updating the best slice whenever a word ends and is longer than the previous best.
Core concepts
strings · linear scan
Complexity
Time O(n), space O(1) excluding the returned string.
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for find-longest-word
using System;
class Program
{
static string LongestWord(string text)
{
int bestStart = 0, bestLength = 0, currentStart = 0, currentLength = 0;
for (int i = 0; i <= text.Length; i++)
{
if (i < text.Length && char.IsLetterOrDigit(text[i]))
{
if (currentLength == 0) currentStart = i;
currentLength++;
}
else
{
if (currentLength > bestLength) { bestStart = currentStart; bestLength = currentLength; }
currentLength = 0;
}
}
return text.Substring(bestStart, bestLength);
}
static void Main()
{
Console.WriteLine(LongestWord("Practice small coding problems daily."));
}
}Knowledge check
Questions students often ask
What is the main idea behind find the longest word?
Track the start and length of the current word, updating the best slice whenever a word ends and is longer than the previous best.
What is the time and space complexity of this solution?
Time O(n), space O(1) excluding the returned string.
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.