Find Missing and Repeated Values — LeetCode 2965 Python Solution

EasyArrayHash TableMathMatrix
Problem
#2965
Reading time
3 min

The problem

You are given a 0-indexed 2D integer matrix grid of size n * n with values in the range [1, n2]. Each integer appears exactly once except a which appears twice and b which is missing.

Example

Input
grid = [[1,3],[2,2]]
Output
[2,4]
Explanation
Number 2 is repeated and number 4 is missing so the answer is [2,4].

Python solution

Python
class Solution:
    def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]:
        n = len(grid)
        cnt = [0] * (n * n + 1)
        for row in grid:
            for v in row:
                cnt[v] += 1
        ans = [0] * 2
        for i in range(1, n * n + 1):
            if cnt[i] == 2:
                ans[0] = i
            if cnt[i] == 0:
                ans[1] = i
        return ans

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n^2) auxiliary

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2965. Find Missing and Repeated Values is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.

The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2965. Find Missing and Repeated Values?
LeetCode 2965. Find Missing and Repeated Values is rated Easy on LeetCode.
What is the time complexity of LeetCode 2965. Find Missing and Repeated Values?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 2965. Find Missing and Repeated Values?
The Python solution on this page uses O(n^2) auxiliary space.
What topics does LeetCode 2965. Find Missing and Repeated Values cover?
LeetCode 2965. Find Missing and Repeated Values is tagged Array, Hash Table, Math and Matrix on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview