Created
December 9, 2024 23:34
-
-
Save igavrysh/b6dd5816e944d4917c79935e2676fe4c to your computer and use it in GitHub Desktop.
3152. Special Array II
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
https://leetcode.com/problems/special-array-ii | |
3152. Special Array II | |
Medium | |
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 is false. | |
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 is true. | |
Constraints: | |
1 <= nums.length <= 10^5 | |
1 <= nums[i] <= 10^5 | |
1 <= queries.length <= 10^5 | |
queries[i].length == 2 | |
0 <= queries[i][0] <= queries[i][1] <= nums.length - 1 | |
*/ | |
class Solution { | |
public boolean[] isArraySpecial(int[] nums, int[][] queries) { | |
int n = nums.length; | |
int[] psum = new int[n]; | |
for (int i = 1; i < n; i++) { | |
psum[i] = psum[i-1] + (nums[i]%2 + nums[i-1]%2 == 1 ? 0 : 1); | |
} | |
int q = queries.length; | |
boolean[] res = new boolean[q]; | |
for (int i = 0; i < q; i++) { | |
int[] query = queries[i]; | |
res[i] = (psum[query[1]] - psum[query[0]] == 0); | |
} | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment