YouKn0wWho's blog

By YouKn0wWho, 15 months ago, In English

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.

See you on a later episode, friend blobheart!

  • Vote: I like it
  • +634
  • Vote: I do not like it

| Write comment?
»
15 months ago, # |
Rev. 2   Vote: I like it +1 Vote: I do not like it

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"

»
15 months ago, # |
  Vote: I like it +70 Vote: I do not like it

I wonder whether you type "mistakes" as "miskates" in the first paragraph on purpose

»
15 months ago, # |
  Vote: I like it +1 Vote: I do not like it

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.

»
15 months ago, # |
  Vote: I like it +3 Vote: I do not like it

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.

»
15 months ago, # |
  Vote: I like it +66 Vote: I do not like it

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

Spoiler
»
15 months ago, # |
Rev. 2   Vote: I like it +7 Vote: I do not like it
Just sharing my mistake list
  • »
    »
    15 months ago, # ^ |
      Vote: I like it +19 Vote: I do not like it

    Thanks for sharing! Added some of them to the blog.

  • »
    »
    15 months ago, # ^ |
      Vote: I like it +8 Vote: I do not like it

    thanks for sharing! in TLE: 4'th line, what is "taking mod less times, use compile time constant for mod"

»
15 months ago, # |
  Vote: I like it 0 Vote: I do not like it

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 &

»
15 months ago, # |
  Vote: I like it +33 Vote: I do not like it

Using 1 << x instead of 1ll << x has cost me a problem in a contest

»
15 months ago, # |
  Vote: I like it +8 Vote: I do not like it

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)

»
15 months ago, # |
  Vote: I like it +26 Vote: I do not like it

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.

»
15 months ago, # |
Rev. 5   Vote: I like it +8 Vote: I do not like it

for mistake 7 we can simply use vector v; cout<<int(v.size())-1<<'\n';

»
15 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

.

»
15 months ago, # |
  Vote: I like it +29 Vote: I do not like it

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.

  • »
    »
    15 months ago, # ^ |
      Vote: I like it +19 Vote: I do not like it

    Relatable. I did this too multiple times. Added it to the blog. Thanks.

»
15 months ago, # |
  Vote: I like it +14 Vote: I do not like it

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.

»
15 months ago, # |
  Vote: I like it +8 Vote: I do not like it

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

»
15 months ago, # |
  Vote: I like it +21 Vote: I do not like it

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 :/)

	common bugs:
		overflow
		divide by zero
		overflow
		remains by zero
		my compare function (do not determinane unique ...)
		set instead of multiset
		overflow
		0 base, 1 base
		default value of variables
		remain can be negative
		correct mod
		mod%mod==0
		overflow
		small inf
		big inf
		i != j
		1 << i != i << 1
		corner case (n = 1, n = 2, n = MAXN)
		ans must be returned by mod

»
15 months ago, # |
  Vote: I like it +27 Vote: I do not like it

Great blog!

Forgetting to reset a global array in multitest is also a classic error.

»
15 months ago, # |
  Vote: I like it +8 Vote: I do not like it

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.

»
15 months ago, # |
  Vote: I like it +8 Vote: I do not like it

how can I be better at proofing greedy?

»
15 months ago, # |
  Vote: I like it +8 Vote: I do not like it

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.

  • »
    »
    15 months ago, # ^ |
      Vote: I like it +11 Vote: I do not like it

    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)

»
15 months ago, # |
Rev. 2   Vote: I like it +16 Vote: I do not like it

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.

»
15 months ago, # |
Rev. 3   Vote: I like it +8 Vote: I do not like it
The well-known typo
The dead by `#define`
From dp to brute-forces
And binary search
In floating point calculation
And guess what can be wrong with this
This might not ended up as what you expected
You missed a loop somewhere, didnt you ?
Your favorite bignum ?
Ah yes, just add this for any problem and hope it will AC
Is this an even number ?
Some compilers will just help you while the judges won't
»
15 months ago, # |
  Vote: I like it +11 Vote: I do not like it

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.

»
15 months ago, # |
  Vote: I like it +16 Vote: I do not like it

most mistakes are related to c++ only

»
15 months ago, # |
  Vote: I like it 0 Vote: I do not like it

In mistake 2, why did you typecast a.size() into int??? I know that size() function returns an integer value.

  • »
    »
    15 months ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    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

»
14 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Thanks!

»
14 months ago, # |
  Vote: I like it +3 Vote: I do not like it

Mistake n+1, view the scoreboard in contest time

»
14 months ago, # |
  Vote: I like it 0 Vote: I do not like it

For python, 3.8 does not have math.lcm but my machine has it. It caused me some damage today. Link

»
10 months ago, # |
  Vote: I like it 0 Vote: I do not like it

very much helpful for me

»
9 months ago, # |
  Vote: I like it 0 Vote: I do not like it

great vai

»
9 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Must needed for cpers. Thanks for this!

»
9 months ago, # |
  Vote: I like it 0 Vote: I do not like it

This is made of love, thanks a lot man! Appreciate that a lot!

»
9 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Awesome Blog!

»
9 months ago, # |
  Vote: I like it 0 Vote: I do not like it

your code for mistake 18 contains mistake 3

»
9 months ago, # |
Rev. 2   Vote: I like it 0 Vote: I do not like it

about mistake 20, I had a similar mistake once, the following will overflow:

vector<int> arr = {INT_MAX, INT_MAX};
vector<long long> prefix_sum(2);
partial_sum(begin(arr), end(arr), begin(prefix_sum));

If you really want to use the STL, this works:

inclusive_scan(begin(arr), end(arr), begin(prefix_sum), plus<long long>(), 0LL);
»
2 months ago, # |
  Vote: I like it 0 Vote: I do not like it

Just revisited this amazing blog, no doubt one of the absolute best!