0% completed
Solution: Problem Challenge 3: Find the First K Missing Positive Numbers
.....
.....
.....
Anonymous
· 2 years ago
It takes O(k) time to test if an element exists in an array, not O(1). So the time complexity of this solution is O(n + k^2).
Anonymous
· 2 years ago
- nums[i] < nums[j] for 1 <= i < j <= nums.length
Is not true if the array is unsorted.
Anonymous
· 2 years ago
class Solution: def findNumbers(self, nums, k): missing_numbers = [] # swapping function def swap(i, j): nums[i], nums[j] = nums[j], nums[i] # if number not in position and number is not outside the array boundary and number does not point to number that is correctly positioned for i in range(len(nums)): while nums[i] > 0 and nums[i] != i + 1 and nums[i] - 1 < len(nums) and nums[i] != nums[nums[i] - 1]: swap(i, nums[i] - 1) # find the missing numbers wrong_numbers = set() for i in range(len(nums)): if nums[i] != i + 1: missing_numbers.append(i + 1) # add the miss-placed number to the set wrong_numbers.add(nums[i]) # if we have found all the missing k numbers just return
Anonymous
· 3 years ago
- place all numbers at the correct index
- store the wrongly indexed numbers in an object while reducing k
- if k is greater than 0 add the remaining numbers to the missing array. to do this, you need to ensure its not in the store object which has all the numbers that already exist in the initial array that were wrongly indexed.
class Solution { findNumbers(nums, k) { let missingNumbers = []; let n = nums.length; let store = {} for (let i = 0; i < n; i++) { if (nums[i] > 0 && nums[i] <= n && nums[i] !== nums[nums[i] - 1]) { [nums[nums[i] - 1], nums[i]] = [nums[i], nums[nums[i] - 1]]; i-- } } for (let i = 0; i < n; i++) { if (nums[i] !== i + 1 && k != 0){ store[nums[i]] = 1 missingNumbe
Anonymous
· 4 years ago
The first for-loop where you first iterate through the elements in the array to insert to missingNumbers and extraNumbers lacks a condition I think. First, a Set does not tolerate duplicate, you can totally add a nums[i] if nums[i] != i + 1, that's true and I agree. However, what if 'i + 1' is equivalent to an element in the Set? For example, consider nums = [5, 6, 7, 8, 9] and k = 9. At i = 4, if I follow the solution's logic, missingNumbers will contain [1, 2, 3, 4, 5]. That 5 is a killer. I managed to fix this by adding a condition to only add i + 1 if extraNumbers has not contained it, and it works so far. Definitely fix me if I'm wrong tho.
Anonymous
· 5 years ago
Is there a leetcode question equivalent of this?
Anonymous
· 5 years ago
I think the space complexity is O(n) not O(k) because at most you would store n extra numbers in the situation where everything inside the array is either n.
Reading Progress
0%