1

input = [10, 9, 7, 18, 13, 19, 4, 20, 21, 14]
Output : 10 9 18 7 20 19 4 13 14 21

def fixing(arr):
    oddIdx = 1
    evenIdx = 0
    while True:
        while evenIdx < len(arr) and arr[evenIdx] %2 ==0:
            evenIdx +=2
        while oddIdx < len(arr) and arr[oddIdx] % 2!=0:
            oddIdx+=2
        if evenIdx < len(arr) and oddIdx < len(arr):
            arr[evenIdx], arr[oddIdx] = arr[oddIdx], arr[evenIdx]
        else:
            break
    return arr

Is it because we are not ignoring the outer loop? If yes, why and if not, why not? Thank you!

2 Answers 2

3

Lets break it down.

The condition for the while True depends on evenIdx < len(arr) and oddIdx < len(arr).

So the outer loop will not iterate more than O(N) where N=len(arr).

But what about the inner loops?

Lets consider the options here:

  1. We only have 1 outer loop iteration where inner functions advance evenIdx and oddIdx to the point where we break. So overall O(N).
  2. The outer loop iterate K times. But evenIdx and oddIdx do not reset. In iteration 1, evenIdx/oddIdx get to somewhere between 0 to N, iteration 2 they still continue to advance, same for iteration 3 up to iteration K. Eventually evenIdx/oddIdx advanced O(N) times. So again O(N).

There is a more strict analysis that can be done but it is still O(N).

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

Comments

1

It's because you don't reset evenIdx or oddIdx back to 0 each time through the outer loop. Each time the outer loop repeats, the inner loops start from where they left off the previous time.

So you don't perform multiple iterations over the list -- you break out of the outer loop as soon as both inner loops reach the end. And each inner loop only visits the even or odd elements once.

2 Comments

How do you know that the inner loops reach the end?
If the inner loops haven't reached the end, the if statement swaps the even and odd elements. That means that the even/odd tests that failed on the previous iteration will succeed, so it will increment the indexes again. Eventually this process will reach the end.

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.