709208. Remove and Reverse

Medium

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:

  1. Initialize two pointers, i and j, to 0 and n-1 respectively, where n is the size of the array.
  2. Loop until i <= j.
  3. If the element at index j is greater than or equal to the element at index i, remove the element at index j from the end of the array and decrement j.
  4. Otherwise, increment i.
  5. 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

View on GeeksforGeeks
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;
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.