|
| 1 | +/** |
| 2 | + * 3043. Find the Length of the Longest Common Prefix |
| 3 | + * https://leetcode.com/problems/find-the-length-of-the-longest-common-prefix/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given two arrays with positive integers arr1 and arr2. |
| 7 | + * |
| 8 | + * A prefix of a positive integer is an integer formed by one or more of its digits, starting |
| 9 | + * from its leftmost digit. For example, 123 is a prefix of the integer 12345, while 234 is not. |
| 10 | + * |
| 11 | + * A common prefix of two integers a and b is an integer c, such that c is a prefix of both a |
| 12 | + * and b. For example, 5655359 and 56554 have common prefixes 565 and 5655 while 1223 and 43456 |
| 13 | + * do not have a common prefix. |
| 14 | + * |
| 15 | + * You need to find the length of the longest common prefix between all pairs of integers (x, y) |
| 16 | + * such that x belongs to arr1 and y belongs to arr2. |
| 17 | + * |
| 18 | + * Return the length of the longest common prefix among all pairs. If no common prefix exists |
| 19 | + * among them, return 0. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @param {number[]} arr1 |
| 24 | + * @param {number[]} arr2 |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | +var longestCommonPrefix = function(arr1, arr2) { |
| 28 | + const prefixSet = new Set(); |
| 29 | + let result = 0; |
| 30 | + |
| 31 | + for (const num of arr1) { |
| 32 | + let prefix = num; |
| 33 | + while (prefix > 0) { |
| 34 | + prefixSet.add(prefix); |
| 35 | + prefix = Math.floor(prefix / 10); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + for (const num of arr2) { |
| 40 | + let prefix = num; |
| 41 | + while (prefix > 0) { |
| 42 | + if (prefixSet.has(prefix)) { |
| 43 | + result = Math.max(result, String(prefix).length); |
| 44 | + } |
| 45 | + prefix = Math.floor(prefix / 10); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + return result; |
| 50 | +}; |
0 commit comments