简体   繁体   中英

What is the space complexity of below method?

I would like to understand space complexity for below method. I tried simplest approach myself. Time complexity is O(n). Unable to determine whether space complexity is O(1) or O(n) as I am reassigning a (string) in every iteration.

    public boolean anagram2(String a, String b) {
        if (a.length() != b.length()) {
            return false;
        }

        for (int i = 0; i < a.length(); i++) {
            if (a.contains("" + b.charAt(i))) {
                a = a.replace("" + b.charAt(i), "");
            }
        }

        return a.length() == 0;
    }

Can you also please explain difference between space complexity and auxiliary space?

They are all destroyed at the end, but the space complexity would be the maximum amount of space needed at any point while the algorithm is running.

You're creating a new string for each iteration, using O(n) space. Only one of them needs to be kept in memory at a time, so the total space complexity would be O(n) .

As they already said, space complexity seems O(1) since no additional variables are used and, even if you reassign a string at each iteration, the previous one is not anymore tracked and gets destroyed at the end of the iteration.

Edit: After @Henry comment, I thought at it a but more and I agree with him, the space complexity seems O(n) since at each iteration you are creating a new string of variabile length in relation to the previous string and assigning it to a variable.

But, I want to point out that the time complexity is not O(n) as you said. Even if you have a single loop, the methods contains and replace aren't costing only O(1), such methods search / work on the whole string and as such, every time you use one, it costs O(a) where a is the length of the string the method is working on. For this reason, the cost is more approximable at O(n * n)

Usually for what I remember, search, replace, sum operations on strings does not cost O(1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM