0

I came across this code. It scans through the array elements only once. But I am confused regarding having two nested while loops increase the complexity to O(n^2). The code is as follows:

def summaryRanges(nums):
    x, size = 0, len(nums)
    ans = []
    while x < size:
        c, r = x, str(nums[x])
        while x + 1 < size and nums[x + 1] - nums[x] == 1:
            x += 1
        if x > c:
            r += "->" + str(nums[x])
        ans.append(r)
        x += 1
    return ans

I am learning algorithms so please correct me if I am going wrong somewhere. Thank you!!

1 Answer 1

1

Your question isn't 100% clear, but if you meant why is this NOT O(N^2) while having nesting loops then:

Although there are nesting loops, they operate on the same space using the same variable to advance the iteration. since the inner loop doesn't backtrack, and whenever it moves ahead it also pushes the outer loop ahead (at the exact same distance), the iteration won't grow larger then M if N grows by M (If N1 = N0 + M). O(N^2) means that as N grows, the iteration grows exponentially.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.