You are given an array nums
consisting of integers. A pair of consecutive integers (nums[i], nums[i+1])
is called a special pair if both integers belong to the same "team":
The task is to process several queries. Each query is of the form [left, right]
, and you need to determine whether there are no special pairs between indices left
and right
in the array. If there are no special pairs, return true
for the query; otherwise, return false
.
We create a prefix array prefix
that counts the cumulative number of special pairs as we traverse the array:
For example, for nums = [4, 3, 1, 6]
:
0
: No pairs yet β prefix[0] = 0
.1
: (4, 3)
isnβt special β prefix[1] = 0
.2
: (3, 1)
is special β prefix[2] = 1
.3
: (1, 6)
isnβt special β prefix[3] = 1
.Final prefix array: [0, 0, 1, 1]
.
For each query [left, right]
:
specialCount = prefix[right] - (left > 0 ? prefix[left - 1] : 0);
specialCount == 0
, return true
; otherwise, return false
.O(n)
, where n
is the size of nums
.O(q)
, where q
is the number of queries.Total: O(n + q)
.
Input:
nums = [4, 3, 1, 6];
queries = [[0, 1], [1, 2], [0, 3]];
Output:
[true, false, false]
Explanation:
[0, 1]
: No special pairs β true
.[1, 2]
: (3, 1)
is special β false
.[0, 3]
: (3, 1)
is special β false
.Input:
nums = [2, 4, 6, 8];
queries = [[0, 3], [1, 2]];
Output:
[false, false]
Explanation:
[0, 3]
: All pairs are special β false
.[1, 2]
: (4, 6)
is special β false
.Input:
nums = [1, 3, 5, 7];
queries = [[0, 2], [1, 3]];
Output:
[false, false]
Explanation:
[0, 2]
: All pairs are special β false
.[1, 3]
: All pairs are special β false
.https://leetcode.com/problems/special-array-ii/description/?envType=daily-question&envId=2024-12-09
Loading component...
Loading component...
Main Function is not defined.
nums = [4,3,1,6], queries = [[0,2],[2,3]]
Output: [false,true]
public static boolean[] isArraySpecial(int[] nums, int[][] queries) {
int n = nums.length;
int[] prefix = new int[n];
boolean[] result = new boolean[queries.length];
for (int i = 1; i < n; i++) {
prefix[i] = prefix[i - 1];
if ((nums[i - 1] % 2 == 0 && nums[i] % 2 == 0) || (nums[i - 1] % 2 != 0 && nums[i] % 2 != 0)) {
prefix[i]++;
}
}
for (int i = 0; i < queries.length; i++) {
int left = queries[i][0];
int right = queries[i][1];
int specialCount = prefix[right] - (left > 0 ? prefix[left] : 0);
result[i] = (specialCount == 0);
}
return result;
}//function end
Utility Function is not required.