0

This code does search of the right boundary in an ordered set of phrases. Program works correctly in VS, but special compiler on web-site gives an error "time limit exceeded". It means the code has to work faster. Could you help me with improving the code?

using System;
using System.Collections.Generic;
using System.Linq;

namespace Autocomplete
{
    public class RightBorderTask
    {
        public static int GetRightBorderIndex(IReadOnlyList<string> phrases, string prefix, int left, int right)
        {
            if (phrases.Count == 0 || string.Compare(prefix, phrases[right-1], StringComparison.OrdinalIgnoreCase) > 0)
                return phrases.Count;
            while (left < right)
            {
                var middle = (right - left) / 2;
                if (string.Compare(prefix, phrases[middle], StringComparison.OrdinalIgnoreCase) < 0)
                    right = middle;
                else left = middle + 1;
            }
            return right;          
        }     
    }
}
Nike
  • 3
  • 1
  • Check the link, on that link multiple string comparison strategies are described. So, use the best fitted one for you. For example : MSDN says "The CompareTo method was designed primarily for use in sorting or alphabetizing operations. It should not be used when the primary purpose of the method call is to determine whether two strings are equivalent. To determine whether two strings are equivalent, call the Equals method" https://stackoverflow.com/questions/859005/string-comparison-performance-in-c-sharp – Nowshad Rahaman Apr 12 '20 at 15:33

1 Answers1

0

Use String.Equals() method instead of string.Compare().