709208. Remove and Reverse
Remove and Reverse
Slug: remove-and-reverse--170634
Difficulty: Medium
Id: 709208
Topic Tags: two-pointer-algorithm, Arrays, Strings, Data Structures, Algorithms
Company Tags: None
Summary
The problem involves removing a specified number of elements from the end of an array and then reversing the resulting array. The key concepts involved are arrays and strings, specifically the manipulation of these data structures using algorithms.
Detailed Explanation
To solve this problem, we can use two-pointer approach where one pointer starts from the beginning of the array and another pointer moves from the end of the array to the start. We compare the elements at these pointers and remove the specified number of elements from the end if the element at the second pointer is greater than or equal to the element at the first pointer.
Here's a step-by-step breakdown of the solution:
- Initialize two pointers,
iandj, to 0 andn-1respectively, wherenis the size of the array. - Loop until
i <= j. - If the element at index
jis greater than or equal to the element at indexi, remove the element at indexjfrom the end of the array and decrementj. - Otherwise, increment
i. - Once the loop finishes, reverse the remaining elements in the array.
The time complexity of this solution is O(n), where n is the size of the array, because we are performing a single pass through the array to remove the specified number of elements from the end and then reversing the array. The space complexity is also O(n) because in the worst-case scenario, we might need to store all the elements in a new array for reversal.
Optimized Solutions
Java
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int k = 2;
removeAndReverse(arr, k);
for (int i : arr) {
System.out.print(i + " ");
}
}
public static void removeAndReverse(int[] arr, int k) {
int n = arr.length;
if (k > n) {
return;
}
int i = 0;
int j = n - 1;
while (i <= j) {
if (j - i < k) {
for (int x = i; x <= j; x++) {
arr[x] = arr[j - x + i];
}
break;
}
if (arr[i] >= arr[j]) {
j--;
} else {
i++;
}
}
for (int x = 0; x < k; x++) {
arr[n - x - 1] = 0;
}
}
}