Skip to content

Commit f1f4f70

Browse files
committed
Add solution #3043
1 parent 9c7788b commit f1f4f70

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2146,6 +2146,7 @@
21462146
3038|[Maximum Number of Operations With the Same Score I](./solutions/3038-maximum-number-of-operations-with-the-same-score-i.js)|Easy|
21472147
3039|[Apply Operations to Make String Empty](./solutions/3039-apply-operations-to-make-string-empty.js)|Medium|
21482148
3042|[Count Prefix and Suffix Pairs I](./solutions/3042-count-prefix-and-suffix-pairs-i.js)|Easy|
2149+
3043|[Find the Length of the Longest Common Prefix](./solutions/3043-find-the-length-of-the-longest-common-prefix.js)|Medium|
21492150
3066|[Minimum Operations to Exceed Threshold Value II](./solutions/3066-minimum-operations-to-exceed-threshold-value-ii.js)|Medium|
21502151
3068|[Find the Maximum Sum of Node Values](./solutions/3068-find-the-maximum-sum-of-node-values.js)|Hard|
21512152
3105|[Longest Strictly Increasing or Strictly Decreasing Subarray](./solutions/3105-longest-strictly-increasing-or-strictly-decreasing-subarray.js)|Easy|
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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

Comments
 (0)