One thing is for sure. You do make mistakes. I also make miskates and that's what makes us human. But what we can surely do is — to try to minimize the errors that we make throughout our life.
I have compiled some of the mistakes that I made in my early Competitive Programming phase. I also mentioned how to avoid them. Also, in most cases, I will give you a chance to find out what the bug is before I reveal the culprit as I tried to make this blog interactive. The codes that I have used in this blog have been written in C++ as it is the most used language for CP.
So, if you are new to CP, stick with me as you might don't wanna repeat the mistakes that I made when I was a beginner.
Mistake 1
Check out the following code:
The output should be $$$10^{18}$$$. But if you run the code, you will get a different output. Why?
Mistake 2
Check out the following code:
Try to run this locally. What is the time complexity of this?
Is it $$$O(n)$$$?
Mistake 3
Check out the following code:
Notice that it is guaranteed that total sum of n is <= 100000
. So how many operations will the code take in the worst case?
Mistake 4
What is happening in the following code?
The output is supposed to be 1 1 1 1 1
. But it's not the case actually! It's 16843009 16843009 16843009 16843009 16843009
instead. Why?
Mistake 5
Don't use endl
! If your code needs to print millions of newlines, then using endl
turns out to be really slower than using '\n'
. Why?
Mistake 6
Never use pow()
function for integer calculations.
Mistake 7
Run the following code
You might expect the output to be $$$-1$$$. But the output is actually 18446744073709551615
! Why?
Mistake 8
Using cerr
might be a good way to debug your code as it doesn't output to the standard output. But leaving the cerr
instances in your code while submitting in OJ might be one of the worst ways of getting TLE.
Check this out for more.
Mistake 9
You should always use Fast IO that's for sure. But check out the following code.
You might expect the output to be:
But actually, that might not be the case! For example, locally I am getting the following output:
Basically, the cout
outputs and printf
outputs seem to be working independently! Why?
Mistake 10
Look at the following code
The output is not $$$4$$$! Why?
Mistake 11
Is the following code correct?
If it's not, where is the problem?
Mistake 12
Consider the following code for calculating the maximum occurrence in an array.
This code seems like it should work fast enough but in fact, for certain inputs, it will get TLE.
Mistake 13
Let's erase an element from a multiset
.
The output is not 1 1 2 2 3 4 5 5
. It's actually 1 1 3 4 5 5
! Seems like we have erased all occurrences of $$$2$$$.
Mistake 14
Run the following code:
What will be the size of the map? $$$5$$$?
Mistake 15
Let's compute the sum of natural numbers using set!
The time complexity of this solution is clearly $$$O(n \, \log{n})$$$, right?
Mistake 16
Check out the following code:
What is the time complexity of this?
Mistake 17
Let's look at the following simple code.
Can you guess where the bug is?
Mistake 18
Consider the following code to count unique elements in an array.
What's wrong with this code?
Mistake 19
Lots of mistakes can happen while doing modular arithmetic.
So while doing modular arithmetic, always make sure that after each operation, all your variables are $$$\ge 0 $$$ and $$$< MOD$$$, and you haven't done any overflow.
Mistake 20
Look at the following code:
It doesn't output $$$3 \cdot 10^{12}$$$.
Mistake 21
Using sqrt()
for integers directly might cause some precision issues and give you wrong results.
One of the best ways to compute square roots is the following:
You can do similar stuff for cbrt()
too.
Mistake 22
Check this out.
What is the time complexity of this solution?
More Mistakes
- Do not
insert
orerase
from a container (set
,vector
etc) while traversing it usingfor (auto val: container)
like syntax at the same time. Because for dynamic containers inserting or erasing from it might change the structure of the container. So traversing it parallelly might cause some unexpected behavior. - Use
setprecision
for printing floating point numbers, otherwise, you might get WA for precision issues. - Do not use
rand()
function to generate random numbers. Also, did you know that the maximum valuerand()
generates is32767
? Check out Don't use rand(): a guide to random number generators in C++ to learn what to use. - Create variables only when you need them instead of just declaring
int a, b, c, d, e, f, g, h;
and 69 other variables at the beginning of your code! This will help you catch unnecessary bugs when you use the same variable in two or more places. - Do not use
long long
everywhere aslong long
, at times, might be 2 times slower thanint
. Uselong long
only when it's necessary. - If you want to count the number of set bits in a
long long
number, then use the__builtin_popcountll
function instead of the__builtin_popcount
function. - In C++, the comparator should return false if its arguments are equal. You might get
Runtime Error
if you don't do this. - Speaking of
Runtime Error
, the most likely case of gettingRuntime Error
is not declaring the array sizes with enough large values. Check out the constraint of the problem to make sure of it. long long x = 1 << 40
will still overflow as1
isint
and doing1 << 40
will produce the result inint
, but $$$2^{40}$$$ is way too large to be stored in anint
variable. To fix this issue, use1LL << 40
(basically set the type of1
tolong long
first, check here).- While comparing two floating point numbers, instead of
if (a == b)
, useif (abs(a - b) < eps)
whereeps = 1e-9
or something similar to avoid precision issues. - If you want to take the ceiling of
a / b
wherea
andb
are positive integers, then do(a + b - 1) / b
, instead ofceil(1.0 * a / b)
. For floors just usea / b
as it will round down to the nearest integer. - If you want to take the floor of the log of an integer $$$n > 0$$$ (same as finding the highest set bit of $$$n$$$), use
__lg(n)
. Clean, fast, and simple. - Slightly Advanced: While string hashing, do not use $$$2^{64}$$$ as your mod, and always use at least 2 different primes and mods. Check out Anti-hash test.
Non-technical mistakes
- Instead of the
Solve - Code
structure, use theSolve - Design - Code
approach. Try to design what you will code before jumping to the coding part right away. This will significantly lessen your wrong submission counts and will save lots of time. - You might use
#define int long long
and make your code pass, but you should understand why your solution was not passing in the first place. What I am trying to say is — Learn to control your code. - Solve problems out of your comfort zone and do not just stick to easier problems. Learning new things by solving problems is more important than just increasing your solve count without learning anything new. "Stop obsessing over the number of hours spent or problems solved. These numbers don't mean shit because the variance is so high and it is very easy to spend a lot of time and solve a lot of problems without learning anything." — Tähvend Uustalu (-is-this-fft-).
- Do not skip on the Time and Space Complexity of your solution just because you got AC in the problem. This is really important for a beginner that will help you in the long run.
- Specially on Codeforces, you might get AC by just guessing the solution. But you should learn to prove the solution if you want your brain to get anything out of the problem.
- Not reading others' code is a great way to miss out on learning new techniques/ways to solve the same problem. You should always read the solutions of some of the best coders to know the different ways of solving a problem.
- Do not bother about rating before learning the basics of CP.
- Use a better coding style as it will be helpful in team contests and while debugging your solution. One example coding style is this.
- One way to improve your coding practice is to break your solution down into smaller, more manageable pieces. Instead of attempting to write the entire solution at once, focus on writing and debugging one part at a time. This approach can make it easier to identify and fix errors, and can also make the coding process much easier.
- Maybe you are not as good as you are thinking right now! Maybe your current practice method is not as good as you are assuming! Check out Self-deception: maybe why you're still grey after practicing every day for more.
- Mistake on facing failures: "For me, failing in contests shows me that I still have much to learn so I try to learn new stuff and that's most of the fun. The rest is seeing practice paying off every once in a while. If everyone could have good performances all the time, nobody would have to practice to get better right?" — Tiago Goncalves(tfg). I agree with Tiago. I think the most fun part is to try to be better. It's not fun being good all the time and also it's not fun being bad all the time. The fun part is the transition from doing bad to doing good, the actual delta. And if you practice efficiently then you will certainly make progress.
- Surround yourself with like-minded people as this way you will be able to learn a lot more than trying to learn everything alone.
- Not being self-confident: Self-confidence is the key! If you think you can't do it, then you are already lost! "If you think you are beaten, you are, If you think you dare not, you don’t If you like to win, but you think you can’t, It is almost certain you won’t. If you think you’ll lose, you’re lost. For out in the world we find, Success begins with a fellow’s will— It’s all in the state of mind. If you think you are outclassed, you are, You’ve got to think high to rise, You’ve got to be sure of yourself before You can ever win a prize. Life’s battles don’t always go To the stronger or faster man, But soon or late the man who wins Is the man WHO THINKS HE CAN!” — Napoleon Hill, Think and Grow Rich.
- Do not skip over anything from the solving part of the problem including understanding the solution, proving the solution, coding the solution efficiently, and time and space complexity of the solution, especially if you are a beginner. Every time you skip over any necessary parts of the solution incurs a debt to the CP god. Sooner or later, that debt is paid.
- Remember that Getting AC is not the main goal, learning something new by solving the problem is the main goal.
Thanks for reading the blog. Feel free to add more mistakes that are common in CP in the comment section.
In Mistake 4, you are saying "the output is not 1 1 3 4 5 5". However this is the output of the code. I think you wanted to say "the output is not 1 1 2 2 3 4 5 5"
Thanks, fixed!
Me finding upvote button
Thanks
I wonder whether you type "mistakes" as "miskates" in the first paragraph on purpose
I agree with you. One mistake you didn't mention is getting stuck on a single problem during contest and not attempting the next one. D sometimes can be easier than C (look at official submissions in div2). Or the next problem may be easier just for you as it happened to me during Edu 141. So I suggest participating from m1.codeforces.com and never look at solve count.
Also, the maximum value
rand()
returns isRAND_MAX
which is implementation dependent, as stated in the blog you linked.The only thing I disagree with is that using long long everywhere can be harmful. It almost never is. One time I came close to getting TLE (but got accepted anyway) because of this, was when there were many divisions with long long. Compare using long long vs not using it. However, you can get MLE using long long when using 2D or 3D arrays/vectors. One 5000*5000 matrix of long long integers consumes around 190MB which is fine, because ML is usually 256MB. But declaring another one will exceed it. It might happen in DP problems.
One of the mistakes I still make is: returning to early.
For example in the past contest there's a "YES" "NO" question, I returned when getting input.
This is silly and time wasting.
Very helpful tutorial, thank you! Will definitely forward this to my students who are starting competitive programming.
But how did the advice about string hashing end up in a post "Common mistakes I made when I was a beginner"?
Thanks for pointing it out! Added a
slightly advanced
flag.Wrong Answer ??
Did you read the question properly ? missed something ?
Int overflow
Edge case, n=1? n=0?
Took Input or forgot?
Uninitialised value?
Automatic integer rounding
= or ==Note: The only difference between this problem and problem B1 is that here, scenes are larger and may contain rocks.
MOD during calculation
MOD with subtraction and division ?
MOD with subtraction ex : (11 + (-7)) mod 5
Base Cases ?
0-indexing or 1-indexing
wrong file subitted
Ascending or Descending sort.
Commented Debug statements
forgot printing endl ?
loop i++ or i--
loop mistakes > or >=, j=i or j=1, m/n misplacing, forgot incrementing
output precision for floating point answers
string : s += 'a' + 'c'
sqrt and sqrll, sqrt error ?
abs, absll
cmp should return false if args are equal.
logical Error ? sure logic isn't faulty?
Long long overflow
DP — Proper base cases ?
Using arrays and getting WA instead of Runtime error on out of bound access.
Try coding in python
IO anamoly in using cout and printf together ex : https://www.codechef.com/viewsolution/84270051
Graph : will your soln break for
self loops, multiple edges between a,n, negative weigted cycle/edges
is graph directed?
TLE
fastio ? endl ??
freopen(input.txt) ? forgot to remove ?
Interactive : dont use fastio, use endl or fflush, properly follow IO format
use Global arrays, taking mod less times, use compile time constant for mod
dont ignore value of t, number of testcases.
try in C
is your complexity is O(n) per test case, or O(maxn)
Crazy runtime errors ?
Name collisions, using some reserved names
Some index being used having invalid values, -1, garbage, etc.
Thanks for sharing! Added some of them to the blog.
thanks for sharing! in TLE: 4'th line, what is "taking mod less times, use compile time constant for mod"
In Mistake 10 — Reason, you said that
+
and&
have same precedence. In fact, they have different order of precedence, with+
having much higher priority than&
Thanks a lot. Fixed.
Using
1 << x
instead of1ll << x
has cost me a problem in a contestsame.
In one of the recent contests, I realized that for a set or an STL container not having random access iterators, upper_bound(s.begin(),s.end(),value) has time complexity of O(N) whereas using s.upper_bound(value) has time complexity of O(log n). Check my submissions 188120001 and 188135247.
This is because in upper_bound(s.begin(),s.end(), value), On non-random-access iterators, the iterator advances produce themselves an additional linear complexity in N on average. (Refer here)
In mistake 2, better to pass by const reference--const reference will make the compiler complain if you edit the values at all, which will catch a few bugs.
for mistake 7 we can simply use vector v; cout<<int(v.size())-1<<'\n';
.
Another common mistake is when you return early on a test-case (e.g., due to identifying a special case that's easily handled without much work) before you read all inputs for the test-case, or before you clear out your containers (vectors/maps/etc), which messes with the later test-cases.
One way to avoid these is to get into the habit of reading all inputs before any processing (even if there is a special case that can be easily detected while reading the inputs) and also to clear containers at the start of each test-case (even before reading input) as opposed to the end of each test-case. Having a separate solve function also deals with the latter.
Relatable. I did this too multiple times. Added it to the blog. Thanks.
I suffered a lot from Mistake 9 one year ago. I was doing a team contest and got WA, then spent a whole week trying to understand what's going on until Naseem17 explained it to me. Many mistakes from this list can't be realised without the help of more experienced coder.
I made the same mistake as Mistake-1 few days ago when i was learning C. That time I solved it with another approach but today I learn another approach.
Waiting for the next episode
nice, thanks! I make this blog bookmark!
I also write the blow code at top of my template(I write it in a way that I understand :/)
Great blog!
Forgetting to reset a global array in multitest is also a classic error.
Thanks, added!
You're welcome :)
Accessing a map index can result in insertion. Thus accessing map index too much can result in MLE and TLE.
int a=mp[2]; here 2 gets inserted in mp if it is not already there.
how can I be better at proofing greedy?
I want to add on Mistake 10.
A common mistake I found myself doing is using a bitwise operator, say or and
==
in a single expression without realizing==
has higher precedence than the bitwise operators.Consider the expression
5^5 == 0
.You might expect it to evaluate as
0 == 0
and hencetrue
but it is evaluated as5 ^ (5 == 0)
to5 ^ 0
to5
.yea this is the same as when he did a + b&c. Ppl usually expect it to output (a+(b&c)) whereas it actually outputs ((a+b)&c)
This is quite useful for me. I often make the mistake 10 such as expressing $$$2^n-1$$$ as
1<<n-1
and sometimes stuck in it for a long time. These mistakes is really hard to fix.Assuming $$$g(x)$$$ is a function that got recalculated each time when called wrong.
Which type of code do you do then ?
or
or
Which type of code do you use on real numbers ?
or
or
Which of the following formula do you use:
or
Using
sqrt()
without declaring<cmath>
In Mistake 14 you can use
!mp.count(i)
instead ofmp.found(i) != mp.end()
if you want a shorter version of it. Although I thinkmp.count(i)
is slower thanmp.found(i)
that is becausefound(i)
stops at the first occurrence ofi
unlikecount(i)
which has to travel the whole map.most mistakes are related to c++ only
In mistake 2, why did you typecast a.size() into int??? I know that size() function returns an integer value.
size() return unsigned integer , when vector is empty() , if you write (v.size()-1) then there is no negative number in unsigned integer, it will become INT_MAX, it will run for infinity
Thanks!
Mistake n+1, view the scoreboard in contest time
For python, 3.8 does not have math.lcm but my machine has it. It caused me some damage today. Link
Awesome Blog!
your code for mistake 18 contains mistake 3
about mistake 20, I had a similar mistake once, the following will overflow:
If you really want to use the STL, this works:
Just revisited this amazing blog, no doubt one of the absolute best!
For Mistake 16, how do you add a character to the beginning versus the end of a string in $$$O(1)$$$ time, as you cannot use the
+=
syntax?Someone please correct me if I am wrong, but I don't think there's a way to add a character to the beginning of the string in C++ in $$$O(1).$$$
I don't remember ever encountering a problem where I needed to insert both to the back and the front and in case you need to insert only to the front, you can just reverse the string.
If you are doing padding because you want string to be indexed from 1, doing S="."+S+"...." is fine as you only do it once in your code.