Skip to content

Welcome to Tech by Example

Menu
  • Home
  • Posts
  • System Design Questions
Menu

Longest Common Prefix in a set of strings

Posted on April 26, 2022April 26, 2022 by admin

Overview

An array of strings is given. The objective is to find the longest common prefix from that array of strings.  It should output an empty string if there is no common prefix.

Example 1

Input: ["fan", "fat", "fame"]
Output: "fa"

Example 2

Input: ["bat", "van", "cat"]
Output: ""

Program

Below is the program for the same

package main

import "fmt"

func longestCommonPrefix(strs []string) string {
	lenStrs := len(strs)

	if lenStrs == 0 {
		return ""
	}

	firstString := strs[0]

	lenFirstString := len(firstString)

	commonPrefix := ""
	for i := 0; i < lenFirstString; i++ {
		firstStringChar := string(firstString[i])
		match := true
		for j := 1; j < lenStrs; j++ {
			if (len(strs[j]) - 1) < i {
				match = false
				break
			}

			if string(strs[j][i]) != firstStringChar {
				match = false
				break
			}

		}

		if match {
			commonPrefix += firstStringChar
		} else {
			break
		}
	}

	return commonPrefix
}

func main() {
	output := longestCommonPrefix([]string{"fan", "fat", "fame"})
	fmt.Println(output)

	output = longestCommonPrefix([]string{"bat", "van", "cat"})
	fmt.Println(output)
}

Output:

"fa"
""

Note: Also, check out our system design tutorial series here – System Design Tutorial Series

©2025 Welcome to Tech by Example | Design: Newspaperly WordPress Theme