3151. Special Array I LeetCode Solution

In this guide, you will get 3151. Special Array I LeetCode Solution with the best time and space complexity. The solution to Special Array I problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Special Array I solution in C++
  4. Special Array I solution in Java
  5. Special Array I solution in Python
  6. Additional Resources
3151. Special Array I LeetCode Solution image

Problem Statement of Special Array I

An array is considered special if the parity of every pair of adjacent elements is different. In other words, one element in each pair must be even, and the other must be odd.
You are given an array of integers nums. Return true if nums is a special array, otherwise, return false.

Example 1:

Input: nums = [1]
Output: true
Explanation:
There is only one element. So the answer is true.

Example 2:

Input: nums = [2,1,4]
Output: true
Explanation:
There is only two pairs: (2,1) and (1,4), and both of them contain numbers with different parity. So the answer is true.

Example 3:

Input: nums = [4,3,1,6]
Output: false
Explanation:
nums[1] and nums[2] are both odd. So the answer is false.

Constraints:

1 <= nums.length <= 100
1 <= nums[i] <= 100

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

3151. Special Array I LeetCode Solution in C++

class Solution {
 public:
  bool isArraySpecial(vector<int>& nums) {
    for (int i = 1; i < nums.size(); ++i)
      if (nums[i] % 2 == nums[i - 1] % 2)
        return false;
    return true;
  }
};
/* code provided by PROGIEZ */

3151. Special Array I LeetCode Solution in Java

class Solution {
  public boolean isArraySpecial(int[] nums) {
    for (int i = 1; i < nums.length; ++i)
      if (nums[i] % 2 == nums[i - 1] % 2)
        return false;
    return true;
  }
}
// code provided by PROGIEZ

3151. Special Array I LeetCode Solution in Python

class Solution:
  def isArraySpecial(self, nums: list[int]) -> bool:
    return all(a % 2 != b % 2 for a, b in itertools.pairwise(nums))
# code by PROGIEZ

Additional Resources

See also  2014. Longest Subsequence Repeated k Times LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.