C Online Compiler
Example: Remove Duplicates In-Place (Sorted Array) in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Remove Duplicates In-Place (Sorted Array) #include <stdio.h> #include <stdlib.h> // For qsort #include <string.h> // For memcpy (not strictly needed but useful for array manipulation) // Comparison function for qsort int compare(const void *a, const void *b) { return (*(int*)a - *(int*)b); } int main() { int arr[] = {10, 20, 20, 30, 40, 40, 50, 60, 10}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original Array: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); // Step 1: Sort the array qsort(arr, n, sizeof(int), compare); printf("Sorted Array: "); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); if (n == 0) { printf("Array is empty, no duplicates to remove.\n"); return 0; } // Step 2: Use two pointers for in-place removal int i = 0; // Pointer for the next unique element position // j iterates through the array for (int j = 1; j < n; j++) { // If current element is different from the last unique element if (arr[j] != arr[i]) { i++; // Move the unique pointer forward arr[i] = arr[j]; // Place the unique element } } // The new effective size of the array is i + 1 int new_n = i + 1; printf("Array after removing duplicates (in-place): "); for (int k = 0; k < new_n; k++) { printf("%d ", arr[k]); } printf("\n"); return 0; }
Output
Clear
ADVERTISEMENTS