Thursday, September 13, 2018

SADNESS OF ARRAY

  • Problem Description

    The sadness of an element in an array is defined as the minimum distance between itself and another element whose value is the same as this element. If there is no other element with the same value, its sadness is -1.

    Given an array of size N, find and print the sadness of every element.

    Input Format

    First line contains integer N. Second line contains N integers, the array arr[N].

    Constraints

    1 <= N <= 100
    1 <= arr[N] <= 100

    Output Format

    Output N integers separated by spaces, ith of them denoting the sadness of arr[i].

    in a single line.

    Constraints:
    1<=N<=105

    1<=M<=105
    1<=u,v<=N

  • CODING ARENA
  • #include <stdio.h>
    int main()
    {
      int n,i,ans[10],j;
      scanf("%d",&n);
      int arr[n];
      for(i=0;i<n;i++)
        scanf("%d",&arr[i]);
      for(i=0;i<(n/2)+1;i++)
      {
        for(j=i;j<n;j++)
        {
          if(arr[i]==arr[j])
          {
            ans[i]=j-i;
            ans[j]=j-i;
          }
        }
      }
      for(i=0;i<n;i++)
      {
        if(ans[i]>0)
        {
          printf("%d ",ans[i]);
        }
        else
        {
          printf("-1 ");
        }
      }
    return 0;
    }
  • Test Case 1

    Input (stdin)
    2
    
    1 2
    
    
    Expected Output
    -1 -1
  • Test Case 2

    Input (stdin)
    5
    
    2 1 3 2 1
    
    
    Expected Output
    3 3 -1 3 3

2 comments: