0831-0840

831. Masking Personal Information $\star\star$

832. Flipping an Image $\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
    const int n = A.size();

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < (n + 1) / 2; ++j) {
        int temp = A[i][j];
        A[i][j] = A[i][n - j - 1] ^ 1;
        A[i][n - j - 1] = temp ^ 1;
      }

    return A;
  }
};

833. Find And Replace in String $\star\star$

834. Sum of Distances in Tree $\star\star\star$

835. Image Overlap $\star\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
 public:
  int largestOverlap(vector<vector<int>>& A, vector<vector<int>>& B) {
    const int n = A.size();
    const int magic = 100;

    int ans = 0;
    vector<pair<int, int>> onesA;
    vector<pair<int, int>> onesB;
    unordered_map<int, int> map;

    for (int i = 0; i < n; ++i)
      for (int j = 0; j < n; ++j) {
        if (A[i][j] == 1) onesA.push_back({i, j});
        if (B[i][j] == 1) onesB.push_back({i, j});
      }

    for (pair<int, int>& a : onesA)
      for (pair<int, int>& b : onesB)
        ++map[(a.first - b.first) * magic + (a.second - b.second)];

    for (auto& [_, value] : map) ans = max(ans, value);

    return ans;
  }
};

836. Rectangle Overlap $\star$

837. New 21 Game $\star\star$

838. Push Dominoes $\star\star$

839. Similar String Groups $\star\star\star$

840. Magic Squares In Grid $\star$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int numMagicSquaresInside(vector<vector<int>>& grid) {
    int ans = 0;

    for (int i = 0; i + 2 < grid.size(); ++i)
      for (int j = 0; j + 2 < grid[0].size(); ++j)
        if (grid[i][j] % 2 == 0 && grid[i + 1][j + 1] == 5)
          ans += isMagic(grid, i, j);

    return ans;
  }

 private:
  int isMagic(vector<vector<int>>& grid, int i, int j) {
    string s;

    for (int num : {0, 1, 2, 5, 8, 7, 6, 3})
      s += to_string(grid[i + num / 3][j + num % 3]);

    return string("4381672943816729").find(s) != string::npos ||
           string("9276183492761834").find(s) != string::npos;
  }
};