Search code examples
arrayscduplicatesruntime-error

Facing Runtime error while Solving finding and counting duplicates in c


Can someone please help me i am facing runtime error while solving this problem. I have first defined the integers and then used scanf to take the input. Then i check whether the 2 consecutive elements of array are equal are not. if they are equal i equate j variable to i+1 and so that it can traverse and find if same duplicate elements are side by side (eg- 15 15 15). I increment the j element till a[j] is equal to a[i]. Then using i try to print the number with the number of occurences of it which is j-i and then assign i with vakue of j-1.

#include <stdio.h>
int main()
{
    int n,j=0,i;
    scanf("%d",&n);
    int a[n];
    for (i = 0; i < n; ++i) {
        scanf("%d",&a[i]);
    }
    for (i = 0; i < n - 1; ++i)
    {
        if(a[i]==a[i+1])
        {
            j=i+1;
            while(j<n && a[i]==a[j])
            {
                j++;
            }
            printf("%d is appearing %d times\n",a[i],j-i);
        }
        i=j-1;
    }
    return 0;
}

Solution

  • The input array needs to be sorted first to count duplicated, the loop logic needs to be fixed to reassign the index i.

    A fixed code might like this:

    #include <stdio.h>
    #include <stdlib.h>
    static int cmp_intp(const void *p1, const void *p2) {
      return *(const int *)p1 > *(const int *)p2;
    }
    int main() {
      int n, j = 0, i;
      scanf("%d", &n);
      int a[n];
      for (i = 0; i < n; ++i) {
        scanf("%d", &a[i]);
      }
      qsort(a, n, sizeof(a[0]), cmp_intp);
      for (i = 0; i < n;) {
        if (i < n - 1 && a[i] == a[i + 1]) {
          j = i + 1;
          while (j < n && a[i] == a[j]) {
            j++;
          }
          printf("%d is appearing %d times\n", a[i], j - i);
          i = j;
        } else {
          ++i;
        }
      }
      return 0;
    }