logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
Table Of Contents
13. Roman to Integer14. Longest Common Prefix20. Valid Parentheses26. Remove Duplicates from Sorted Array35. Search Insert Position69. Sqrt(x)70. Climbing Stairs88. Merge Sorted Array (In-Place)104. Maximum Depth of Binary Tree118. Pascal's Triangle121. Best Time to Buy and Sell Stock205. Isomorphic Strings242. Valid Anagram283. Move Zeroes345. Reverse Vowels of a String605. Can Place Flowers704. Binary Search796. Rotate String1071. Greatest Common Divisor of Strings1299. Replace Elements with Greatest Element on Right Side1431. Kids With the Greatest Number of Candies1614. Maximum Nesting Depth of the Parentheses1752. Check if Array Is Sorted and Rotated1768. Merge Strings Alternately1903. Largest Odd Number in String2965. Find Missing and Repeated Values
Code Scratch/leetcode/easy

14. Longest Common Prefix

1 min read
On this pageIntuition
IntuitionComplexityCode

# Intuition

To find the longest common prefix among all strings in an array, we can take advantage of comparing characters at each position across all strings.
Since we're looking for a common prefix from the beginning, the moment characters at a particular position don't match across strings, we can stop and return the prefix up to that point.

# Complexity

Space ComplexityTime Complexity
O(1)\text{O}(1)O(1)O(nm)\text{O}(nm)O(nm)

# Code

public String longestCommonPrefix(String[] words) {
    // Initialize the maximum possible common prefix length as the length of the first word
    int lastMatchingIndex = words[0].length();
 
    // Compare the first word with each of the other words
    for (int i = 1; i < words.length; ++i) {
        // Reduce the comparison length to the minimum length of both current and previous words
        lastMatchingIndex = Math.min(words[i].length(), lastMatchingIndex);
 
        // Compare characters one by one up to the last known matching index
        for (int j = 0; j < lastMatchingIndex; ++j) {
            if (words[0].charAt(j) != words[i].charAt(j)) {
                // Mismatch found; update the last matching index and break
                lastMatchingIndex = j;
                break;
            }
        }
    }
 
    // Return the longest common prefix from the first word
    return words[0].substring(0, lastMatchingIndex);
}
 
←Previous13. Roman to IntegerNext→20. Valid Parentheses

On this page

IntuitionComplexityCode