A Way For Learning

Reorganize The Array

No comments
Reorganize The Array :

Given an array of elements of length ​ N ​ , ranging from ​ 0 to N-1​ , your task is to write a program that rearranges the elements of the array. All elements may not be present in the array, if element is not present then there will be -1 present in the array. Rearrange the array such that A[i] = i and if i is not present, display -1 at that place.
Examples:
                   Input : arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1}
                   Output : {-1, 1, 2, 3, 4, -1, 6, -1, -1, 9}

Solution :
C
#include <stdio.h>
#include <stdlib.h>
int main() {
int T,i,n;
scanf("%d", &T);
while(T--) {
    scanf("%d", &n);
    int *arr,k;
    arr = (int *)calloc(n+1,sizeof(int));
    for(i = 0; i < n; i++) {
        scanf("%d", &k);
        if(k >= 0) {
            arr[k]++;
        }
    }
    for(i = 0; i < n; i++) {
        if(arr[i] > 0) {
            printf("%d ", i);
        }
        else {
            printf("-1 ");
        }
    }
    printf("\n");
}
return 0;
}

No comments :

Post a Comment