Time Complexity (Terminated due to timeout 2s at Hackerrank) - c

Suggest some ways to reduce the time complexity of this following code.
The problem is:
This is question
This is sample input output
This code is working fine except two cases (terminated due to time limit 2s)
#include<stdio.h>
#include<string.h>
int main()
{
unsigned char str[1000000];
unsigned long int l;
int i,j,t,k,c=0;
scanf("%d",&t);
for(k=0;k<t;k++)
{
c=0;
scanf("%lu",&l);
scanf("%s",str);
for(i=0;i<l-1;i++)
{
for(j=i+1;j<l;j++)
if(str[i]=='S' && str[j]=='A')
c++;
}
printf("%d\n",c);
}
return 0;
}

I'd use the following algorithm to solve:
Traverse the string :
a variable count which will store number of S's before a currently found A and total which is the total substrings found yet.
int total=0,count=0;
for(int j=0; j < s.length(); ++j){ //s.length or till wherever you want to find
if(s[j] == 'A') total+=count;
else if(s[j]=='S') count++;
}

Related

I don't understand why this code is not working properly

In C programme:
Question is: You are given a binary string S of size N. Now you need to tell total how many 01 and 10 pair exist in the given string.
#include<stdio.h>
int main() {
int i,t,j,count;
int n;
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d",&n);
char s[n];
scanf("%s",&s[n]);
j=0,count=0;
while(s[j]!='\0')
{
if(s[j]=='1' && s[j+1]=='0')
{ count++;}
else if(s[j]=='0' && s[j+1]=='1')
{ count++;}
j++;
}
printf("%d\n",count);
}
return 0;
}
When n is less than 6,there is showing correct answer. But when n is greater then 6, this is showing 0. Please help me out.
scanf("%s",&s[n]); - that &s[n] is the address where s ends. It's the first address after s. You want to write to the first address of s: &s[0] or just s.

How to find duplicate letter in array in C

I am making a program which requires the user to input an argument (argv[1]) where the argument is every letter of the alphabet rearranged however the user likes it. Examples of valid input is "YTNSHKVEFXRBAUQZCLWDMIPGJO" and "JTREKYAVOGDXPSNCUIZLFBMWHQ". Examples of invalid input would then be "VCHPRZGJVTLSKFBDQWAXEUYMOI" and "ABCDEFGHIJKLMNOPQRSTUYYYYY" since there are duplicates of 'V' and 'Y' in the respective examples.
What I know so far is, that you can loop through the whole argument like the following
for (int j = 0, n = strlen(argv[1]); j < n; j++)
{
//Place something in here...
}
However, I do not quite know if this would be the right way to go when looking for duplicates? Furthermore, I want the answer to be as simple as possible, right know time and cpu usage is not a priority, so "the best" algorithm is not necessarily the one I am looking for.
Try it.
#include <stdio.h>
#include <stddef.h>
int main()
{
char * input = "ABCC";
/*
*For any character, its value must be locate in 0 ~ 255, so we just
*need to check counter of corresponding index whether greater than zero.
*/
size_t ascii[256] = {0, };
char * cursor = input;
char c = '\0';
while((c=*cursor++))
{
if(ascii[c] == 0)
++ascii[c];
else
{
printf("Find %c has existed.\n", c);
break;
}
}
return 0;
}
assuming that all your letters are capital letters you can use a hash table to make this algorithm work in O(n) time complexity.
#include<stdio.h>
#include<string.h>
int main(int argc, char** argv){
int arr[50]={};
for (int j = 0, n = strlen(argv[1]); j < n; j++)
{
arr[argv[1][j]-'A']++;
}
printf("duplicate letters: ");
for(int i=0;i<'Z'-'A'+1;i++){
if(arr[i]>=2)printf("%c ",i+'A');
}
}
here we make an array arr initialized to zeros. this array will keep count of the occurrences of every letter.
and then we look for letters that appeared 2 or more times those are the duplicated letters.
Also using that same array you can check if all the letters occured at least once to check if it is a permutation
I don't know if this is the type of code that you are looking for, but here's what I did. It looks for the duplicates in the given set of strings.
#include <stdio.h>
#include <stdlib.h>
#define max 50
int main() {
char stringArg[max];
int dupliCount = 0;
printf("Enter A string: ");
scanf("%s",stringArg);
system("cls");
int length = strlen(stringArg);
for(int i=0; i<length; i++){
for(int j=i+1; j<length; j++){
if(stringArg[i] == stringArg[j]){
dupliCount +=1;
}
}
}
if(dupliCount > 0)
printf("Invalid Input");
printf("Valid Input");
}
This code snippet is used to count the duplicate letters in the array.
If you want to remove the letters, Also this code snippet is helpful .Set null when the same characters are in the same letter.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int count=0;
int array[]={'e','d','w','f','b','e'};
for(int i=0;i<array.Lenth;i++)
{
for(int j=1;j<array.Length;j++)
{
if(array[i]==array[j])
{
count++;
}
}
}
printf("The dublicate letter count is : %d",count);
}

