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:

**Code**

The output should be $$$10^{18}$$$. But if you run the code, you will get a different output. Why?

**Reason**

#### Mistake 2

Check out the following code:

**Code**

Try to run this locally. What is the time complexity of this?

Is it $$$O(n)$$$?

**Solution**

#### Mistake 3

Check out the following code:

**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?

**Solution**

#### Mistake 4

What is happening in the following code?

**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?

**Reason**

#### 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?

**Reason**

#### Mistake 6

Never use `pow()`

function for integer calculations.

**Why?**

#### Mistake 7

Run the following code

**Code**

You might expect the output to be $$$-1$$$. But the output is actually `18446744073709551615`

! Why?

**Reason**

#### 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.

**Code**

You might expect the output to be:

**Expected Output**

But actually, that might not be the case! For example, locally I am getting the following output:

**Actual Output**

Basically, the `cout`

outputs and `printf`

outputs seem to be working independently! Why?

**Reason**

#### Mistake 10

Look at the following code

**Code**

The output is not $$$4$$$! Why?

**Reason**

#### Mistake 11

Is the following code correct?

**Code**

If it's not, where is the problem?

**Solution**

#### Mistake 12

Consider the following code for calculating the maximum occurrence in an array.

**Code**

This code seems like it should work fast enough but in fact, for certain inputs, it will get TLE.

**Why?**

#### Mistake 13

Let's erase an element from a `multiset`

.

**Code**

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$$$.

**Why?**

#### Mistake 14

Run the following code:

**Code**

What will be the size of the map? $$$5$$$?

**Check**

#### Mistake 15

Let's compute the sum of natural numbers using set!

**Code**

The time complexity of this solution is clearly $$$O(n \, \log{n})$$$, right?

**Right?**

#### Mistake 16

Check out the following code:

**Code**

What is the time complexity of this?

**Solution**

#### Mistake 17

Let's look at the following simple code.

**Code**

Can you guess where the bug is?

**Bug**

#### Mistake 18

Consider the following code to count unique elements in an array.

**Code**

What's wrong with this code?

**Bug**

#### Mistake 19

Lots of mistakes can happen while doing modular arithmetic.

**Example Mistakes**

**Where are the Bugs?**

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:

**Code**

It doesn't output $$$3 \cdot 10^{12}$$$.

**Why?**

#### 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:

**Solution**

You can do similar stuff for `cbrt()`

too.

#### Mistake 22

Check this out.

**Code**

What is the time complexity of this solution?

**Check**

#### More Mistakes

- Do not
`insert`

or`erase`

from a container (`set`

,`vector`

etc) while traversing it using`for (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 value`rand()`

generates is`32767`

? 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 as`long long`

, at times, might be 2 times slower than`int`

. Use`long 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 getting`Runtime 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 as`1`

is`int`

and doing`1 << 40`

will produce the result in`int`

, but $$$2^{40}$$$ is way too large to be stored in an`int`

variable. To fix this issue, use`1LL << 40`

(basically set the type of`1`

to`long long`

first, check here).- While comparing two floating point numbers, instead of
`if (a == b)`

, use`if (abs(a - b) < eps)`

where`eps = 1e-9`

or something similar to avoid precision issues. - If you want to take the ceiling of
`a / b`

where`a`

and`b`

are positive integers, then do`(a + b - 1) / b`

, instead of`ceil(1.0 * a / b)`

. For floors just use`a / 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 the`Solve - 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

He makes miskates

But i make mistakes

Nice Blog

nice blog but miskates in 3rd line make me laughing.

Mistake 3 is unclear to me, does creating a vector also has time complexity?

Creating a vector and pre-defining value definitely has time complexity. (2nd argument when creating vector)

OMG, huge informative. Thanks Shohag vai.

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 is`RAND_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.

The headline should be YouKn0wWho style!

style!The ultimate mistakes in CP & ultimate way to avoid them (❁´◡`❁)

thanks brother for making this awesome blog

thanks vaiya for this informative blog. I hope one day we will meet vaiya...

Very helpful tutorial, thank you! Will definitely forward this to my students who are starting competitive programming.

SpoilerBut 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.Thanks for this blog .

Thank you vai❤️

Great post! It's always helpful to learn from others' mistakes, especially when starting out in competitive programming. The examples and explanations provided in this post really helped me understand common pitfalls and how to avoid them. The interactive approach of giving readers the chance to find the bugs before revealing the solution is a great way to engage and teach. I'll definitely be keeping these tips in mind as I continue to hone my skills. Thanks for sharing!

Just sharing my mistake listWrong 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 of`1ll << x`

has cost me a problem in a contestsame.

Nice initiative. Helpful and informative.

You are a legend!

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.

Next codeforces round when?

I suffered a lot from

Mistake 9one 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 :)

hmm

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 hence`true`

but it is evaluated as`5 ^ (5 == 0)`

to`5 ^ 0`

to`5`

.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.The well-known typoThe dead by `#define`From dp to brute-forcesAssuming $$$g(x)$$$ is a function that got recalculated each time when called wrong.

Which type of code do you do then ?

or

or

And binary searchWhich type of code do you use on real numbers ?

or

or

In floating point calculationWhich of the following formula do you use:

or

And guess what can be wrong with thisThis might not ended up as what you expectedYou missed a loop somewhere, didnt you ?Your favorite bignum ?Ah yes, just add this for any problem and hope it will ACIs this an even number ?Some compilers will just help you while the judges won'tUsing

`sqrt()`

without declaring`<cmath>`

In Mistake 14 you can use

`!mp.count(i)`

instead of`mp.found(i) != mp.end()`

if you want a shorter version of it. Although I think`mp.count(i)`

is slower than`mp.found(i)`

that is because`found(i)`

stops at the first occurrence of`i`

unlike`count(i)`

which has to travel the whole map.most mistakes are related to c++ only

how does one really go about proving their solutions ? Do you mean to say a proper mathematical proof or just logical but exhaustive arguments for correctness ? It can be insanely hard to come up with a proper proof for newbies (like me).

Very nice blog, thanks

Wow, huge info in a single artilce,

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

bro i think Mistake 3 s time complexity is 100000(100000+n), isn't it ? anyway very very thanks.

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

I want to do competitive programming I have solved 76 problems in Codeforces .But now I try to solve every day But I can't solve problems every day And I can't do any math related problems Now what can i do please help me your best suggestion