[Solved] Your program took more time than expected.Time Limit Exceeded. Expected Time Limit < 3.496sec [closed]


The simple answer is that your code is too slow. Why does this matter?

  • You’re running code on someone else’s server, so there are limits in what you can do; frivolously wasting server resources would make the experience worse for everyone else, and increase the costs of the host.
  • You’re doing programming excercises that test your ability to write correct, performant code. The time limit is part of the problem you’re supposed to solve 🙂

Pay attention to the constraints defined in the problem:

1 ≤ T ≤ 200

1 ≤ N ≤ 10E7

1 ≤ arr[i] ≤ 1000

Each of the arrays can be up to 10 million elements in length. That’s a lot of int parsing and string concatenation, a lot of allocations etc.

What can you try to improve your code?

  • Avoid parsing the same number twice – you’re always parsing each element of the array twice, which is an unnecessary cost.
  • Try using StringBuilder to build the output string rather than individual Console.Write calls; write the whole StringBuilder with a single Console.WriteLine call, and clear the StringBuilder for use in the next iteration (avoiding having to allocate yet another large string over and over).
  • Instead of using Split and int.Parse, you can write your own integer parser that can read the input data character by character without having to create new strings all the time. The input data you have is well constrained, so writing a parser is almost trivial.
  • Depending on the execution environment, it might be worth to stream the data from input to output directly without intermediate strings (this is essentially the opposite of point 2.), ideally while buffering the input and output so that you don’t have to deal with strings that are too big (again, keep in mind the array can have ten million elements, which is a very long string!).

Good luck trying to finish the challenge! 🙂

solved Your program took more time than expected.Time Limit Exceeded. Expected Time Limit < 3.496sec [closed]