Weekly Contest 161

1247. Minimum Swaps to Make Strings Equal

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int minimumSwap(string A, string B) {
auto cnt = [&](auto target) -> int {
return count_if(A.begin(), A.end(), [=](auto c){ return c == target; }) +
count_if(B.begin(), B.end(), [=](auto c){ return c == target; });
};
auto x = cnt('x'),
y = cnt('y');
if (x % 2 || y % 2)
return -1;
auto a = 0,
b = 0;
for (auto i=0; i < A.size(); ++i) {
if (A[i] == B[i])
continue;
a += A[i] == 'x';
b += B[i] == 'x';
}
return (a / 2) + (b / 2) + ((a % 2) + (b % 2));
}
};

1248. Count Number of Nice Subarrays

Exactly K times = at most K times - at most K - 1 times

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int numberOfSubarrays(vector<int>& nums, int k) {
return atMost(nums, k) - atMost(nums, k-1);
}

int atMost(vector<int> &nums, int k){
int res = 0;
int i = 0;
int n = nums.size();
for(int j=0; j<n; j++){
k -= nums[j] % 2;
while(k < 0) k += nums[i++] % 2;
res += j-i+1;
}
return res;
}
};

Minimum Remove to Make Valid Parentheses

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
string minRemoveToMakeValid(string s) {
stack<int> st;
for(auto i = 0; i < s.size(); i++){
if(s[i] == '(') st.push(i);
if(s[i] == ')'){
if(!st.empty()) st.pop();
else s[i] = '*';
}
}
while(!st.empty()){
s[st.top()] = '*';
st.pop();
}
s.erase(remove(s.begin(), s.end(), '*'), s.end());
return s;
}
};

1250. Check If It Is a Good Array

1
2
3
4
5
6
7
8
9
class Solution {
public:
bool isGoodArray(vector<int>& A) {
int res = A[0];
for (int a: A)
res = gcd(res, a);
return res == 1;
}
};
Donate? comment?