881655. Remove from vector

Basic

Remove from Vector

Summary

Given a vector and an integer, remove all occurrences of that integer from the vector. This problem is about manipulating a vector (a dynamic array) using Standard Template Library (STL) algorithms.

Detailed Explanation

The problem can be solved by iterating through the vector and removing elements that match the given integer. We'll use the erase method to remove elements, which returns an iterator pointing to the element following the removed one.

Here's a step-by-step breakdown of the solution:

  1. Iterate through the vector using an iterator.
  2. For each element, check if it matches the given integer.
  3. If it does, use the erase method to remove that element from the vector. This will shift all subsequent elements down by one position.
  4. Repeat steps 2-3 until the end of the vector is reached.

Time complexity analysis: O(n), where n is the size of the vector, because we're iterating through each element once.

Space complexity analysis: O(1), because we're not using any extra space that scales with the input size.

Optimized Solutions

Java

View on GeeksforGeeks
public static void removeFromVector(int[] arr, int num) {
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == num) {
            arr = Arrays.copyOfRange(arr, 0, i);
            arr = Arrays.copyOfRange(arr, i + 1, arr.length);
            i--; // adjust the loop variable
        }
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.