Magicsheet logo

Transform Array by Parity

Easy
88.6%
Updated 6/1/2025

Asked by 1 Company

Transform Array by Parity

What is this problem about?

"Transform Array by Parity" is an introductory array manipulation problem. Given an array of integers, you are asked to transform it according to the parity (even or odd) of its elements. Usually, this involves replacing each even number with 0 and each odd number with 1, and then sorting the resulting array so that all zeros come before all ones. It's a simple exercise in mapping values and then organizing them.

Why is this asked in interviews?

This "Transform Array by Parity interview question" is typically used for screening or entry-level positions at companies like Infosys. It checks if a candidate can perform basic array operations like iteration, conditional replacement, and sorting. While the problem is "EASY," it's a good way to see if a candidate writes clean, efficient code and understands the underlying complexity of built-in sorting functions.

Algorithmic pattern used

The "Array, Counting, Sorting interview pattern" is used here. You can solve this in two steps: first, iterate through the array to transform each element based on its parity (num % 2). Second, sort the array. However, a more optimized way is to simply count the number of even elements. Since every even becomes 0 and every odd becomes 1, the final array will just be a sequence of N zeros followed by M ones, where N is the count of evens and M is the count of odds. This reduces the complexity from O(nlogn)O(n \log n) to O(n)O(n).

Example explanation

Input: [4, 1, 2, 3, 10]

  1. Map parities:
    • 4 is even -> 0
    • 1 is odd -> 1
    • 2 is even -> 0
    • 3 is odd -> 1
    • 10 is even -> 0 Resulting array: [0, 1, 0, 1, 0]
  2. Sort: [0, 0, 0, 1, 1] Final output: [0, 0, 0, 1, 1] Alternatively, count evens (3) and odds (2), then construct [0, 0, 0, 1, 1].

Common mistakes candidates make

A common mistake in the "Transform Array by Parity coding problem" is over-complicating the solution by using a full sorting algorithm when a simple count would suffice. Another error is not handling negative numbers correctly with the modulo operator (e.g., -1 % 2 might return -1 instead of 1 in some languages). Ensuring the transformation logic is robust for all integer inputs is key.

Interview preparation tip

For the "Array, Counting, Sorting interview pattern," always look for ways to avoid sorting if the range of values is small or if the transformation results in only a few distinct values. Counting or using a frequency array (Bucket Sort concept) is often much faster and shows a deeper understanding of algorithmic efficiency.

Similar Questions