diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index b0e2e764..da68aa6a 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -127,4 +127,5 @@ | 2256 | [Minimum Average Difference](https://leetcode.com/problems/minimum-average-difference/) | [C](./src/2256.c) | Medium | | 2270 | [Number of Ways to Split Array](https://leetcode.com/problems/number-of-ways-to-split-array/) | [C](./src/2270.c) | Medium | | 2304 | [Minimum Path Cost in a Grid](https://leetcode.com/problems/minimum-path-cost-in-a-grid/) | [C](./src/2304.c) | Medium | +| 2482 | [Difference Between Ones and Zeros in Row and Column](https://leetcode.com/problems/difference-between-ones-and-zeros-in-row-and-column/description/) | [C](./src/2482.c) | Medium | | 2501 | [Longest Square Streak in an Array](https://leetcode.com/problems/longest-square-streak-in-an-array/description/) | [C](./src/2501.c) | Medium | diff --git a/leetcode/src/2482.c b/leetcode/src/2482.c new file mode 100644 index 00000000..df9f702d --- /dev/null +++ b/leetcode/src/2482.c @@ -0,0 +1,42 @@ +/** + * Return an array of arrays of size *returnSize. + * The sizes of the arrays are returned as *returnColumnSizes array. + * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). + */ + +// Calculating ones on each row and column. +// Runtime: O(n * m) +// Space: O(n + m) +int** onesMinusZeros(int** grid, int gridSize, int* gridColSize, int* returnSize, int** returnColumnSizes){ + int n = gridSize; + int m = gridColSize[0]; + + int** result = malloc(gridSize * sizeof(int*)); + for (int i = 0; i < n; i++){ + result[i] = malloc(m * sizeof(int)); + } + + int* onesRows = calloc(n, sizeof(int)); + int* onesCols = calloc(m, sizeof(int)); + for (int i = 0; i < n; i++){ + for (int j = 0; j < m; j++){ + if (grid[i][j] == 1){ + onesRows[i] += 1; + onesCols[j] += 1; + } + } + } + + for (int i = 0; i < gridSize; i++){ + for (int j = 0; j < gridColSize[i]; j++){ + result[i][j] = onesRows[i] + onesCols[j] - (m - onesRows[i]) - (n - onesCols[j]); + } + } + + free(onesRows); + free(onesCols); + + *returnSize = gridSize; + *returnColumnSizes = gridColSize; + return result; +}