3152. Special Array II #933
-
Topics: 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 Return an array of booleans Example 1:
Example 2:
Constraints:
Hint:
Footnotes
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine whether a subarray of Approach:
Let's implement this solution in PHP: 3152. Special Array II <?php
/**
* @param Integer[] $nums
* @param Integer[][] $queries
* @return Boolean[]
*/
function specialArray($nums, $queries) {
$n = count($nums);
$parity_change = array_fill(0, $n - 1, 0);
// Step 1: Preprocess the array to find parity transitions
for ($i = 0; $i < $n - 1; $i++) {
if (($nums[$i] % 2) !== ($nums[$i + 1] % 2)) {
$parity_change[$i] = 1; // Different parity
}
}
// Step 2: Create prefix sum array to track the number of parity transitions
$prefix_sum = array_fill(0, $n, 0);
for ($i = 1; $i < $n; $i++) {
$prefix_sum[$i] = $prefix_sum[$i - 1] + $parity_change[$i - 1];
}
// Step 3: Process each query
$result = [];
foreach ($queries as $query) {
list($from, $to) = $query;
// Check if all pairs in the range [from, to] have different parity
$transition_count = $prefix_sum[$to] - $prefix_sum[$from];
if ($transition_count == ($to - $from)) {
$result[] = true;
} else {
$result[] = false;
}
}
return $result;
}
// Example usage
$nums1 = [3,4,1,2,6];
$queries1 = [[0, 4]];
print_r(specialArray($nums1, $queries1)); // [false]
$nums2 = [4,3,1,6];
$queries2 = [[0, 2], [2, 3]];
print_r(specialArray($nums2, $queries2)); // [false, true]
?> Explanation:
Time Complexity:
This solution efficiently handles the problem constraints with an optimized approach. |
Beta Was this translation helpful? Give feedback.
We need to determine whether a subarray of
nums
is "special," i.e., every pair of adjacent elements in the subarray must have different parity (one must be odd, and the other must be even).Approach:
Identify Parity Transitions:
We can preprocess the array to mark positions where the parity changes. For example:
0
represents an even number.1
represents an odd number.The idea is to identify all positions where adjacent elements have different parity. This will help us efficiently determine if a subarray is special by checking if the positions in the query are part of the same "special" block.
Preprocessing:
Create a binary array
parity_change
where each element is1
if the adjacent…