Space
Open
From Fieldwork
Scales
Archive
Easy is obviously to just take a set and then iterate through to check what's not in it, but the other way is to treat it like "Find All Duplicates in an Array," which is essentially the inverse of this problem. It uses the exact same trick — using the array indices as a hash map — but you check for the condition at a different time.
class Solution:
def findDisappearedNumbers(self, nums):
# Pass 1: Mark existing numbers by negating values at the corresponding index
for n in nums:
# We use abs() because the number might have been negated already by a previous step
idx = abs(n) - 1
# Only negate if it's currently positive
if nums[idx] > 0:
nums[idx] *= -1
# Pass 2: Collect indices that contain positive numbers
res = []
for i in range(len(nums)):
if nums[i] > 0:
# If the number at index i is positive, i+1 was missing
res.append(i + 1)
return resPractice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode