Arindam,

Strings in Java are immutable, which means they can't change. So when you
say:

res+=path.charAt(j)=='S'?'E':'S'

You aren't saying "Java, please add a character to the end of res."
You're saying: "Java, please create a new String by copying over all the
data from res, and adding one character. Then point res at that new String."
If you do that 50,000 times, you end up copying 1+2+3+4+5...+50000
characters: 1.25 billion, just for one test case.

Java provides a class called StringBuilder, which lets you build a String
this way in O(N) instead of O(N^2).

Best,
Bartholomew

On Thu, Apr 11, 2019 at 7:50 AM Arindam Roy <[email protected]> wrote:

> Hi,
>
> Can anyone help me in understanding why the following code is TLE for the
> hidden test case:
>
> import java.util.*;
> import java.io.*;
> public class Solution {
>     public static void main(String[] args) {
>         Scanner in = new Scanner(new BufferedReader(new
> InputStreamReader(System.in)));
>         int t = Integer.parseInt(in.nextLine());
>         for (int i = 1; i <= t; ++i) {
>             in.nextLine(); //ignore grid size
>             String path = in.nextLine();
>             String res = "";
>             for(int j=0;j<path.length();j++) {
>                 res+=path.charAt(j)=='S'?'E':'S';
>             }
>             System.out.println("Case #" + i + ": " + res);
>         }
>     }
> }
>
> --
> You received this message because you are subscribed to the Google Groups
> "Google Code Jam" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To post to this group, send email to [email protected].
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/google-code/9c5814cd-a047-490c-bda9-75d5db226a9a%40googlegroups.com
> .
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Google Code Jam" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/google-code/CAHaiWHO681%2BTkbbrdVPNxxFa0n7ctRrN1Va016CmUQLynvKCcw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to