C# code encountered Time Limit Exceeded error


  • 0
    K

    Can anyone help me figure it out what's wrong with this C# code? I got the Time Limit Exceeded error when I submit. Thank you!

    public class Solution
        {
            public int LengthOfLongestSubstring(string s)
            {
                if (string.IsNullOrEmpty(s)) return 0;
                char[] characters = s.ToCharArray();
                bool test = false;
                for (int l = s.Length; l > 1; l--)
                {
                    for (int i = 0; i < s.Length + 1 - l; i++)
                    {
                        for (int m = i; m < i + l - 1; m++)
                        {
                            for (int n = m + 1; n < i + l; n++)
                            {
                                if (characters[m] == characters[n])
                                {
                                    test = true;
                                    break;
                                }
                            }
                            if (test)
                            {
                                test = false;
                                break;
                            }
                            if (m == i + l - 2) return l;
                        }
                    }
                }
                return 1;
            }
        }
    

  • 0
    X

    @Kyle Try not to use so many "for" loops in one for loop, they tend to get you Time Limit Exceeded errors. Each testcase has a time limit, and since you are using 4 for loops, by the time the 3rd for loop reaches its first few loops on the first and the second for loops' first loop, the time will definitely run out. So minimizing the time that your code takes to return a value is key to every algorithm you do.


  • 0
    K

    @xVekkix Thank u very much. I'll try to modify it.


Log in to reply
 

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