Big O of my solution

  • 0

    Is my accepted code below big O(n)? Thanks in advance!

    string longestCommonPrefix(vector<string>& strs) {
            if(strs.size() == 0) return "";
            sort(strs.begin(), strs.end());
            string prefix = strs[0];
            int length = prefix.length();
            for (int i = 0; i < strs.size(); ++i) {
                if (prefix == strs[i].substr(0, length)) continue;
                if (prefix != strs[i].substr(0, length)) {
                    prefix = prefix.substr(0, --length);
                    length = prefix.length();
                    i = 0;
                if (prefix == "") break;
            return prefix;

  • 0

    @rtmitchell5 said in Big O of my solution:

    Is my accepted code below big O(n)?

    Depends on what you mean with n.

  • 0

    @StefanPochmann For n I mean the size of the strs vector. I'm a little shaky with algorithm analysis, so I'm not too sure on this one.

Log in to reply

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