Remove Element - C Solution

1. Introduction

This blog post explores a common algorithmic challenge in C programming: removing all occurrences of a specific value from an array, and doing so in-place. This problem is a practical example of array manipulation, focusing on in-place operations and efficient use of memory.

Problem

Given an array of integers nums and an integer val, the task is to remove all instances of val in nums in-place, altering the order of the elements if necessary. The goal is to return the number of elements in nums that are not equal to val.

2. Solution Steps

1. Start by setting up a counter j to track the position of non-val elements in the array.

2. Iterate through the array, checking each element.

3. If an element is not equal to val, place it at the current j position and increment j.

4. Continue the iteration for all elements.

5. After completing the iteration, j holds the count of elements not equal to val.

6. Return the value of j.

3. Code Program

#include <stdio.h>

// Function to remove all instances of 'val' from 'nums'
int removeElement(int* nums, int numsSize, int val) {
    int j = 0;  // Initialize counter for non-'val' elements

    // Loop through each element in the array
    for (int i = 0; i < numsSize; i++) {
        // Check if the current element is not 'val'
        if (nums[i] != val) {
            nums[j++] = nums[i]; // Place it in the next position in the 'non-val' part of the array
        }
    }
    return j; // The new size of the array without 'val'
}

// Main function to test the removeElement function
int main() {
    int nums[] = {3, 2, 2, 3}; // Example array
    int val = 3; // Value to remove
    int numsSize = sizeof(nums) / sizeof(nums[0]); // Size of the array

    // Call function and store the new array size
    int k = removeElement(nums, numsSize, val);

    // Print the modified array and the count of non-'val' elements
    printf("Array after removing %d: ", val);
    for (int i = 0; i < k; i++) {
        printf("%d ", nums[i]);
    }
    printf("\nCount of elements not equal to %d: %d\n", val, k);

    return 0;
}

Output:

Array after removing 3: 2 2
Count of elements not equal to 3: 2

Explanation:

1. int j = 0; - Initialize the counter for tracking the position of non-val elements.

2. for (int i = 0; i < numsSize; i++) - Iterate through each element of the array.

3. if (nums[i] != val) - Check if the current element is not equal to val.

4. nums[j++] = nums[i]; - If the element is not val, move it to the position indicated by j, and then increment j.

5. return j; - Return the count of elements not equal to val.

6. The main function tests the removeElement function with an example array, prints the modified array and the count of non-val elements.


Comments