I have a min and a max. Iterating through an array I need to remove all elements that are in between min and max. I cannot use any built in array functions like splice and the array needs to stay in the original order. For Example the array [1,5,13,27,58] min = 10 max = 30 would return an array of [1,5,58]. I am looking for more of strategy of how to do this in N time complexity. This question is for interview prep.
Here is the code I have tried,
function filter_range(array, min, max) {
for (var i = 0; i < array.length; i++) {
if (min < array[i] && array[i] < max) {
for (var j = i; j < array.length - 1; j++) {
var temp = array[j]
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
var array = [1, 5, 23, 13, 59];
filter_range(array, 10, 30);
for (var i = 0; i < array.length; i++) {
console.log(array[i])
}
undefined(ornullor whatever), and then do a second pass where you defragement the array by shifting elements down to the left. This is stillO(n)time, because there are a fixed number of passes, and each pass only handles each element once. (So it'sO(2n), which isO(n).)