Similar Problems

Similar Problems not available

Find The Prefix Common Array Of Two Arrays - Leetcode Solution


LeetCode:  Find The Prefix Common Array Of Two Arrays Leetcode Solution

Difficulty: Medium

Topics: hash-table bit-manipulation array  

Problem statement:

Given two arrays A and B, find the longest common prefix of the two arrays. The prefix should be a non-empty string and it should be same for both A and B.

Example 1: Input: A = [“flower”, “flow”, “flight”], B = [“flower”, “flow”, “flight”] Output: “fl”

Example 2: Input: A = [“dog”, “racecar”, “car”], B = [“dog”, “racecar”, “car”] Output: “”


One of the simplest and easiest approach is to find the minimum length among the two arrays and use a loop from 0 to that minimum length to compare each corresponding character of the two arrays. If there is any mismatch at any index then we found the maximum prefix length up to that point and we can return the prefix. If there is no mismatch then we can return the whole minimum length string.


class Solution: def longestCommonPrefix(self, A: List[str], B: List[str]) -> str: # Initialize prefix prefix = "" # Find minimum array length min_len = min(len(A), len(B)) # Loop from 0 to min_len and compare each character for i in range(min_len): if A[i] != B[i]: # If there is any mismatch, return the prefix up to that point return prefix # Append the common character to the prefix prefix += A[i] # If all the characters are same in both arrays upto that point, # then return the whole prefix string return prefix

Time Complexity:

The time complexity of the above solution is O(min(n,m)), where n and m are the lengths of the two arrays, A and B. This is because we are only looping through the minimum number of elements in both arrays.

Space Complexity:

In this algorithm, we are only using a constant amount of extra space to store the prefix string and the minimum length of the two arrays. Therefore, the space complexity is O(1).

Find The Prefix Common Array Of Two Arrays Solution Code