~/coding-interview/leetcode-longest-common-prefix.md

Longest Common Prefix - Leet Code Solution

// TL;DR

Take the first string as the prefix, then shorten it character by character until it matches the start of every other string. O(S) where S is total characters across all strings.

Longest Common Prefix - Leet Code Solution

Problem Statement

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:
	Input: ["flower","flow","flight"]
	Output: "fl"

Example 2:
	Input: ["dog","racecar","car"]
	Output: ""

Note: All given inputs are in lowercase letters a-z.

Solution-1

Lets look at a simple solution, where we will look in entire strings for the match.

  1. We have to search in all strings
  2. Lets take length of first string. Result can not be greater than the length of smallest string. We are just taking first string.
  3. Now, iterate to this length.
    • Take first character of first string
    • Iterate over all strings
    • And, match that character from first string in all other strings
    • If matched, append it to our result.
    • Else, just break down.
public String longestCommonPrefix(String[] strs) {
	int strsLen = strs.length;
	if (strsLen == 0) {
		return "";
	}
	int l = strs[0].length();
	
	StringBuffer sb = new StringBuffer();
	for (int i=0; i<l; i++) {
		char ch = strs[0].charAt(i);
		boolean matched = true;
		for (int j=1; j<strsLen; j++) {
			if (i >= strs[j].length() || ch != strs[j].charAt(i)) {
				matched = false;
				break;
			}
		}
		if (!matched) {
			break;
		}
		sb.append(ch);
	}
	
	return sb.toString();
}

Solution-2

We can use divide and conquer, and then merge the result. Since, common of two strings will be eligible to match from other strings.

  • Divide the string array, untill it remains single
  • Then, merge such single strings. Means, just find longest common prefix in these two strings.
  • In subsequent recursion, we will be comparing two common prefixes with each other.
  • Recursively do this, and combine results in the end.
public String longestCommonPrefix(String[] strs) {
	if (strs.length == 0) return "";
    return helper(strs, 0, strs.length-1);
}

private String findRes(String l, String r) {
    int len = Math.min(l.length(), r.length());
    int i=0;
    for (; i<len; i++) {
        if (l.charAt(i) != r.charAt(i)) {
            break;
        }
    }

    return l.substring(0, i);
}
private String helper(String[] strs, int l, int r) {
    if (l == r) return strs[l];

	int m = (l+r)/2;
	String left = helper(strs, l, m);
	String right = helper(strs, m+1, r);

	return findRes(left, right);
}

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

Leetcode Solution - Best Time to Buy and Sell Stock

Leetcode Solution - Best Time to Buy and Sell Stock

Problem Statement You are given an array prices where prices[i] is the price of…

Binary Tree - Level Order Traversal

Binary Tree - Level Order Traversal

Problem Statement Given a Binary tree, print out nodes in level order traversal…

Four Sum - Leet Code Solution

Four Sum - Leet Code Solution

Problem Statement Given an array nums of n integers and an integer target, are…

Leetcode - Rearrange Spaces Between Words

Leetcode - Rearrange Spaces Between Words

Problem Statement You are given a string text of words that are placed among…

Leetcode - Maximum Non Negative Product in a Matrix

Leetcode - Maximum Non Negative Product in a Matrix

Problem Statement You are given a rows x cols matrix grid. Initially, you are…

Leetcode - Split a String Into the Max Number of Unique Substrings

Leetcode - Split a String Into the Max Number of Unique Substrings

Problem Statement Given a string s, return the maximum number of unique…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…