| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 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.LongestCommonPrefix; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class LongestCommonPrefixBinarySearch : ILongestCommonPrefix |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(S log n), where S is the sum of all characters in all strings |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="strs"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public string LongestCommonPrefix(string[] strs) |
| 14 | 24 | | { |
| 52 | 25 | | var minLength = strs.Min(s => s.Length); |
| 14 | 26 | | var low = 1; |
| 14 | 27 | | var high = minLength; |
| | 28 | |
|
| 46 | 29 | | while (low <= high) |
| 32 | 30 | | { |
| 32 | 31 | | var middle = (low + high) / 2; |
| | 32 | |
|
| 32 | 33 | | if (IsCommonPrefix(strs, middle)) |
| 24 | 34 | | { |
| 24 | 35 | | low = middle + 1; |
| 24 | 36 | | } |
| | 37 | | else |
| 8 | 38 | | { |
| 8 | 39 | | high = middle - 1; |
| 8 | 40 | | } |
| 32 | 41 | | } |
| | 42 | |
|
| 14 | 43 | | var longestPrefixIndex = (low + high) / 2; |
| | 44 | |
|
| 14 | 45 | | return strs[0][..longestPrefixIndex]; |
| 14 | 46 | | } |
| | 47 | |
|
| | 48 | | private static bool IsCommonPrefix(IReadOnlyList<string> strs, int length) |
| 32 | 49 | | { |
| 32 | 50 | | var str1 = strs[0][..length]; |
| 160 | 51 | | for (var i = 1; i < strs.Count; i++) |
| 56 | 52 | | { |
| 56 | 53 | | if (!strs[i].StartsWith(str1)) |
| 8 | 54 | | { |
| 8 | 55 | | return false; |
| | 56 | | } |
| 48 | 57 | | } |
| | 58 | |
|
| 24 | 59 | | return true; |
| 32 | 60 | | } |
| | 61 | | } |