Logo

Kode$word

Find All Numbers Disappeared in an Array

Find All Numbers Disappeared in an Array

LeetCode Question 448

10 views
0
0

LeetCode Problem 448

Link of the Problem to try -: Link

Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums.

Example 1:

Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]

Example 2:

Input: nums = [1,1]
Output: [2]

Constraints:

  1. n == nums.length
  2. 1 <= n <= 105
  3. 1 <= nums[i] <= n


Solution:

In this question as the question suggests we have to find the missing element from the array that is not in the array but comes in that range of 1 to array.length and we can solve this by creating an HashMap where we simply store all the elements and then run the loop again from 1 to array.length and then check is that element present if not then store it on our ArrayList and return it this is how we can solve this question easily in O(n) Time Complexity.


Code:

public List<Integer> findDisappearedNumbers(int[] nums) {
HashMap<Integer,Integer> mp = new HashMap<>();
List<Integer> lis = new ArrayList<>();
for(int i =0;i<nums.length;i++){
mp.put(nums[i],0);
}
for(int i = 1;i<=nums.length;i++){
if(!mp.containsKey(i)){
lis.add(i);
}
}
return lis;
}