Untitled

mail@pastecode.io avatar
unknown
plain_text
12 days ago
1.3 kB
1
Indexable
Never
/**
 * @param {number[][]} grid
 * @return {number}
 */
var equalPairs = function (grid) {
    let map = new Map();

    // Traverse through each row and column
    for (let i = 0; i < grid.length; i++) {
        let current_row = grid[i].slice(); // Make a copy of the row
        let current_col = []; // Initialize current column array
        for (let j = 0; j < grid[0].length; j++) {
            current_col.push(grid[j][i]); // Build current column array
        }

        // Sort current_row and current_col
        current_row.sort((a,b) => a-b);
        current_col.sort((a,b) => a-b);

        // Convert arrays to strings for map key
        let rowKey = current_row.toString();
        let colKey = current_col.toString();

        // Update map for rowKey
        if (map.has(rowKey)) {
            map.set(rowKey, map.get(rowKey) + 1);
        } else {
            map.set(rowKey, 1);
        }

        // Update map for colKey
        if (map.has(colKey)) {
            map.set(colKey, map.get(colKey) + 1);
        } else {
            map.set(colKey, 1);
        }
    }

    let sum = 0;
    // Count pairs with even frequency greater than 1
    for (let value of map.values()) {
        if (value % 2 === 0 && value > 1) {
            sum++;
        }
    }
    return sum;
};
Leave a Comment