You should simplify this to exist early and avoid doing needless work, that way this method's complexity is greatly reduced before you actually have to do something.