No result illustrationNo result illustration

DevLoom

search

Lets Connect

chevron right
Menu
Home

Home

Community

Community

Blog Posts

Blog Posts

Programming

Programming

Tech Topics

Tech Topics

Explore

Explore

Find Jobs

Find Jobs

Tags

Tags

DevLoomPerfect Place for devs
    profile

    Jubair

    upvoteupvote

    1

    downvote

    0

    star

    Remove all Similar Elements

    clock icon

    Asked 9 months ago

    message

    0Comments

    eye

    1 Views

    Understanding the Problem: The problem "Remove Element" asks us to remove all instances of a given value from an array in-place and return the new length of the array.

    What We Need to Do:

    1. Remove all occurrences of the given value from the array.
    2. Return the new length of the array after removals.

    Let's break down the solution :

    class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            for(int i = 0; i < nums.size(); i++){
                if(nums[i] == val){
                    nums.erase(nums.begin() + i);
                    i--;
                }
            }
            return nums.size();
        }
    };

    The Key Lines Explained:

    1. nums.erase(nums.begin() + i);
      • This line removes the element at index i from the vector.
      • nums.begin() points to the start of the vector.
      • nums.begin() + i points to the i-th element.
      • erase() removes the element at this position and shifts all subsequent elements to the left.
    2. i--;
      • This line is crucial and easy to overlook.
      • After erasing an element, all elements to the right shift left by one position.
      • If we don't decrement i, we would skip the next element that just moved into the current position.
      • By decrementing i, we ensure that in the next iteration, we check the element that has shifted into the current position.

    Why These Lines Are Important:

    1. In-Place Removal: The erase() function modifies the vector in-place, which is a requirement of the problem.
    2. No Element Skipping: The i-- ensures we don't accidentally skip any elements after a removal.

    Let's explore a better approach using the two-pointer technique. This method achieves O(n) time complexity and is generally preferred for its efficiency.

    USING TWO POINTER ! 

    class Solution {
    public:
        int removeElement(vector<int>& nums, int val) {
            int k = 0; // k is the write pointer
            
            for (int i = 0; i < nums.size(); i++) {
                if (nums[i] != val) {
                    nums[k] = nums[i];
                    k++;
                }
            }
            return k;
        }
    };

    Let's break down this more efficient solution:

    1. We use two pointers:
      • i: the read pointer, which scans through the entire array.
      • k: the write pointer, which keeps track of where to place the next non-val element.
    2. As we iterate through the array:
      • If the current element (nums[i]) is not equal to val, we copy it to the position indicated by k and then increment k.
      • If the current element is equal to val, we simply move on to the next element without incrementing k.
    3. At the end, k represents both:
      • The number of elements not equal to val (i.e., the new length of the array).
      • The position where any remaining val elements begin in the array.

    Key advantages of this approach:

    1. Time Complexity: O(n), where n is the length of the array. We only pass through the array once.
    2. Space Complexity: O(1), as we modify the array in-place without using extra space.
    3. No need for expensive erase operations: We're simply overwriting elements instead of removing them and shifting the rest.
    4. Maintains relative order of elements: The order of non-val elements remains the same.

    Example walkthrough: Let's say nums = [3, 2, 2, 3] and val = 3:

    1. i = 0, k = 0: nums[0] == 3, skip
    2. i = 1, k = 0: nums[1] == 2, copy to nums[k], increment k
    3. i = 2, k = 1: nums[2] == 2, copy to nums[k], increment k
    4. i = 3, k = 2: nums[3] == 3, skip
    5. Final array: [2, 2, 2, 3], return k = 2

    The first k elements of the array are now the result, with all instances of val effectively removed.

    Adobe
    array
    Two Pointer
    easy

    Share

    Write your comment here !

    0 Responses