3151. Special Array I #1254
-
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 integers Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to determine if the given array is "special" by checking if every pair of adjacent elements contains two numbers with different parity (one even and one odd). Here's how you can implement this:
Let's implement this solution in PHP: 3151. Special Array I <?php
/**
* @param Integer[] $nums
* @return Boolean
*/
function isArraySpecial($nums) {
$length = count($nums);
// If there is only one element, it's automatically a special array.
if ($length === 1) {
return true;
}
// Check each adjacent pair for different parity
for ($i = 1; $i < $length; $i++) {
if (($nums[$i] % 2) === ($nums[$i - 1] % 2)) {
// If two consecutive elements have the same parity, return false
return false;
}
}
// If all pairs have different parity, return true
return true;
}
// Test cases
$nums1 = [1];
$nums2 = [2, 1, 4];
$nums3 = [4, 3, 1, 6];
echo isArraySpecial($nums1) ? 'true' : 'false'; // Output: true
echo "\n";
echo isArraySpecial($nums2) ? 'true' : 'false'; // Output: true
echo "\n";
echo isArraySpecial($nums3) ? 'true' : 'false'; // Output: false
echo "\n";
?> Explanation:
This solution runs in O(n), where n is the length of the array, making it efficient for the given constraints. |
Beta Was this translation helpful? Give feedback.
We need to determine if the given array is "special" by checking if every pair of adjacent elements contains two numbers with different parity (one even and one odd). Here's how you can implement this:
true
; otherwise, returnfalse
.Let's implement this solution in PHP: 3151. Special Array I