< Summary

Information
Class: LeetCode.Algorithms.LongestCommonPrefix.LongestCommonPrefixBinarySearch
Assembly: LeetCode
File(s): D:\a\LeetCode-CS\LeetCode-CS\source\LeetCode\Algorithms\LongestCommonPrefix\LongestCommonPrefixBinarySearch.cs
Line coverage
100%
Covered lines: 28
Uncovered lines: 0
Coverable lines: 28
Total lines: 61
Line coverage: 100%
Branch coverage
100%
Covered branches: 8
Total branches: 8
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
LongestCommonPrefix(...)100%44100%
IsCommonPrefix(...)100%44100%

File(s)

D:\a\LeetCode-CS\LeetCode-CS\source\LeetCode\Algorithms\LongestCommonPrefix\LongestCommonPrefixBinarySearch.cs

#LineLine coverage
 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
 12namespace LeetCode.Algorithms.LongestCommonPrefix;
 13
 14/// <inheritdoc />
 15public 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)
 1424    {
 5225        var minLength = strs.Min(s => s.Length);
 1426        var low = 1;
 1427        var high = minLength;
 28
 4629        while (low <= high)
 3230        {
 3231            var middle = (low + high) / 2;
 32
 3233            if (IsCommonPrefix(strs, middle))
 2434            {
 2435                low = middle + 1;
 2436            }
 37            else
 838            {
 839                high = middle - 1;
 840            }
 3241        }
 42
 1443        var longestPrefixIndex = (low + high) / 2;
 44
 1445        return strs[0][..longestPrefixIndex];
 1446    }
 47
 48    private static bool IsCommonPrefix(IReadOnlyList<string> strs, int length)
 3249    {
 3250        var str1 = strs[0][..length];
 16051        for (var i = 1; i < strs.Count; i++)
 5652        {
 5653            if (!strs[i].StartsWith(str1))
 854            {
 855                return false;
 56            }
 4857        }
 58
 2459        return true;
 3260    }
 61}