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

Integer behaviour by language
TopicC#PythonJavaC++
int overflowWraps silently (unchecked by default); checked throws OverflowExceptionNever: int has arbitrary precisionWraps silently; Math.addExact and friends throwSigned overflow is undefined behaviour; unsigned wraps modulo 2ⁿ
Width of int32 bits (long 64)Unbounded32 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 minimumMath.Abs(int.MinValue) throwsFineMath.abs(Integer.MIN_VALUE) returns MIN_VALUEUndefined behaviour
Safe midpointlo + (hi - lo) / 2(lo + hi) // 2 is safelo + (hi - lo) / 2 or (lo + hi) >>> 1lo + (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 str raises ValueError unless the limit is raised (sys.set_int_max_str_digits).
  • Products overflow before sums do: a * b of two 32-bit values needs 64 bits. Widen before multiplying, not after.
  • Floating point: 0.1 + 0.2 != 0.3 in all four languages. Compare with a tolerance, or keep money and counts in integers.

Strings and Unicode

What length and indexing count
TopicC#PythonJavaC++
StorageUTF-16, immutableCode points, immutableUTF-16, immutablestd::string: bytes (usually UTF-8), mutable
length countsUTF-16 code units (s.Length)Code points (len(s))UTF-16 code units (s.length())Bytes (s.size())
One indexed elementchar: one code unit; emoji take twoA one-code-point strchar: one code unitOne byte; non-ASCII letters take several
Code pointsRune, s.EnumerateRunes()Already code pointss.codePoints(), codePointAtDecode UTF-8 yourself or use a library
Build in a loopStringBuilder"".join(parts)StringBuilderstd::string::append / += (amortized O(1))
None of these count user-perceived characters (grapheme clusters): "é" can be one or two code points, and a flag emoji is two. Reversing or slicing by index can split them.

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

Which end comes out first by default
TopicC#PythonJavaC++
DefaultPriorityQueue<TElement, TPriority>: smallest priority first (min-heap)heapq: min-heapPriorityQueue<E>: smallest first (natural order)std::priority_queue: largest first (max-heap)
Flip itComparer<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 priorityNot supported: insert again and skip stale entriesNot supported: same lazy-deletion trickremove(Object) is O(n); prefer lazy deletionNot supported

Equality and hashing contracts

What a hash key needs
TopicC#PythonJavaC++
ContractOverride Equals and GetHashCode together (or implement IEquatable<T>); records do it for youEqual objects need equal __hash__; defining __eq__ alone makes a class unhashableOverride equals and hashCode together; records do it for youNeeds std::hash<Key> (or a custom hasher) and operator==
Common trapMutating a key after inserting it loses the entrylist and dict are unhashable: use tuple or frozensetArrays use identity: an equal int[] copy never finds the entry; use List<Integer> or Arrays.hashCodeNo 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

Changing a collection while looping over it
TopicC#PythonJavaC++
List / arrayChanging a List<T> in foreach throws InvalidOperationExceptionRemoving from a list while iterating silently skips elementsConcurrentModificationException (best effort, fail-fast)vector::push_back may reallocate and invalidate every iterator, pointer and reference; erase invalidates from the erased point on
Map / setDictionary allows Remove during enumeration (.NET Core 3.0+); adding throwsChanging a dict or set size raises RuntimeErrorSame fail-fast exception; use Iterator.remove or removeIfunordered_map rehash invalidates iterators, not references; erase invalidates only the erased element
Safe patternCollect, then modify; or RemoveAllIterate over a copy, or build a new listremoveIf, Iterator.removestd::erase_if (C++20), or it = c.erase(it)

More traps

Missing keys
C# indexer throws KeyNotFoundException; Python d[k] raises KeyError; Java get returns null (unboxing it to int throws); 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 throws StackOverflowError, in C++ is undefined. Convert deep DFS to an explicit stack.
Shared rows
Python [[0] * m] * n repeats 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 int is uninitialised (std::vector<int>(n) is zeroed).
Comparator subtraction
(a, b) => a - b overflows for large values in C# and Java; use CompareTo / Integer.compare.

References