Cheatsheet
Language gotchas for DSA
Overflow, division, Unicode, heap orientation, hashing contracts and iterator invalidation: where C#, Python, Java and C++ differ in DSA code.
Version 1 · updated 2026-11-24
Integers and arithmetic
| Topic | C# | Python | Java | C++ |
|---|---|---|---|---|
int overflow | Wraps silently (unchecked by default); checked throws OverflowException | Never: int has arbitrary precision | Wraps silently; Math.addExact and friends throw | Signed overflow is undefined behaviour; unsigned wraps modulo 2ⁿ |
Width of int | 32 bits (long 64) | Unbounded | 32 bits (long 64) | At least 16 bits, 32 on mainstream platforms; use int64_t when it matters |
-7 / 2 and -7 % 2 | -3, -1 (truncates toward zero) | -7 // 2 is -4, -7 % 2 is 1 (floors) | -3, -1 | -3, -1 (truncation fixed since C++11) |
| Absolute value of the minimum | Math.Abs(int.MinValue) throws | Fine | Math.abs(Integer.MIN_VALUE) returns MIN_VALUE | Undefined behaviour |
| Safe midpoint | lo + (hi - lo) / 2 | (lo + hi) // 2 is safe | lo + (hi - lo) / 2 or (lo + hi) >>> 1 | lo + (hi - lo) / 2 or std::midpoint (C++20) |
- Python big ints are exact but not free: arithmetic slows down as the number of digits grows, and since 3.11 converting an int with more than 4,300 digits to
strraisesValueErrorunless the limit is raised (sys.set_int_max_str_digits). - Products overflow before sums do:
a * bof two 32-bit values needs 64 bits. Widen before multiplying, not after. - Floating point:
0.1 + 0.2 != 0.3in all four languages. Compare with a tolerance, or keep money and counts in integers.
Strings and Unicode
| Topic | C# | Python | Java | C++ |
|---|---|---|---|---|
| Storage | UTF-16, immutable | Code points, immutable | UTF-16, immutable | std::string: bytes (usually UTF-8), mutable |
length counts | UTF-16 code units (s.Length) | Code points (len(s)) | UTF-16 code units (s.length()) | Bytes (s.size()) |
| One indexed element | char: one code unit; emoji take two | A one-code-point str | char: one code unit | One byte; non-ASCII letters take several |
| Code points | Rune, s.EnumerateRunes() | Already code points | s.codePoints(), codePointAt | Decode UTF-8 yourself or use a library |
| Build in a loop | StringBuilder | "".join(parts) | StringBuilder | std::string::append / += (amortized O(1)) |
Repeated s = s + x on an immutable string copies the whole string each time: O(n²) for n appends in general. Use a builder.
Heap orientation
| Topic | C# | Python | Java | C++ |
|---|---|---|---|---|
| Default | PriorityQueue<TElement, TPriority>: smallest priority first (min-heap) | heapq: min-heap | PriorityQueue<E>: smallest first (natural order) | std::priority_queue: largest first (max-heap) |
| Flip it | Comparer<T>.Create((a, b) => b.CompareTo(a)) | Negate numeric keys, or heapq.heappush_max and friends (Python 3.14+) | new PriorityQueue<>(Comparator.reverseOrder()) | std::priority_queue<T, std::vector<T>, std::greater<T>> |
| Change a priority | Not supported: insert again and skip stale entries | Not supported: same lazy-deletion trick | remove(Object) is O(n); prefer lazy deletion | Not supported |
Equality and hashing contracts
| Topic | C# | Python | Java | C++ |
|---|---|---|---|---|
| Contract | Override Equals and GetHashCode together (or implement IEquatable<T>); records do it for you | Equal objects need equal __hash__; defining __eq__ alone makes a class unhashable | Override equals and hashCode together; records do it for you | Needs std::hash<Key> (or a custom hasher) and operator== |
| Common trap | Mutating a key after inserting it loses the entry | list and dict are unhashable: use tuple or frozenset | Arrays use identity: an equal int[] copy never finds the entry; use List<Integer> or Arrays.hashCode | No standard std::hash for std::pair or std::tuple |
| Value vs identity | == on string compares values | == compares values, is identity | == on objects compares identity (Integer boxes outside −128…127 differ); use equals | == compares values for standard containers |
Iterator invalidation and modification during iteration
| Topic | C# | Python | Java | C++ |
|---|---|---|---|---|
| List / array | Changing a List<T> in foreach throws InvalidOperationException | Removing from a list while iterating silently skips elements | ConcurrentModificationException (best effort, fail-fast) | vector::push_back may reallocate and invalidate every iterator, pointer and reference; erase invalidates from the erased point on |
| Map / set | Dictionary allows Remove during enumeration (.NET Core 3.0+); adding throws | Changing a dict or set size raises RuntimeError | Same fail-fast exception; use Iterator.remove or removeIf | unordered_map rehash invalidates iterators, not references; erase invalidates only the erased element |
| Safe pattern | Collect, then modify; or RemoveAll | Iterate over a copy, or build a new list | removeIf, Iterator.remove | std::erase_if (C++20), or it = c.erase(it) |
More traps
- Missing keys
- C# indexer throws
KeyNotFoundException; Pythond[k]raisesKeyError; Javagetreturnsnull(unboxing it tointthrows); C++map[k]silently inserts a default value. - Recursion depth
- Python stops at 1,000 frames by default (
sys.getrecursionlimit); deep recursion in C# terminates the process, in Java throwsStackOverflowError, in C++ is undefined. Convert deep DFS to an explicit stack. - Shared rows
- Python
[[0] * m] * nrepeats one row object n times; use[[0] * m for _ in range(n)]. - Default values
- C#, Java and Python containers start initialised; a local C++ array of
intis uninitialised (std::vector<int>(n)is zeroed). - Comparator subtraction
(a, b) => a - boverflows for large values in C# and Java; useCompareTo/Integer.compare.
References
- checked and unchecked statements — Microsoft Learn
- Integer string conversion length limitation — Python documentation
- heapq — Heap queue algorithm — Python documentation
- Object.hashCode contract — Java SE 21 API
- ConcurrentModificationException — Java SE 21 API
- Object.GetHashCode Method — Microsoft Learn
- Arithmetic operators (overflow, division) — cppreference.com
- std::vector (iterator invalidation) — cppreference.com
- Character encoding in .NET — Microsoft Learn