-
Notifications
You must be signed in to change notification settings - Fork 0
/
lenOfLongestCommonPrefix.py
29 lines (23 loc) · 1.16 KB
/
lenOfLongestCommonPrefix.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
'''
Q. - You are given two arrays with positive integers arr1 and arr2.
A prefix of a positive integer is an integer formed by one or more of its digits, starting from its leftmost digit. For example, 123 is a prefix of the integer 12345, while 234 is not.
A common prefix of two integers a and b is an integer c, such that c is a prefix of both a and b. For example, 5655359 and 56554 have common prefixes 565 and 5655 while 1223 and 43456 do not have a common prefix.
You need to find the length of the longest common prefix between all pairs of integers (x, y) such that x belongs to arr1 and y belongs to arr2.
Return the length of the longest common prefix among all pairs. If no common prefix exists among them, return 0.
'''
Solution - Loops and conditionals logic
class Solution:
def longestCommonPrefix(self, arr1: List[int], arr2: List[int]) -> int:
s = set()
for x in arr1:
while x:
s.add(x)
x //= 10
ans = 0
for x in arr2:
while x:
if x in s:
ans = max(ans, len(str(x)))
break
x //= 10
return ans