add codeforces solutions folder

This commit is contained in:
2026-03-05 19:55:52 +05:30
parent 77ff815f38
commit e698c35654
20 changed files with 778 additions and 0 deletions
+32
View File
@@ -0,0 +1,32 @@
class Solution{
public:
int numSpecial(vector<vector<int>> &mat){
int ans = 0;
int r = mat.size();
int c = mat[0].size();
for(int row=0;row<r;row++){
for(int col = 0;col<c;col++){
if(mat[row][col]==0) continue;
bool good = true;
for(int m = 0;m<r;m++){
if(m!=row && mat[m][col] == 1){
good = false;
break;
}
}
for(int n = 0;n<c;n++){
if(n!=col && mat[row][n] == 1){
good = false;
break;
}
}
if(good) ans++;
}
}
return ans;
}
};
//TC : o(r.c(r+c)) SC: o(1)
+31
View File
@@ -0,0 +1,31 @@
class Solution {
public:
int numSpecial(vector<vector<int>>& mat) {
int m = mat.size();
int n = mat[0].size();
vector<int> rowCount(m, 0);
vector<int> colCount(n, 0);
for (int row = 0; row < m; row++) {
for (int col = 0; col < n; col++) {
if (mat[row][col] == 1) {
rowCount[row]++;
colCount[col]++;
}
}
}
int ans = 0;
for (int row = 0; row < m; row++) {
for (int col = 0; col < n; col++) {
if (mat[row][col] == 1) {
if (rowCount[row] == 1 && colCount[col] == 1) {
ans++;
}
}
}
}
return ans;
}
};
+48
View File
@@ -0,0 +1,48 @@
class Solution{
public:
int numSpecial(vector<vector<int>> &mat){
int ans = 0;
int m = mat.size();
int n = mat[0].size();
for(int row = 0;row<m;row++){
int colIndex = -1;
int count = 0;
for(int col = 0;col<n;col++){
if(mat[row][col]==1){
count++;
colIndex = col;
}
}
if(count==1){
bool good = true;
for(int r=0;r<m;r++){
if(r!=row && mat[r][colIndex]==1) {
good = false;
break;
}
}
if(good) ans++;
}
}
return ans;
}
};
/*
Approach:
We iterate through each row of the matrix and count how many 1s appear in that row.
While scanning the row, we also record the column index where the 1 occurs. If a row
contains exactly one 1, it becomes a candidate for a special position. For that candidate,
we then check the entire column corresponding to that 1 to ensure no other row contains a 1
in the same column. If the column also has exactly one 1 (the current position), then that
position satisfies both conditions and we increment the answer. After checking all rows,
the total number of such positions is returned.
Time Complexity: O(mn + m²) in the worst case. We scan each row once (mn work), and for
rows that contain exactly one 1 we scan the column (up to m operations). In practice this
is usually closer to O(mn).
Space Complexity: O(1)
*/