educative.io

Educative

Question has Some Bug - Need to Check Swap Location

If you log out the array swapped you see the following modification
nums [ 4, 2, 1, 2 ]
nums [ 2, 2, 1, 4 ]
nums [ 2, 3, 2, 1 ]
nums [ 3, 2, 2, 1 ]
nums [ 2, 2, 3, 1 ]

The array is perminantly changed, added a 3 and deleted the 4 somehow. I think what we need to do is add a check that "skips"a swap if the swap location is already correct.


Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Find all Missing Numbers (easy) - Grokking the Coding Interview: Patterns for Coding Questions

Hi Bryan
We’re swapping the elements of the array only when they’re at not at correct indices using if nums[i] != nums[j]: conditional statement. If the element is at correct index, we simply move forward by incrementing the index i (i.e., we’re not swapping the elements here).

Here’s the coded solution that is being used in this lesson (with few additional printing statements here):

def find_missing_numbers(nums):
  i = 0
  while i < len(nums):
    j = nums[i] - 1
    if nums[i] != nums[j]:
      nums[i], nums[j] = nums[j], nums[i]  # swap
      print("if : ", nums)
    else:
      print("incrementing index..")
      i += 1

  missingNumbers = []

  for i in range(len(nums)):
    if nums[i] != i + 1:
      missingNumbers.append(i + 1)

  return missingNumbers


def main():

  print(find_missing_numbers([2, 4, 1, 2]))

main()

You can run this code to verify the swapping instances.

Hope this helps. If you still have any confusion, please let us know.
Thank you!