3151. Special Array I
Problem Description
You are given an array of integers nums
. An array is considered special if every pair of its adjacent elements contains two numbers with different parity. Parity refers to whether a number is odd or even. Two numbers with different parity means one is odd and the other is even. The task is to determine if the given array nums
is a special array. If it is, return true
; otherwise, return false
.
Intuition
To solve this problem, the key insight is to compare each pair of adjacent elements in the array and check their parity. If any pair of adjacent numbers share the same parity (both are even or both are odd), then the array is not special.
The process follows a straightforward single-pass approach:
- Traverse the array from left to right.
- For each pair of adjacent elements, determine their parity using the modulus operation (
%
). - If two adjacent elements have the same result when taken modulo 2 (indicating the same parity), then the array is not special.
- If all adjacent pairs in the array have different parity, the array meets the criteria for being special.
By leveraging Python's all()
function and list comprehensions, we can efficiently check the parity difference in a compact manner.
Solution Approach
To determine if the array is special, the solution employs a single-pass traversal through the array, utilizing a generator expression to check the parity of each pair of adjacent elements:
-
Pairwise Comparison: We need to compare each adjacent pair of elements in the array. In Python, this can be done efficiently using a function like
pairwise()
to create pairs from the listnums
. -
Parity Check: For each pair
(a, b)
, we use the expressiona % 2 != b % 2
. This checks ifa
andb
have different parity:a % 2
gives0
ifa
is even and1
ifa
is odd.- Similarly,
b % 2
gives0
ifb
is even and1
ifb
is odd. - If
a % 2 != b % 2
, thena
andb
have different parity.
-
Use of
all()
function: Theall()
function is used to ensure all comparisons in the generator expression returnTrue
. It iterates through each result of the generator expression:- If any pair of elements has the same parity, the generator will produce
False
for that pair, andall()
will returnFalse
. - If all pairs have different parity,
all()
will returnTrue
.
- If any pair of elements has the same parity, the generator will produce
The implementation can be summarized as follows:
class Solution:
def isArraySpecial(self, nums: List[int]) -> bool:
return all(a % 2 != b % 2 for a, b in pairwise(nums))
This approach ensures an optimal complexity of O(n)
where n
is the number of elements in the array, as the array is traversed only once.
Ready to land your dream job?
Unlock your dream job with a 2-minute evaluator for a personalized learning plan!
Start EvaluatorExample Walkthrough
Let's walk through an example using the solution approach described. Consider the array nums = [1, 2, 3, 4]
.
-
List Preparation: We prepare pairs of adjacent elements:
- First pair:
(1, 2)
- Second pair:
(2, 3)
- Third pair:
(3, 4)
- First pair:
-
Parity Check on Each Pair:
- For the pair
(1, 2)
:1 % 2 = 1
(odd)2 % 2 = 0
(even)- Parity is different, so this pair is valid.
- For the pair
(2, 3)
:2 % 2 = 0
(even)3 % 2 = 1
(odd)- Parity is different, so this pair is valid.
- For the pair
(3, 4)
:3 % 2 = 1
(odd)4 % 2 = 0
(even)- Parity is different, so this pair is valid.
- For the pair
-
Result Using
all()
Function:- All pairs have different parity, the generator expression evaluates to
True
for each pair. all()
aggregates these results and returnsTrue
, indicating that the arraynums
is a special array.
- All pairs have different parity, the generator expression evaluates to
From this walkthrough, we can see that the array nums
satisfies the condition of being special, and thus the function isArraySpecial
will return True
for this input.
Solution Implementation
1from itertools import pairwise
2from typing import List
3
4class Solution:
5 def isArraySpecial(self, nums: List[int]) -> bool:
6 # Check if the array is 'special' by ensuring adjacent pairs
7 # of elements have different parity (one is even, the other is odd)
8 return all(a % 2 != b % 2 for a, b in pairwise(nums))
9
1class Solution {
2 public boolean isArraySpecial(int[] nums) {
3 // Iterate through the array starting from the second element
4 for (int i = 1; i < nums.length; ++i) {
5 // Check if the current and previous elements are both even or both odd
6 if (nums[i] % 2 == nums[i - 1] % 2) {
7 // If so, the array is not special, return false
8 return false;
9 }
10 }
11 // If no consecutive elements have the same parity, return true
12 return true;
13 }
14}
15
1#include <vector>
2
3class Solution {
4public:
5 bool isArraySpecial(std::vector<int>& nums) {
6 // Check each pair of consecutive elements.
7 for (int i = 1; i < nums.size(); ++i) {
8 // If two consecutive numbers have the same parity, return false
9 if (nums[i] % 2 == nums[i - 1] % 2) {
10 return false;
11 }
12 }
13 // If no consecutive numbers have the same parity, return true
14 return true;
15 }
16};
17
1/**
2 * Determines if the array is special.
3 * An array is considered special if adjacent elements alternate between even and odd.
4 *
5 * @param nums - Array of numbers to check
6 * @returns True if the array is special, otherwise false
7 */
8function isArraySpecial(nums: number[]): boolean {
9 // Iterate through the array, starting from the second element
10 for (let i = 1; i < nums.length; ++i) {
11 // Check if the current element and the previous element have the same parity
12 if (nums[i] % 2 === nums[i - 1] % 2) {
13 // If they have the same parity, the array is not special
14 return false;
15 }
16 }
17 // If no consecutive elements share the same parity, the array is special
18 return true;
19}
20
Time and Space Complexity
The time complexity of the code is O(n)
, where n
is the length of the list nums
, because the algorithm needs to check each pair of consecutive elements in the list exactly once. The space complexity is O(1)
, because the algorithm uses a constant amount of additional space regardless of the input size.
Learn more about how to find time and space complexity quickly.
How would you design a stack which has a function min
that returns the minimum element in the stack, in addition to push
and pop
? All push
, pop
, min
should have running time O(1)
.
Recommended Readings
Coding Interview Patterns Your Personal Dijkstra's Algorithm to Landing Your Dream Job The goal of AlgoMonster is to help you get a job in the shortest amount of time possible in a data driven way We compiled datasets of tech interview problems and broke them down by patterns This way
Recursion Recursion is one of the most important concepts in computer science Simply speaking recursion is the process of a function calling itself Using a real life analogy imagine a scenario where you invite your friends to lunch https algomonster s3 us east 2 amazonaws com recursion jpg You first
Runtime Overview When learning about algorithms and data structures you'll frequently encounter the term time complexity This concept is fundamental in computer science and offers insights into how long an algorithm takes to complete given a certain input size What is Time Complexity Time complexity represents the amount of time
Want a Structured Path to Master System Design Too? Don’t Miss This!