LeetCode Weekly Contest 356 Solutions
Counting Employees Meeting Target Hours This problem requires counting employees whose work hours meet or exceed a target value. A simple linear scan suffices.
class Solution {
public:
int numberOfEmployeesWhoMetTarget(vector<int>& hours, int target) {
int count = 0;
for (int h : hours) {
if (h >= target) count++;
}
return count;
}
};
Counting Complete Subarrays Using Sliding Window A complete subarray contains all distinct elements from the original array. We first determine the total unique eleemnts, then use a sliding window appproach to find all valid subarrays.
class Solution {
public:
int countCompleteSubarrays(vector<int>& nums) {
int totalUnique = unordered_set<int>(nums.begin(), nums.end()).size();
unordered_map<int, int> freq;
int left = 0, result = 0;
for (int right = 0; right < nums.size(); ++right) {
freq[nums[right]]++;
while (freq.size() == totalUnique) {
result += nums.size() - right;
freq[nums[left]]--;
if (freq[nums[left]] == 0) {
freq.erase(nums[left]);
}
left++;
}
}
return result;
}
};
Shortest String Containing Three Substrings We need to find the shortest possible string that contains three given strings as substrings. Since there are only three strings, we can enumerate all permutations and find the optimal merging.
class Solution {
private:
string combineStrings(string a, string b) {
if (a.find(b) != string::npos) return a;
if (b.find(a) != string::npos) return b;
int maxOverlap = min(a.size(), b.size());
for (int i = maxOverlap; i > 0; --i) {
if (a.substr(a.size() - i) == b.substr(0, i)) {
return a + b.substr(i);
}
}
return a + b;
}
public:
string minimumString(string a, string b, string c) {
vector<string> strs = {a, b, c};
string result = a + b + c;
sort(strs.begin(), strs.end());
do {
string merged = combineStrings(combineStrings(strs[0], strs[1]), strs[2]);
if (merged.size() < result.size() ||
(merged.size() == result.size() && merged < result)) {
result = merged;
}
} while (next_permutation(strs.begin(), strs.end()));
return result;
}
};
Counting Stepping Numbers in Range This problem requires counting stepping numbers (where adjacent digits differ by exact 1) within a given range. This requires a digit DP approach which will be covered in a future update.