codeholic_7's blog

By codeholic_7, history, 6 weeks ago, In English

How will we submit code in running contest when the same code give us TLE in java and accepted in C++. (checked after contest)

like at which point I actually be realized that this Problem will only be accepted in C++ not in Java.

problem: https://codeforces.com/contest/1474/problem/A

c++ code:

include

using namespace std; int main() { int test; cin>>test; while(test--){ int i,n; cin>>n; string b; cin>>b; string ans="1"; for(i=1;i<n;i++){ if('1'+b[i]!=ans[i-1]+b[i-1]) ans+='1'; else ans+='0'; } cout<<ans<<endl; }

return 0;

}

Java Code: import java.util.Scanner; public class Test{ public static void main(String...c){ Scanner sc=new Scanner(System.in); int test=sc.nextInt(); while(test-->0){ int n=sc.nextInt(); String s2=sc.next(); String s1="1"; int i; for(i=1;i<n;i++){ if(s2.charAt(i-1)+s1.charAt(i-1)!=s2.charAt(i)+'1') s1+='1'; else s1+='0'; } System.out.println(s1); } }

}

 
 
 
 
  • Vote: I like it
  • -12
  • Vote: I do not like it

»
6 weeks ago, # |
  Vote: I like it 0 Vote: I do not like it

Complexity of string concatenation in java is O(n), so the overall complexity of your code is O(n^2). You can use a StringBuilder or a StringBuffer which has O(1) complexity to solve this problem. See my code for reference.

»
6 weeks ago, # |
  Vote: I like it +8 Vote: I do not like it

First you need to know how to paste submission link :)