Find Missing and Repeated Values

Find Missing and Repeated Values

You are given a 0-indexed 2D integer matrix grid of size n * n with values in the range [1, n<sup>2</sup>]. Each integer appears exactly once except a which appears twice and b which is missing. The task is to find the repeating and missing numbers a and b.

Return a 0-indexed integer array ans of size 2 where ans[0] equals to a and ans[1] equals to b.

LeetCode Problem - 2965

import java.util.*;

class Solution {
    // Function to find missing and repeated values in a 2D grid
    public int[] findMissingAndRepeatedValues(int[][] grid) {
        int[] result = new int[2]; // Array to store missing and repeated values

        Map<Integer, Integer> mp = new HashMap<>(); // Map to store frequency of values
        for (int i = 0; i < grid.length; i++) { // Iterate over rows
            for (int j = 0; j < grid[0].length; j++) { // Iterate over columns
                int currentValue = grid[i][j]; // Get the current value
                if (!mp.containsKey(currentValue)) { // If value not in map
                    mp.put(currentValue, 1); // Add to map with frequency 1
                } else { // If value already in map
                    result[0] = currentValue; // Assign the repeated value
                }
            }
        }

        int missingValue = 1; // Initialize the missing value
        int gridLength = grid.length * grid.length; // Calculate total number of values in grid
        boolean flag = true; // Flag to check if missing value found
        for (int e : mp.keySet()) { // Iterate over unique values in the map
            if (missingValue != e) { // If missing value found
                result[1] = missingValue; // Assign the missing value
                flag = false; // Update flag
                break; // Exit loop
            }
            missingValue++; // Increment missing value
        }

        if (flag && (gridLength == missingValue)) { // If missing value not found and reached the end of grid
            result[1] = missingValue; // Assign the missing value
        }
        return result; // Return array containing missing and repeated values
    }
}

Did you find this article valuable?

Support Gulshan Kumar by becoming a sponsor. Any amount is appreciated!