Longest Common Prefix

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Longest Common Prefix

Approach

Initialize prefix with the first string, then keep shrinking it until each remaining string starts with that prefix.

Complexity Analysis

Time
O(n * m)
Space
O(1)

Pattern

Prefix Reduction

Why It Works

The common prefix cannot be longer than the shortest mismatch point, so repeated shrinking converges to the maximal shared prefix.

Updated Feb 2026