This post is completed by 3 users
|
Add to List |
529. Duplicate even elements in an array
Given an array of numbers, write a program to duplicate the even numbers and return the new array.
Example:
Input: [2, 4, 1, 5, 2, 3, 8, 9, 10, 4] Output: [2, 2, 4, 4, 1, 5, 2, 2, 3, 8, 8, 9, 10, 10, 4, 4] Input: [2, 4, 6, 8] Output: [2, 2, 4, 4, 6, 6, 8, 8] Input: [1, 3, 5, 6] Output: [1, 3, 5, 6, 6]
Approach:
- Iterate the input array and count the number of even numbers.
- Initialize result of array of size newLength-1 = input array + evenCount (for even number).
- Initialize index = newLength-1.
- Now iterate the array from right to left and for the current element
- If the current element is odd then copy the current element to the result[index].
- If the current element is even then copy the current element to the result[index] and result[--index].
- Do index = index - 1.
- Return the result array.
Time Complexity: O(N)
Output:
Input: [2, 4, 1, 5, 2, 3, 8, 9, 10, 4] Output: [2, 2, 4, 4, 1, 5, 2, 2, 3, 8, 8, 9, 10, 10, 4, 4] ------------------------ Input: [2, 4, 6, 8] Output: [2, 2, 4, 4, 6, 6, 8, 8] ------------------------ Input: [1, 3, 5, 6] Output: [1, 3, 5, 6, 6]