Given a list of strings, return the longest common prefix shared by all strings. If there is no common prefix, return an empty string. If the input list is null, return null. If the input list is empty, return an empty string. A list containing a single element returns that element as the prefix.

Examples:

Input: strs = ['flower', 'flow', 'flight'] Output: 'fl' Explanation: All three strings start with fl. Input: strs = ['dog', 'racecar', 'car'] Output: '' Explanation: There is no shared prefix among the strings. Input: strs = ['interspecies', 'interstellar', 'interstate'] Output: 'inters' Explanation: The longest shared prefix is inters. Input: strs = ['alone'] Output: 'alone' Explanation: A single string is its own longest prefix. Input: strs = null Output: null Explanation: Null input returns null.
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 August 2026

Contest runs August 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.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In