Timeout For my C# solution, not sure how to further optimize it.

  • 0

    Hello, I was wondering if anyone can help me determine why I am getting a timeout for my solution below. It seems to me an optimal solution, but I am sure there are ways to make it faster. Can anyone see where there may be a bottleneck in the implementation?

        public int LengthOfLongestSubstring(string s) {
            int subLen = s.Length;
            while(subLen > 0)
                for (int i=0; i < s.Length; i++)
                    if (subLen > s.Length - i) break;
                    string sub = s.Substring(i, subLen);
                    bool hasRepeats = HasRepeats(sub);
                    //Console.WriteLine("{0} has repeats: {1}", sub, hasRepeats);
                    if (!hasRepeats) return subLen;
            return 0;
        private bool HasRepeats(string sub)
            int index = 0;
            var dict = new Dictionary<char, int>();
            foreach(char c in sub)
                int ival;
                dict.TryGetValue(c, out ival);
                if (ival == 0)
                    dict[c] = 1;
                else return true;
            return false;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.