| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | namespace LeetCode.Algorithms.FindTheLengthOfTheLongestCommonPrefix; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class FindTheLengthOfTheLongestCommonPrefixBruteForce : IFindTheLengthOfTheLongestCommonPrefix |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n * m * d), where n is the length of arr1, m is the length of arr2, d is the average num |
| | | 19 | | /// digits in the numbers of arr1 and arr2 |
| | | 20 | | /// Space complexity - O(1) |
| | | 21 | | /// </summary> |
| | | 22 | | /// <param name="arr1"></param> |
| | | 23 | | /// <param name="arr2"></param> |
| | | 24 | | /// <returns></returns> |
| | | 25 | | public int LongestCommonPrefix(int[] arr1, int[] arr2) |
| | 7 | 26 | | { |
| | 7 | 27 | | return arr1.Aggregate(0, |
| | 104 | 28 | | (current, num1) => arr2.Select(num2 => GetCommonPrefixLength(num1, num2)).Prepend(current).Max()); |
| | 7 | 29 | | } |
| | | 30 | | |
| | | 31 | | private static int GetCommonPrefixLength(int num1, int num2) |
| | 75 | 32 | | { |
| | 75 | 33 | | var str1 = num1.ToString(); |
| | 75 | 34 | | var str2 = num2.ToString(); |
| | | 35 | | |
| | 75 | 36 | | var minLength = Math.Min(str1.Length, str2.Length); |
| | | 37 | | |
| | 252 | 38 | | for (var i = 0; i < minLength; i++) |
| | 115 | 39 | | { |
| | 115 | 40 | | if (str1[i] != str2[i]) |
| | 64 | 41 | | { |
| | 64 | 42 | | return i; |
| | | 43 | | } |
| | 51 | 44 | | } |
| | | 45 | | |
| | 11 | 46 | | return minLength; |
| | 75 | 47 | | } |
| | | 48 | | } |