I'm working on this challenge:
Given an array of integers of size N. Assume ‘0’ as invalid number and all other as valid number. Write a program that modifies the array in such a way that if next number is valid number and is same as current number, double the current number value and replace the next number with 0. After the modification, rearrange the array such that all 0’s are shifted to the end and the sequence of the valid number or new doubled number is maintained as in the original array.
Examples:
Input : arr[] = {2, 2, 0, 4, 0, 8} Output : 4 4 8 0 0 0 Input : arr[] = {0, 2, 2, 2, 0, 6, 6, 0, 0, 8} Output : 4 2 12 8 0 0 0 0 0 0
Input:
The first line of the input contains an integer T, denoting the number of test cases. Then T test case follows. First line of each test contains an integer N denoting the size of the array. Then next line contains N space separated integers denoting the elements of the array.
Output:
For each test case print space separated elements of the new modified array on a new line.
Constraints:
1 ≤ T ≤ 10³
1 ≤ N ≤ 10⁵
Example:
Input:
2 5 2 2 0 4 4 5 0 1 2 2 0
Output:
4 8 0 0 0 1 4 0 0 0
I managed to get my code to work for the given input and output cases. However, when I submit it, I get a "time limit exceeded" message.
#include <stdio.h>
int main() {
//code
int x,q,n,i,j,k,m,arr[100000],d,t;
scanf("%d",&x);
for(q=0;q<x;q++)
{
scanf("%d",&n);
for(t=0;t<n;t++)
{
scanf("%d",&arr[t]);
}
for(i=0;i<n;i++)
{
if(i>0)
{
if(arr[i]==arr[i-1])
{
arr[i-1]=arr[i]+arr[i-1];
arr[i]=0;
}
}
}
j=n-1;
k=0;
while(k != j)
{
if(arr[k]==0)
{
for(m=0;k+m+1<=j;m++)
{
arr[k+m]=arr[k+m+1];
}
arr[j]=0;
j--;
}
else
{
k++;
}
}
for(d=0;d<n;d++)
{
printf("%d",arr[d]);
printf(" ");
}
printf("\n");
}
return 0;
}