Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do String methods in Java run in O(1) time?

This is my code to find the length of the longest substring without repeating characters. Does this code run in O(n) time? Or does it run in O(n^2) time? I am not sure if the String methods run in O(n) time or O(1) time.

A test case includes: "pwwkewo" returning 4 because "kewo" is the the longest substring inside the string that has unique characters.

public int lengthOfLongestSubstring(String s) {

    int maxLength = 0;
    String sub = "";

    for(int i=0; i<s.length(); i++) {

         //add that char to the sub string
         sub = sub + s.charAt(i);

        //if we find a char in our string
        if(sub.indexOf(s.charAt(i)) != -1) {

           //drop any replicated indexes before it
            sub = sub.substring(sub.indexOf(s.charAt(i)) + 1);
        }

        if(sub.length() > maxLength) {
            maxLength = sub.length();
        }


    }

    return maxLength;

}
like image 531
Kousei Avatar asked Dec 07 '25 09:12

Kousei


1 Answers

sub.indexOf() can take linear time, since it might have to check all the characters of sub. And the length of sub is O(n) in the worst case (assuming your input has no repeating characters).

Therefore your total running time is O(n2), since the loop has n iterations and in each iteration you call indexOf().

like image 74
Eran Avatar answered Dec 08 '25 21:12

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!