Help - Not sure why my code times out during submission but not testing

  • 0

    When I run my code on the problem page with the same very long test string that is used by the submission grader, I am getting runtime of around 90ms. However, when I submit my code, for the same test case, it gets time limit exceeded.

    I'm thinking that it may have something to do with clearing the HashMap, but why would it exceed time when submitting vs passing finely with ~ 90ms runtime when I run the code on the LeetCode problem page?

    I understand there are faster solutions, but I'm more interested in the inconsistent behavior. My reasoning for not having a fixed sized container such as a char array was because I did not know what the input space was originally. The more optimal solutions on leetcode are similar in concept to this algorithm here with the HashMap.

    public int lengthOfLongestSubstring(String s)
            char[] charArray = s.toCharArray();
            Map<Character, Integer> charIndexMap = new HashMap<Character, Integer>();
            int longestSubstring = 0;
            for (int i = 0; i < charArray.length; i++)
                char ci = charArray[i];
                charIndexMap.put(ci, i);
                int currSubstringLength = 1;
                for (int j = i + 1; j < charArray.length; j++)
                    char cj = charArray[j];
                    if (!charIndexMap.containsKey(cj))
                        charIndexMap.put(cj, j);
                        i = charIndexMap.get(cj);
                longestSubstring = Math.max(currSubstringLength, longestSubstring);
            return longestSubstring;

    Interestingly, this passes submission perfectly fine when I switch the data structure from HashMap to a HashSet with a run time of around 110ms.


Log in to reply

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