2024-12-09 Daily Challenge
Today I have done leetcode's December LeetCoding Challenge with cpp
.
December LeetCoding Challenge 9
Description
Special Array II
An array is considered special if every pair of its adjacent elements contains two numbers with different parity.
You are given an array of integer nums
and a 2D integer matrix queries
, where for queries[i] = [fromi, toi]
your task is to check that subarray nums[fromi..toi]
is special or not.
Return an array of booleans answer
such that answer[i]
is true
if nums[fromi..toi]
is special.
Example 1:
Input: nums = [3,4,1,2,6], queries = [[0,4]]
Output: [false]
Explanation:
The subarray is [3,4,1,2,6]
. 2 and 6 are both even.
Example 2:
Input: nums = [4,3,1,6], queries = [[0,2],[2,3]]
Output: [false,true]
Explanation:
- The subarray is
[4,3,1]
. 3 and 1 are both odd. So the answer to this query isfalse
. - The subarray is
[1,6]
. There is only one pair:(1,6)
and it contains numbers with different parity. So the answer to this query istrue
.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 105
1 <= queries.length <= 105
queries[i].length == 2
0 <= queries[i][0] <= queries[i][1] <= nums.length - 1
Solution
class Solution {
public:
vector<bool> isArraySpecial(vector<int>& nums, vector<vector<int>>& queries) {
vector<int> prefixSumSpecial(nums.size());
for(int i = 1; i < nums.size(); ++i) {
prefixSumSpecial[i] = prefixSumSpecial[i - 1] + ((nums[i] % 2) ^ (nums[i - 1] % 2));
}
vector<bool> answer;
answer.reserve(queries.size());
for(const auto &q : queries) {
answer.push_back(q[1] - q[0] == prefixSumSpecial[q[1]] - prefixSumSpecial[q[0]]);
}
return answer;
}
};
// Accepted
// 536/536 cases passed (4 ms)
// Your runtime beats 87.5 % of cpp submissions
// Your memory usage beats 63.34 % of cpp submissions (126.7 MB)