703385. Transform the array
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:
- Initialize an empty array
transformed_arraywith the same length as the input array. - Iterate over each element
elementin the input array using a loop (e.g., for or while). - For each element, check if it is even or odd by using the modulo operator (
% 2 == 0for even and% 2 != 0for odd). - Based on whether the element is even or odd:
- If even, assign
transformed_array[i] = 2, whereiis the index of the current element. - If odd, assign
transformed_array[i] = 1.
- If even, assign
- 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
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;
}