703385. Transform the array

Easy

Transform the Array Slug: transform-the-array4344 Difficulty: Easy Id: 703385 Topic Tags: Arrays, Data Structures Company Tags: Microsoft

Summary

This problem involves transforming an array according to specific rules. The task requires iterating over the elements of the array and applying certain operations based on their values or indices. This problem can be approached using basic algorithms such as loops and conditional statements.

Detailed Explanation

The given array is a list of integers, and the goal is to transform it into another array following these rules:

  • If an element in the original array is even, its corresponding position in the transformed array will have the value 2.
  • If an element in the original array is odd, its corresponding position in the transformed array will have the value 1.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty array transformed_array with the same length as the input array.
  2. Iterate over each element element in the input array using a loop (e.g., for or while).
  3. For each element, check if it is even or odd by using the modulo operator (% 2 == 0 for even and % 2 != 0 for odd).
  4. Based on whether the element is even or odd:
    • If even, assign transformed_array[i] = 2, where i is the index of the current element.
    • If odd, assign transformed_array[i] = 1.
  5. Return the transformed array.

Time complexity: O(n), where n is the length of the input array (since we're iterating once over all elements). Space complexity: O(n), as we create a new array with the same size as the original one.

Optimized Solutions

Java

View on GeeksforGeeks
public int[] transformArray(int[] arr) {
    int[] transformedArr = new int[arr.length];
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] % 2 == 0) {
            transformedArr[i] = 2;
        } else {
            transformedArr[i] = 1;
        }
    }
    return transformedArr;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.