Java solution with explanation [O(n) time and O(n) space] - HashSet


  • 0

    Java solution with explanation [O(n) time and O(n) space] - HashSet

    Find duplicate by storing nos in a hashset.
    To find the missing no we find the sum of the nos and the difference b/w the sum and the sum of the first n natural nos.
    The missing no is the duplicate + difference.

    public class Solution {
        public int[] findErrorNums(int[] nums) {
            Set<Integer> set = new HashSet<>();
            int repeating = -1; int sum = 0;
            for(int num : nums) {
                boolean added = set.add(num);
                if(!added) {
                    repeating = num;
                }
                sum += num;
            }
            
            int error = nums.length * (nums.length + 1) / 2 - sum;
            int[] result = new int[2];
            result[0] = repeating;
            result[1] = repeating + error;
            
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.