Geeks for Geeks Sudo placement: Immediate Smaller Element in array in C language

The code below is Geeks for Geeks Sudo placement challenge for checking immediate smaller Element in an array and printing the desired output.

Geeks for Geeks challenge(Sudo Placement):

Given an integer array, for each element in the array check whether there exists a smaller element on the next immediate position of the array. If it exists print the smaller element. If there is no smaller element on the immediate next to the element then print -1.

Input:

The first line of input contains an integer T denoting the number of test cases.
The first line of each test case contains an integer N, where N is the size of an array.
The second line of each test case contains N integers separated with space which is input for the array arr[ ]

Output:

For each test case, print in a newline the next immediate smaller elements for each element in the array.

Constraints:

1 ≤ T ≤ 100
1 ≤ N ≤ 500
1 ≤ arr[i] ≤ 1000

Example:

Input
2
5
4 2 1 5 3
6
5 6 2 3 1 7

Output
2 1 -1 3 -1
-1 2 -1 1 -1 -1

Code:

#include
#include
int main() {
    int *arr,tc,n,i,x;
    //printf("Enter the no. of test cases:\n");
    scanf("%d",&tc);
    for(i=0;i<tc;i++){
      //  printf("\nEnter the no. of elements in %dst testcase\n",i+1);
        scanf("%d",&n);
    	arr=(int*)malloc(sizeof(int)*n);
        //printf("\nEnter the elements in array:\n");
            for(x=0;x<n;x++){
            scanf("%d",&arr[x]);
            }
            for(x=0;x<n;x++){ if(x > 0){
                if(arr[x] < arr[x-1]){
                    printf("%d ",arr[x]);
                }
                else
                {
                    printf("-1 ");
                
                }
                
                            }         
    }
   printf("-1 ");
    printf("\n");
        free(arr);
    }
    
    return 0;
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: