2023-06-13 Daily Challenge

Today I have done leetcode's June LeetCoding Challenge with cpp.

June LeetCoding Challenge 13

Description

Equal Row and Column Pairs

Given a 0-indexed n x n integer matrix grid, return the number of pairs (ri, cj) such that row ri and column cj are equal.

A row and column pair is considered equal if they contain the same elements in the same order (i.e., an equal array).

 

Example 1:

Input: grid = [[3,2,1],[1,7,6],[2,7,7]]
Output: 1
Explanation: There is 1 equal row and column pair:
- (Row 2, Column 1): [2,7,7]

Example 2:

Input: grid = [[3,1,2,2],[1,4,4,5],[2,4,2,2],[2,4,2,2]]
Output: 3
Explanation: There are 3 equal row and column pairs:
- (Row 0, Column 0): [3,1,2,2]
- (Row 2, Column 2): [2,4,2,2]
- (Row 3, Column 2): [2,4,2,2]

 

Constraints:

  • n == grid.length == grid[i].length
  • 1 <= n <= 200
  • 1 <= grid[i][j] <= 105

Solution

auto speedup = [](){
  cin.tie(nullptr);
  cout.tie(nullptr);
  ios::sync_with_stdio(false);
  return 0;
}();
class Solution {
public:
  int equalPairs(vector<vector<int>>& grid) {
    map<string, int> rows;
    map<string, int> cols;
    int n = grid.size();
    for(int i = 0; i < n; ++i) {
      string row;
      string col;
      for(int j = 0; j < n; ++j) {
        row.push_back('-');
        col.push_back('-');
        row += to_string(grid[i][j]);
        col += to_string(grid[j][i]);
      }
      rows[row] += 1;
      cols[col] += 1;
    }
    int answer = 0;
    for(const auto &[s, c] : rows) {
      answer += cols[s] * c;
    }

    return answer;
  }
};

// Accepted
// 72/72 cases passed (227 ms)
// Your runtime beats 42.93 % of cpp submissions
// Your memory usage beats 13.65 % of cpp submissions (45.7 MB)