#3043

Find the Length of the Longest Common Prefix

Medium
ArrayHash TableStringTrieHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + m)
Space
O(1)
O(n)
💡

Intuition

Time O(n + m)Space O(n)

The optimal solution uses a HashSet to store all possible prefixes of integers in arr1. Then, it checks each integer in arr2 to see if any of its prefixes exist in the HashSet, allowing for efficient lookup.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a HashSet to store all prefixes of each integer in arr1.
  2. 2Step 2: For each integer in arr2, generate its prefixes and check if they exist in the HashSet.
  3. 3Step 3: Keep track of the maximum length of the common prefixes found.
solution.py21 lines
1# Full working Python code
2arr1 = [1, 10, 100]
3arr2 = [1000]
4
5def longest_common_prefix(arr1, arr2):
6    prefixes = set()
7    for x in arr1:
8        str_x = str(x)
9        for i in range(1, len(str_x) + 1):
10            prefixes.add(str_x[:i])
11
12    max_length = 0
13    for y in arr2:
14        str_y = str(y)
15        for i in range(1, len(str_y) + 1):
16            if str_y[:i] in prefixes:
17                max_length = max(max_length, i)
18
19    return max_length
20
21print(longest_common_prefix(arr1, arr2))

Complexity note: The time complexity is O(n + m) where n is the total number of digits in arr1 and m is the total number of digits in arr2. The space complexity is O(n) due to the HashSet storing prefixes from arr1.

  • 1Using a HashSet allows for O(1) average time complexity for lookups.
  • 2Generating prefixes efficiently reduces the number of comparisons needed.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.