↓Skip to main content
  1. LeetCode/

LeetCode 598: Range Addition II

·2 mins· ·
LeetCode Easy Array Math
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-28

  • Submissions: Wrong Answer → Accepted ×3 → Runtime Error ×2 → Accepted ×2

Approach
#

Each operation is a rectangle anchored at (0, 0), so the cells hit by every operation hold the maximum; they form the intersection, min(a) rows by min(b) columns, each minimum taken separately and then multiplied (Math Template 4). With no operations everything is 0 and the answer is m × n.

My Attempts
#

Attempt 1 returned min(min_row, min_column) ** 2 when the two minimums differed, treating the intersection as a square: m = 4, n = 1, ops = [[2, 1]] should be 2; it returned 1. Two REs followed (a misnamed variable, a type error), and multiplying the two passed.

Solution
#

class Solution:
    def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:
        for a, b in ops:
            m, n = min(m, a), min(n, b)
        return m * n

Complexity
#

Time O(k) for k operations, space O(1).

Mistakes to Avoid
#

  • The intersection need not be square; take the row and column minimums separately.
  • With no operations the answer is m × n.

Interview Explanation
#

Every operation contains the top-left corner, so the maximum cells are the intersection of all operations: the product of the minimum row and column bounds, starting from m and n so no operations gives m × n. Time O(k).

Related

LeetCode 268: Missing Number
·1 min
LeetCode Easy Array Hash-Table Math Binary-Search
LeetCode 268 note: the sum of 0..n minus the array’s sum is the missing number, which may be 0
LeetCode 66: Plus One
·2 mins
LeetCode Easy Array Math
LeetCode 66 note: add one from the last digit, turning 9s into 0s while carrying, and prepend 1 when every digit was 9
LeetCode 599: Minimum Index Sum of Two Lists
·2 mins
LeetCode Easy Array Hash-Table String
LeetCode 599 note: map list1’s strings to indices, sum both indices while scanning list2, and keep every string with the minimum sum
LeetCode 605: Can Place Flowers
·2 mins
LeetCode Easy Array Greedy
LeetCode 605 note: scan left to right and plant in any empty plot whose neighbors are empty; a new flower blocks the next plot, so actually update the array
LeetCode 561: Array Partition
·1 min
LeetCode Easy Array Greedy Sorting Counting-Sort
LeetCode 561 note: sort and pair neighbors; each pair’s minimum is the element at an even index, so sum those
LeetCode 566: Reshape the Matrix
·2 mins
LeetCode Easy Array Matrix Simulation
LeetCode 566 note: return the original if the element counts differ; otherwise element k goes to (k // c, k % c)