Solution: Remove Even Integers From Array
Explore how to remove even integers from an array in C++ by traversing the array and creating a new array of odd integers. Understand the solution’s O(n) time complexity and O(1) space complexity, preparing you for interview coding challenges involving array manipulation.
We'll cover the following...
Statement
Given an array of integers, arr, remove all the even integers from the array.
Constraints:
-
arr.length -
arr[i]
Solution
The naive approach is to traverse the array and add all the odd integers to a separate array. This results in a new array, with all the even integers removed.
Here are the steps of this solution:
Find the number of odd integers in the array,
m.Initialize a new array,
oddswith sizem.Traverse through
arr, and for each element in the array:Append the current element to the
oddsarray if it’s an odd integer (i.e., not divisible by 2).
Finally, return
oddsafter all elements ofarrare traversed.
Let’s look at the illustration below to better understand the solution:
Let’s look at the code for this solution below:
Complexity analysis
Let’s look at the time and space complexity of this solution:
Time complexity
The time complexity of the solution is
Space complexity
The space complexity is