Find All Numbers Disappeared in an Array - Array - Easy - LeetCode
💻 coding

Find All Numbers Disappeared in an Array - Array - Easy - LeetCode

1 min read 110 words
1 min read
ShareWhatsAppPost on X
  • 1The problem requires finding all numbers in the range [1, n] that do not appear in a given array of integers.
  • 2The solution must achieve O(n) runtime complexity and use O(1) extra space, excluding the output list.
  • 3The provided algorithm modifies the input array to track which numbers have been seen by marking indices as negative.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem requires finding all numbers in the range [1, n] that do not appear in a given array of integers."

Find All Numbers Disappeared in an Array - Array - Easy - LeetCode

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

Example:

Input: [4,3,2,7,8,2,3,1]

Output: [5,6]

public class Solution {
 public IList<int> FindDisappearedNumbers(int[] nums) {
 
 var result = new List<int>();
 var index = 0;
 for(int i=0;i<nums.Length;i++){
 index = Math.Abs(nums[i])-1;
 if(nums[index]>0){
 nums[index]*=-1;
 }
 }
 
 for(int i=0;i<nums.Length;i++){
 if(nums[i]>0){
 result.Add(i+1);
 }
 }
 
 return result;
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 26 September 2020 · 1 min read · 110 words

Part of AskGif Blog · coding

You might also like