Given a sentence, return the longest word. If two words have the same length, return the first one encountered. Return an empty string for empty input and null for null input.
Examples:
Input: sentence = 'Hello world goodbye'
Output: 'goodbye'
Explanation: goodbye has 7 characters, the longest in the sentence
Input: sentence = 'cat dog elephant'
Output: 'elephant'
Explanation: elephant has 8 characters, the longest
Input: sentence = 'I am a student'
Output: 'student'
Explanation: student has 7 characters, the longest
Input: sentence = ''
Output: ''
Explanation: Empty string returns empty string
Input: sentence = 'hello'
Output: 'hello'
Explanation: Single word returns that word
Apex Code Editor
Welcome to Lightning Challenge!
How It Works
- • Write your solution in the code editor
- • Connect your Salesforce org to test
- • Submit to check if your solution passes
- • Use hints if you get stuck
Contest Alert
🏆 #CodeEveryDay July 2026
Contest runs July 1 - 31. Complete challenges to climb the leaderboard!
Only the 31 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.