Longest common prefix

Beginner Problems Basic Strings Easy
  • Fun Fact: The problem of finding the longest common prefix among an array of strings is often used in the field of autocompletion and suggestion engines, which are quite prevalent in search engines, IDEs (Integrated Development Environments), and so on
  • When a user starts typing something, these engines use the longest common prefix algorithm to generate relevant and instant suggestions to the user based on historical and contextual data
  • Such functionalities optimize the user experience and efficiency in using the software application

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 "".

Examples:

Input : str = ["flowers" , "flow" , "fly", "flight" ]

Output : "fl"

Explanation : All strings given in array contains common prefix "fl".

Input : str = ["dog" , "cat" , "animal", "monkey" ]

Output : ""

Explanation : There is no common prefix among the given strings in array.

Input : str = ["lady" , "lazy"]

Constraints

  • 1 <= str.length <= 200
  • 1 <= str[i].length <= 200
  • str[i] contains only lowercase English letters.

Company Tags

TCS Cognizant Accenture Infosys Capgemini Wipro IBM HCL Tech Mahindra MindTree