Facebook Pixel

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:

  1. 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 list nums.

  2. Parity Check: For each pair (a, b), we use the expression a % 2 != b % 2. This checks if a and b have different parity:

    • a % 2 gives 0 if a is even and 1 if a is odd.
    • Similarly, b % 2 gives 0 if b is even and 1 if b is odd.
    • If a % 2 != b % 2, then a and b have different parity.
  3. Use of all() function: The all() function is used to ensure all comparisons in the generator expression return True. 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, and all() will return False.
    • If all pairs have different parity, all() will return True.

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 Evaluator

Example Walkthrough

Let's walk through an example using the solution approach described. Consider the array nums = [1, 2, 3, 4].

  1. List Preparation: We prepare pairs of adjacent elements:

    • First pair: (1, 2)
    • Second pair: (2, 3)
    • Third pair: (3, 4)
  2. 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.
  3. Result Using all() Function:

    • All pairs have different parity, the generator expression evaluates to True for each pair.
    • all() aggregates these results and returns True, indicating that the array nums is a special array.

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.


Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

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

Want a Structured Path to Master System Design Too? Don’t Miss This!


Load More