What will be the time complexity of this function?

时间:2018-02-03 08:29:00

标签: java algorithm analysis

This is the function to check the string of pattern a^nb^n.

Input : str = "aabb" Output : Yes

Input : str = "abab" Output : No

Input : str = "aabbb" Output : No

Can someone please help determine the time complexity? As the loop will run n/2 times , is it still linear ?

 public static boolean isAnBn(String s)
    {
        int l = s.length();

        // Only even length strings will have same number of a's and b's
        if (l%2 == 1)
        {
            return false;
        }
        // Set two pointers, one from the left and another from right
        int i = 0;
        int j = l-1;

        // Compare the characters till the center
        while (i<j)
        {
            if(s.charAt(i) != 'a' || s.charAt(j) != 'b')
            {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }

2 个答案:

答案 0 :(得分:0)

Yes, it will still be linear time. In the worse case, you'll have to go through each character if i is never equal to 'a' or j is never 'b'. When it comes to big O think about the worse case. I hope that helps.

答案 1 :(得分:0)

Complexity is O(n).

Don't be confused about n/2. Constant values, 1/2 in your case, should be ignored.

For example:

  • n/2 = O(n)
  • 3n = O(n)
  • 10000000n = O(n)
  • etc..
相关问题