Basics for coding rounds · core
Integer types, operators and overflow
An int holds about 2.1 x 10^9. Many Wrong Answers in coding tests come from overflow, from unsigned sizes, or from changing one variable twice in one line.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- int is 32 bits on common systems: -2,147,483,648 to 2,147,483,647 (about 2.1 x 10^9). long long is at least 64 bits: up to about 9.2 x 10^18.
- long is 64 bits on Linux but only 32 bits on 64-bit Windows. Use long long when you need 64 bits.
- Signed overflow is undefined behaviour. The value often wraps to a negative number, but the compiler may also assume overflow never happens and produce strange results.
long long x = a * b;with int a and b still overflows, because the multiplication happens in int first. Write1LL * a * b, or make a and b long long.- Unsigned arithmetic wraps modulo 2^n. v.size() is unsigned, so
v.size() - 1on an empty vector is a huge number, andi < v.size() - 1runs far past the end. - Integer division cuts toward zero: 7 / 2 is 3 and -7 / 2 is -3. The remainder takes the sign of the left side: -7 % 2 is -1. Dividing by zero is undefined.
- i++ gives the old value and then adds one; ++i adds one and gives the new value. Changing the same variable twice in one expression, as in
i++ + ++i, is undefined behaviour in C++ too. - Counting pairs: n(n - 1)/2 for n = 2 x 10^5 is about 2 x 10^10, which does not fit in int. Use long long for counts and sums.
The red pen
Common traps: mistake → fix
Mistake: long long x = a * b is safe
Fix: a * b is computed in int and overflows before the assignment.
Mistake: long is always 64 bits
Fix: it is 32 bits on 64-bit Windows.
Mistake: Overflow always gives a negative number
Fix: signed overflow is undefined; anything can happen.
Mistake: -7 % 2 is 1
Fix: it is -1 in C++.
Easy to hard
Questions interviewers ask, easy to hard
- What is the largest value an int can hold? When do you use long long?
- Your pair count is right for small tests but negative for a big one. Why?
- Why is
for (int i = 0; i < v.size() - 1; i++)dangerous? - What does
int j = i++ + ++i;give, and why is there no single right answer?
Practise
Practise with these questions
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.