time limit exceeded for next palindrome

given a number, i was aked to find the next number which is a palindrome.Thisis the code i have writen. my code works fine but the website I am working on says "time limit exceeded"...how do I correct this?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXLEN 50
void reverse (char s[]){
int c,i,j;
for (i=0,j=strlen(s)-1;i<j;i++,j--){
c= s[i];
s[i]=s[j];
s[j]=c;
}
}
void itoa (int n, char s[]) {
int i;
i = 0;
do {
s[i++] = n % 10 + '0';
} while ((n /= 10) > 0);
s[i] = '\0';
reverse(s);
}
int main (void) {
int t,j;
scanf("%d",&t);
for(j=0;j<t;j++){
int k,c=1,i;
char s[MAXLEN];
scanf("%d",&k);
int a= k+1;
while (c!=0){
itoa(a,s);
int e=strlen(s)-1;
for(i=0;i<(e+1)/2;i++){
if (s[i]==s[e-i]){
c=0;
}
else{
c=1;
goto state;
}
}
state:a++;
}
printf("%s\n",s);
}
return 0;
}
You need to use a smarter way than brute force!
Here is an algorithm with time complexity log(N):
Read the number as a string.
Take the first half of the number.
Make a palindrome by adding the first half reversed. (Consider the two cases: even/odd length of the original number)
If this palindrome is greater than the original number you are done.
If it is not:
Take the first half of the number and add 1.
Make a palindrome by adding the first half reversed. (Again consider the two cases: even/odd length of the original number).
Done!

C : Output printing a line later

I wrote this small program to count the number of trailing zeroes. I got my algorithm correct. But I cannot get the output right. The first line we enter is for the number of inputs (T). Later the user enters the number (whose number of trailing zeroes in factorial is to be calculated.) And then print the answer (count). But after I input the value for N, I get the answer on the third line (I used just one '\n'). I need to get my output right.
#include <stdio.h>
int main()
{
int T;
int i,j,temp,count=0;
long int N;
scanf("%d",&T);
for(i=0;i<T;i++)
{
scanf("\n%ld",&N);
for(j=5;j<=N;j+=5)
{
temp=j;
while(j > 1)
{
if(j%5 == 0)
count++;
j=j/5;
}
j=temp;
}
printf("\n%d",count);
count =0;
}
return 0;
}
Change:
printf("\n%d",count);
to:
printf("%d\n",count);
and:
scanf("\n%ld",&N);
to:
scanf("%ld",&N);

what is wrong with the loops

I am solving a problem of adding the last digits of numbers lying between a range (for ex. between 'm' and 'n' where m < n).I have coded this
#include <stdio.h>
int main()
{
int t=0;
long int m=0,n=0,num=0,sum=0,lsum=0,i=0;
scanf("%d",&t);
while(t--){
scanf("%ld%ld",&m,&n);
i=m;
while(i<=n){
while(i!=0){
num=i%10;
i/=10;
}
lsum=lsum+(sum%10);
i++;
}
}
printf("\n%ld",lsum);
return 0;
}
Here t=No of Test Cases. m and n is the range. I don't know why it is running infinitely in the terminal. I am using gcc(4.3.2) compiler.How can I optimize it for speed ,or is it the case where the while conditions are never terminated, but why?
You are dividing the i: i/=10. This means that i is always set back to 1 at the end of the loop. You should use a temporary variable for the dividing.
Like this:
while(i<=n){
int temp = i;
while(temp !=0){
num=temp %10;
temp /=10;
}
lsum=lsum+(sum%10);
i++;
}
P.S. There are many other errors in your code. But they are not connected with the infinite looping.
There is an infinite loop int the code :
while(i<=n)
{
while(i!=0)
{
num=i%10;
i/=10;
}
lsum=lsum+(sum%10);
i++;
}
the first while(1<= n) is always true : the second loop makes i = 0 or i = 1 !

Resources