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;          
        }     
    }
}
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" stackoverflow.com/questions/859005/… Commented Apr 12, 2020 at 15:33

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

2 Comments

Operator '>' cannot be applied to operands of type 'bool' and 'int'
@Nike, you can rewrite your algorithm using the String.Equal() method if you intention is only equality check

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.