#include <stdio.h>
#include <stdlib.h>

int* findDuplicates(int* nums, int numsSize, int* returnSize) {
    *returnSize = 0;  // Initialize the size of the result array
    int* result = (int*)malloc(numsSize * sizeof(int));  // Allocate space for the result array

    for (int i = 0; i < numsSize; i++) {
        int index = abs(nums[i]) - 1;  // Get the index based on the value in the array
        
        // If the number at that index is negative, the number has been seen before
        if (nums[index] < 0) {
            result[(*returnSize)++] = abs(nums[i]);  // Add the duplicate to the result array
        } else {
            nums[index] = -nums[index];  // Mark the number as seen by negating it
        }
    }

    return result;
}

int main() {
    int nums[] = {4, 3, 2, 7, 8, 2, 3, 1};  // Example input
    int numsSize = sizeof(nums) / sizeof(nums[0]);
    int returnSize;

    int* result = findDuplicates(nums, numsSize, &returnSize);  // Find duplicates

    printf("Duplicates: ");
    for (int i = 0; i < returnSize; i++) {
        printf("%d ", result[i]);  // Print the result
    }

    free(result);  // Free the allocated memory for the result array
    return 0;
}
