The short answer
Use the language you already write most often. If you are starting fresh, use Python for interviews, C++ for competitive programming, and Java if the jobs you want are Java jobs. The rest of this page explains why.
- Interviews: Python. Less typing leaves more time to explain and test.
- Contests with one time limit for every language: C++. It is the fastest of the three.
- Backend roles at Java companies: Java. The interviewer reads it without effort.
One problem, three languages
Here is Two Sum with the same algorithm in each language: keep a hash map from value to index, and for each number check whether the value it needs is already in the map.
def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
if target - x in seen:
return [seen[target - x], i]
seen[x] = i
return []vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> seen;
for (int i = 0; i < (int)nums.size(); i++) {
auto it = seen.find(target - nums[i]);
if (it != seen.end()) return {it->second, i};
seen[nums[i]] = i;
}
return {};
}public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer j = seen.get(target - nums[i]);
if (j != null) return new int[] { j, i };
seen.put(nums[i], i);
}
return new int[0];
}The Python version is seven lines and has no types to declare. The C++ and Java versions are nine lines each and need a type on the map, the loop counter and the return value. Two lines is a small gap here, but it grows on problems that need a heap, a custom sort order or a pair of values, because Python has tuples and short syntax for all three.
Python: short code, hidden costs
Python is quick to write because its built-in types do a lot in one call. The risk is that a call which looks cheap can be slow, and the code gives no hint. These four cause most Python failures on LeetCode.
queue = [start]
node = queue.pop(0) # O(n): shifts every element
from collections import deque
queue = deque([start])
node = queue.popleft() # O(1)Python also removes one whole class of bug: its integers never overflow. A sum that needs 64 bits, or 200 bits, just works.
list.pop(0)is O(n), because every later element shifts left. A BFS that uses a list as its queue becomes O(n²). Usecollections.dequeandpopleft(), which is O(1).heapqis a min-heap only. For a max-heap, push the negative of each value and negate again when you pop.- The recursion limit is 1000 by default. A recursive DFS on a tree that is one long chain of 10,000 nodes stops with
RecursionError. Raise the limit withsys.setrecursionlimit, or write the DFS with your own stack. s += chinside a loop can copy the whole string each time, which is O(n²) in total. Collect the pieces in a list and call''.join(parts)once at the end.
C++: fastest, and the easiest to break
C++ runs fastest and its standard library has every container a DSA problem needs. In exchange, it compiles code that is wrong and gives no warning. Three bugs come up again and again.
int total = 0;
for (int x : nums) total += x; // overflows past about 2.1 billion
long long total2 = 0; // fix
for (int i = 0; i < v.size() - 1; i++) // empty v: runs out of bounds
for (int i = 0; i + 1 < (int)v.size(); i++) // fix
if (seen[x] > 0) { } // inserts x when it is missing
if (seen.count(x)) { } // fix- Integer overflow. An
intholds about 2.1 billion. Adding 100,000 values of up to 1,000,000,000 reaches 10¹⁴, which does not fit. The result is garbage, not an error. Uselong longfor sums and products. size() - 1on an empty vector.size()returns an unsigned number, so0 - 1becomes a huge positive value and the loop runs far past the end. Cast first:(int)v.size() - 1.map[key]inserts the key. Readingseen[x]whenxis missing addsxwith value 0. A laterseen.count(x)then says the key exists. Usefindorcountwhen you only want to look.
Java: explicit, with one famous trap
Java makes you write every type, which is slower to type but easy for an interviewer to follow. Its best-known trap is comparing two Integer objects with ==.
Deque<Integer> stack = new ArrayDeque<>();
Deque<Integer> mins = new ArrayDeque<>();
stack.push(1000);
mins.push(1000);
if (stack.peek() == mins.peek()) { } // false: compares two objects
if (stack.peek().equals(mins.peek())) { } // true: compares the values== on two Integer objects checks whether they are the same object, not whether they hold the same number. Java reuses one object for each value from -128 to 127, so the bug stays hidden on small test values and appears only on large ones. This is the usual reason a Min Stack solution passes the examples and fails on submit.
intoverflow wraps around silently, as in C++. Uselongfor large sums.- A comparator written as
(a, b) -> a - boverflows when the two values are far apart. UseInteger.compare(a, b). - Joining strings with
+in a loop is O(n²). UseStringBuilder.
Does speed matter?
On LeetCode and in interviews, rarely. What decides pass or fail is the complexity of the algorithm. An O(n²) solution on 100,000 elements is too slow in every language, and an O(n log n) solution passes in every language.
Speed matters on contest sites that set one time limit for all languages. There, a correct Python solution can time out where the same algorithm in C++ passes, because a simple loop in Python runs many times slower. That is why most competitive programmers use C++.
A rule for choosing
Pick one language and stay with it until you can write a hash map, a heap, a queue, a sort with a custom order and a recursive DFS without looking anything up. Switching languages halfway through your preparation costs more than any language saves.
- You already know one of the three well: use it.
- You are new and want interviews: Python.
- You want contests: C++.
- You are applying for Java roles: Java.