#need help finding runtime of lc solution

1 messages · Page 1 of 1 (latest)

frosty holly
#

Hello, I got a solution for lc 977 but need to check if its O(n) or O(n^2) and im really confused...
here is my code:

    public int[] sortedSquares(int[] nums) {
        int numNeg = 0;
        int numPos = 0;

        int p = 0;

        while (p < nums.length && nums[p] < 0) {
            numNeg++;
            p++;
        }

        numPos = nums.length - numNeg;

        int[] negArr = new int[numNeg];
        int[] posArr = new int[numPos];

        for (int i = 0; i < numNeg; i++) {
            negArr[i] = nums[i] * nums[i];
        }

        for (int i = numNeg; i < nums.length; i++) {
            posArr[i-numNeg] = nums[i] * nums[i];
        }

        int i = negArr.length - 1;
        int j = 0;

        int[] res = new int[nums.length];
        int curr = 0;

        while (i >= 0 && j < posArr.length) {
            if (negArr[i] < posArr[j]) {
                res[curr] = negArr[i];
                i--;
            } else {
                res[curr] = posArr[j];
                j++;
            }
            curr++;
        }

        if (i < 0) {
            while (j < posArr.length) {
                res[curr] = posArr[j];
                curr++;
                j++;
            }
        } else if (j >= posArr.length) {
            while (i >= 0) {
                res[curr] = negArr[i];
                curr++;
                i--;
            }
        }

        return res;
    }
}```
frosty holly
#

but the problem states the entire solution can be done in O(n) and encourages to try that

#

yeah it is, i just implemented it a diff way by separating the negative and positive elements and then a pointer for each and comparing

frosty holly
#

thanks, do you think my original solution above is O(n)? if not, why ?

#

my reasoning for why its O(n)

#

each element is visited a constant num of times

#

it isnt visited n times where n is length of array