The 34 errors and slips that come up most while solving DSA problems in Python, Java and C++: the message you'll see, what it means, where it usually comes from, and a broken and fixed example. Every message here is the real one, checked against the same versions the in-browser editor runs. Got an error in the editor? Its What does this mean? link lands on the right entry here.
How to read an error
1Read the last line firstIt names the error and says what went wrong. The lines above it are the path the program took to get there.
2Then the line numberGo to that line. For syntax errors, check the line just above it too: a missing colon or bracket is often reported one line late.
3Then the failing inputIn the editor, the test that broke shows its input. Run that input by hand on paper: empty lists, one element and negatives cause most errors.
Before it runs
The code can't be read or compiled, so nothing runs. The message names the line: start there, or just above it.
The code breaks the language's grammar, so it can't even be read. Python wants a colon after if / for / while / def; Java and C++ want a semicolon after each statement.
In DSA problems: Usually a missing colon after for i in range(n) or if left < right, or a missing semicolon after i++ in Java and C++. The line it names is sometimes the one after the real mistake.
Breaks (Python)
def total(nums):
s = 0
for x in nums
s += x
return s
Fixed
def total(nums):
s = 0
for x in nums:
s += x
return s
How to fix it
โLook at the line it names, then the line just above it.
โPython: a colon ends every if, elif, else, for, while, def and class line.
โJava / C++: a semicolon ends every statement; braces come in pairs.
PythonIndentationError: expected an indented block after 'for' statement on line 1
PythonIndentationError: unexpected indent
PythonIndentationError: unindent does not match any outer indentation level
In Python the indent is the structure: the lines inside an if or a loop are the ones indented under it. A line indented too much, too little, or not at all breaks that.
In DSA problems: Common after pasting code, or after leaving a loop: the return lands inside the loop (it then runs on the first pass) or one space off from the lines around it.
Breaks (Python)
def has_zero(nums):
for x in nums:
if x == 0:
return True
return False
Fixed
def has_zero(nums):
for x in nums:
if x == 0:
return True
return False
How to fix it
โIndent with 4 spaces per level (Tab in this editor inserts them).
โEverything inside a for / if / def sits one level deeper than its line.
โMixing tabs and spaces looks fine and still fails: retype the indent.
An opening ( [ or { has no partner, so the language reads to the end of the file looking for it.
In DSA problems: Nested calls like max(best, len(s[i:j]) and long conditions are the usual suspects; in Java and C++, a missing } after an if or a loop.
Breaks (Python)
def longest(words):
best = 0
for w in words:
best = max(best, len(w)
return best
Fixed
def longest(words):
best = 0
for w in words:
best = max(best, len(w))
return best
How to fix it
โCount the brackets on the line it names: every ( [ { needs its ) ] }.
โPython may name the line where the bracket opened, or the next line.
โThis editor closes brackets as you type them, so the pair stays together.
PythonUnboundLocalError: cannot access local variable 'count' where it is not associated with a value
Javaerror: cannot find symbol
C++error: 'total' was not declared in this scope
A variable or function is used before it exists, or under a slightly different name. Python only finds out when that line runs; Java and C++ refuse to compile. UnboundLocalError is the same mistake inside a function: count += 1 before count = 0.
In DSA problems: A typo (lenght, nums vs num), a counter never set to 0, forgetting self. before a method of the Solution class, or a nested DFS helper doing count += 1 on the outer function's variable (it needs nonlocal count).
Breaks (Python)
def count_evens(nums):
evens = 0
for x in nums:
if x % 2 == 0:
evens += 1
return even
Fixed
def count_evens(nums):
evens = 0
for x in nums:
if x % 2 == 0:
evens += 1
return evens
How to fix it
โCheck the spelling against where it was created.
โCreate counters and results before the loop, not inside it.
โInside the Solution class, call your own helpers as self.helper(...).
โA nested helper changing an outer variable: declare it with nonlocal (or use self.count).
Javaerror: incompatible types: possible lossy conversion from long to int
Javaerror: incompatible types: String cannot be converted to char
C++error: cannot convert 'std::vector<int>' to 'int' in initialization
Java and C++ check every value's type before running. Putting a long into an int (it might not fit), a String into a char, or a whole list into a single number is refused.
In DSA problems: int mid = (long) left + right style mixes, char c = "a" (double quotes make a String; a char uses single quotes), and returning int[] where the signature says List<Integer>.
Breaks (Java)
class Main {
static int sum(int[] nums) {
long total = 0;
for (int x : nums) total += x;
return total;
}
public static void main(String[] a) { System.out.println(sum(new int[]{1, 2})); }
}
Fixed
class Main {
static long sum(int[] nums) {
long total = 0;
for (int x : nums) total += x;
return total;
}
public static void main(String[] a) { System.out.println(sum(new int[]{1, 2})); }
}
How to fix it
โMake the types agree: return a long, or cast with (int) when you know it fits.
โSingle quotes for a char ('a'), double quotes for a String ("a").
โMatch the return type in the starting code's signature exactly.
Java proves that every path through a function returns a value. If a loop or an if can finish without returning, it refuses to compile. C++ compiles it anyway and returns garbage on that path, which is worse.
In DSA problems: A search that returns inside the loop when it finds the answer, with nothing after the loop for when it doesn't (binary search, two pointers, "find the index").
Breaks (Java)
class Main {
static int find(int[] nums, int target) {
for (int i = 0; i < nums.length; i++)
if (nums[i] == target) return i;
}
public static void main(String[] a) { System.out.println(find(new int[]{4, 7}, 7)); }
}
Fixed
class Main {
static int find(int[] nums, int target) {
for (int i = 0; i < nums.length; i++)
if (nums[i] == target) return i;
return -1;
}
public static void main(String[] a) { System.out.println(find(new int[]{4, 7}, 7)); }
}
How to fix it
โAdd the "not found" return after the loop (often -1, false or an empty list).
โIn C++, the same fix: never let a non-void function fall off the end.
Javaerror: variable sum might not have been initialized
A local variable is read before it has a value. Java refuses; C++ allows it and the variable holds whatever was in memory, so results change from run to run.
In DSA problems: int sum; or int best; declared and then updated in a loop. Give it a starting value: 0 for sums, the first element or a huge value for minimums.
Breaks (Java)
class Main {
public static void main(String[] a) {
int sum;
for (int x : new int[]{1, 2, 3}) sum += x;
System.out.println(sum);
}
}
Fixed
class Main {
public static void main(String[] a) {
int sum = 0;
for (int x : new int[]{1, 2, 3}) sum += x;
System.out.println(sum);
}
}
How to fix it
โGive every local variable a value where you declare it.
โMinimums start at Integer.MAX_VALUE (or the first element), maximums at Integer.MIN_VALUE.
While it runs
It started, then hit something impossible: an index past the end, a missing key, an empty stack. The test that broke shows the input that caused it.
Javajava.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Javajava.lang.StringIndexOutOfBoundsException
C++vector::_M_range_check: __n (which is 3) >= this->size() (which is 3)
LeetCodeAddressSanitizer: heap-buffer-overflow
An index past the last element (or below 0 in Java and C++). A list of length n has indexes 0 to n โ 1, so nums[n] is already one too far. In C++, v[i] doesn't check at all: it reads garbage or crashes; LeetCode's checker reports it as a heap-buffer-overflow.
In DSA problems: The most common error in DSA. Looking ahead with nums[i + 1] on the last index, range(len(nums) + 1), while i <= len(s), two pointers that step past each other, and nums[0] on an empty input.
Breaks (Python)
def count_rises(nums):
rises = 0
for i in range(len(nums)):
if nums[i + 1] > nums[i]:
rises += 1
return rises
Fixed
def count_rises(nums):
rises = 0
for i in range(len(nums) - 1):
if nums[i + 1] > nums[i]:
rises += 1
return rises
How to fix it
โFind the largest index the line can reach and check it against len - 1.
โLooking at i + 1? Stop the loop one early.
โHandle an empty input before touching nums[0].
โTwo pointers: loop while left < right (or <=), and check after moving them.
Javajava.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is null
Reading a key the dictionary doesn't have. Python raises KeyError; Java's get returns null, which crashes as soon as it's used as a number. C++'s map[key] silently adds the key with 0, which hides the bug instead.
In DSA problems: Counting with count[x] += 1 before x is in the map, or looking up a complement in Two Sum without checking it's there first.
Breaks (Python)
def freq(s):
count = {}
for ch in s:
count[ch] += 1
return count
Fixed
def freq(s):
count = {}
for ch in s:
count[ch] = count.get(ch, 0) + 1
return count
How to fix it
โPython: count.get(key, 0), if key in count, or collections.Counter / defaultdict(int).
โJava: map.getOrDefault(key, 0), or map.merge(key, 1, Integer::sum).
โC++: map.count(key) or map.find(key) before reading, when adding it isn't what you want.
PythonAttributeError: 'NoneType' object has no attribute 'next'
Javajava.lang.NullPointerException
This editorSegmentation fault
Something that should be a node (or an object) is actually None / null, and the code reaches into it. In C++ that's a null pointer, and the program crashes with a segmentation fault.
In DSA problems: Linked lists and trees, all the time: node.next.next when node.next is the last node, root.left.val on a leaf, or a function that returns None in one branch.
Breaks (Python)
class Node:
def __init__(self, val, next=None):
self.val, self.next = val, next
def middle(head):
slow = fast = head
while fast.next:
slow, fast = slow.next, fast.next.next
return slow.val
Fixed
class Node:
def __init__(self, val, next=None):
self.val, self.next = val, next
def middle(head):
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
return slow.val
How to fix it
โBefore reading x.next or x.left, make sure x itself isn't None.
โFast and slow pointers: loop while fast and fast.next.
โRecursion on trees: the first line handles if not root.
PythonTypeError: list indices must be integers or slices, not float
In Python, / always gives a float (7 / 2 is 3.5, and even 4 / 2 is 2.0), and a list can't be indexed with a float. // divides and rounds down to a whole number.
In DSA problems: Binary search: mid = (left + right) / 2. Use //. Java and C++ don't have this problem, since int / int is already a whole number there.
Breaks (Python)
def search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) / 2
if nums[mid] == target:
return mid
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
Fixed
def search(nums, target):
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
How to fix it
โUse // whenever the result is an index or a count.
Set items and dictionary keys must never change, and a list can. So a list can't go in a set or be a key; a tuple (which can't change) can.
In DSA problems: Group Anagrams (groups[sorted(word)]), keeping visited [row, col] cells in a set, or storing a path as a key. Turn it into a tuple first.
Breaks (Python)
def group(words):
groups = {}
for w in words:
groups.setdefault(sorted(w), []).append(w)
return list(groups.values())
Fixed
def group(words):
groups = {}
for w in words:
groups.setdefault(tuple(sorted(w)), []).append(w)
return list(groups.values())
How to fix it
โUse tuple(lst) as the key or set item.
โGrid cells: (r, c), not [r, c].
โFor strings, ''.join(sorted(w)) works as a key too.
PythonTypeError: 'str' object does not support item assignment
A Python string can't be edited: s[i] = ... is refused. (Java's String is the same: there's no setter.) Build a new string, or edit a list of characters and join it.
In DSA problems: Reversing, swapping characters, or replacing letters in place: Reverse Vowels, valid palindromes after edits, string compression.
Breaks (Python)
def reverse(s):
i, j = 0, len(s) - 1
while i < j:
s[i], s[j] = s[j], s[i]
i, j = i + 1, j - 1
return s
Fixed
def reverse(s):
chars = list(s)
i, j = 0, len(chars) - 1
while i < j:
chars[i], chars[j] = chars[j], chars[i]
i, j = i + 1, j - 1
return ''.join(chars)
How to fix it
โchars = list(s), edit chars, then ''.join(chars).
โJava: a char[] (s.toCharArray()) or a StringBuilder.
โAdding to a string in a loop makes a new one each time: collect pieces in a list and join once.
PythonTypeError: unsupported operand type(s) for +: 'int' and 'str'
PythonTypeError: can only concatenate str (not "int") to str
PythonTypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
An operation between values that don't go together: a number plus a string, or None plus a number (usually a helper that forgot to return).
In DSA problems: Building an answer string from numbers ('#' + count), digit problems mixing '7' and 7, and recursive helpers that return None on one path, then get added up.
Breaks (Python)
def encode(words):
out = ''
for w in words:
out += len(w) + '#' + w
return out
Fixed
def encode(words):
out = ''
for w in words:
out += str(len(w)) + '#' + w
return out
How to fix it
โstr(n) to put a number in a string, int(s) to use a digit string as a number.
โf-strings mix both safely: f'{count}#{word}'.
โ'NoneType' in the message: something returned nothing. Check every return path.
A function was called with more or fewer values than it takes. Inside a class, Python passes the object as the first argument (self), so a method written without self gets one argument too many.
In DSA problems: LeetCode's Solution class: def twoSum(nums, target) without self, or calling your own helper as helper(x) instead of self.helper(x).
Breaks (Python)
class Solution:
def double(nums):
return [2 * x for x in nums]
Fixed
class Solution:
def double(self, nums):
return [2 * x for x in nums]
How to fix it
โEvery method in the class starts with self.
โKeep the parameters from the starting code exactly.
โCount the arguments in the call against the def line.
Dividing (or taking % of) a number by 0. C++ crashes with a "floating point exception", even for whole numbers.
In DSA problems: An average of an empty list, x % k with k = 0, slopes between two points with the same x (Max Points on a Line), and Koko-style rates when the speed starts at 0.
Breaks (Python)
def average(nums):
return sum(nums) / len(nums)
Fixed
def average(nums):
if not nums:
return 0
return sum(nums) / len(nums)
How to fix it
โCheck the divisor before dividing: empty input, k == 0, equal x values.
โBinary search on a speed or capacity: start the low end at 1, not 0.
PythonValueError: max() iterable argument is empty
PythonIndexError: index out of range
Javajava.util.EmptyStackException
Javajava.util.NoSuchElementException
Popping or peeking at an empty stack, queue or heap, or taking the max of nothing. C++ doesn't check: st.top() on an empty stack reads garbage or crashes.
In DSA problems: Valid Parentheses with a closing bracket first ()(), monotonic stacks popping one time too many, BFS queues, and heaps in k-largest problems.
Breaks (Python)
def is_valid(s):
pairs = {')': '(', ']': '['}
stack = []
for ch in s:
if ch in pairs:
if stack.pop() != pairs[ch]:
return False
else:
stack.append(ch)
return not stack
Fixed
def is_valid(s):
pairs = {')': '(', ']': '['}
stack = []
for ch in s:
if ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
else:
stack.append(ch)
return not stack
How to fix it
โCheck if stack (or !st.empty()) before pop, top or peek.
โMonotonic stack: while stack and ..., with the emptiness check first.
โmax() / min() of something that might be empty: max(nums, default=0).
PythonRecursionError: maximum recursion depth exceeded
Javajava.lang.StackOverflowError
This editorSegmentation fault
A function called itself too many times without finishing. Usually the base case is missing or never reached, so it would recurse forever; sometimes the input is just very deep (Python stops at about 1000 calls).
In DSA problems: A base case that misses (if n == 0 when n can skip past 0, if not node missing), recursing on the same input (f(n) instead of f(n - 1)), or DFS on a graph without a visited set, going back and forth between two nodes.
Breaks (Python)
def count_down_steps(n):
if n == 0:
return 0
return 1 + count_down_steps(n - 2)
Fixed
def count_down_steps(n):
if n <= 0:
return 0
return 1 + count_down_steps(n - 2)
How to fix it
โWrite the base case first, and make it catch every way the input can end (<= 0, not node).
โMake sure each call gets closer to it (n - 1, node.left).
โGraphs: mark a node visited before recursing into its neighbours.
โReally deep but correct? Rewrite it as a loop with your own stack.
C++ read or wrote memory it doesn't own, and the operating system stopped it. There's no friendly message: it's always one of a few causes.
In DSA problems: An index outside the vector (v[i] doesn't check), a null pointer (node->next when node is nullptr), st.top() on an empty stack, or recursion so deep the call stack runs out.
Breaks (C++)
#include <bits/stdc++.h>
using namespace std;
struct Node { int val; Node* next; };
int second(Node* head) { return head->next->val; }
int main() { Node a{1, nullptr}; cout << second(&a); }
Fixed
#include <bits/stdc++.h>
using namespace std;
struct Node { int val; Node* next; };
int second(Node* head) { return head && head->next ? head->next->val : -1; }
int main() { Node a{1, nullptr}; cout << second(&a); }
How to fix it
โUse v.at(i) while debugging: it throws out_of_range with the index instead of crashing.
โCheck pointers before -> (if (!node) ...).
โCheck .empty() before top(), front() or back().
โThe test that crashed shows the input: try it by hand.
PythonRuntimeError: dictionary changed size during iteration
Javajava.util.ConcurrentModificationException
Adding or removing items from the collection a loop is walking through. Dictionaries and sets in Python, and lists in Java, refuse. A Python list doesn't complain: it silently skips items, which is worse.
In DSA problems: Removing zero counts from a frequency map inside the loop, deleting from a list while filtering it, or changing an adjacency list while traversing it.
Breaks (Python)
def drop_zeros(count):
for k in count:
if count[k] == 0:
del count[k]
return count
Fixed
def drop_zeros(count):
for k in list(count):
if count[k] == 0:
del count[k]
return count
How to fix it
โLoop over a copy: for k in list(d).
โOr build a new one: {k: v for k, v in d.items() if v}.
โJava: an Iterator's remove(), or removeIf(...).
Runs, but the answer is wrong
No error at all, just a wrong answer. These are the classic slips that pass a glance and fail the tests.
A Python function without a return (or that ends without reaching one) returns None. The tests then see None instead of your answer.
In DSA problems: Building the answer in a variable and never returning it, returning only inside an if, or calling a recursive helper without returning its result (self.dfs(...) instead of return self.dfs(...)).
Breaks (Python)
def squares(nums):
out = [x * x for x in nums]
Fixed
def squares(nums):
out = [x * x for x in nums]
return out
Prints None, then [1, 4] once fixed.
How to fix it
โEnd the function with return answer.
โRecursive helpers: return the recursive call's result.
โEvery branch of an if / else returns something.
You'll notice: The answer appears under "What your code printed", and every test still fails.
The tests call your function and look at what it returns. Printing the answer shows it on screen, but the function still returns None.
In DSA problems: Very common coming from HackerRank-style problems that read input and print output. On LeetCode and here, the values arrive as parameters and the answer goes out with return.
Breaks (Python)
def add(a, b):
print(a + b)
Fixed
def add(a, b):
return a + b
Prints 5 ยท returned None, then returned 5 once fixed.
How to fix it
โReturn the answer; print only to debug.
โNo input() either: the parameters are the input.
You'll notice: Your output is one more or one less than expected, often only on some tests.
A loop that runs one time too many or too few, or a range that includes or skips one element. range(a, b) stops before b; a window from i to j has j โ i + 1 elements.
In DSA problems: Binary search bounds (< or <=, mid or mid ยฑ 1), window lengths (right - left + 1), the last element of a loop, and inclusive vs exclusive ranges in prefix sums.
Breaks (Python)
def longest_ones(nums):
best = left = 0
for right, x in enumerate(nums):
if x == 0:
left = right + 1
best = max(best, right - left)
return best
Fixed
def longest_ones(nums):
best = left = 0
for right, x in enumerate(nums):
if x == 0:
left = right + 1
best = max(best, right - left + 1)
return best
Prints 2, then 3 once fixed.
How to fix it
โTry the smallest inputs by hand: one element, two elements.
โWindow from left to right, both included: right - left + 1.
โBinary search: pick one template (left <= right with mid ยฑ 1) and stick to it.
You'll notice: The right number of answers, but all of them empty (or all the same).
res.append(path) stores the list itself, not a snapshot. Backtracking keeps changing path (and empties it at the end), so every saved answer ends up the same, usually empty.
In DSA problems: Subsets, Permutations, Combination Sum and every other backtracking problem: the answer has the right count of lists, all empty or identical.
Breaks (Python)
def subsets(nums):
res, path = [], []
def go(i):
if i == len(nums):
res.append(path)
return
go(i + 1)
path.append(nums[i])
go(i + 1)
path.pop()
go(0)
return res
Fixed
def subsets(nums):
res, path = [], []
def go(i):
if i == len(nums):
res.append(path[:])
return
go(i + 1)
path.append(nums[i])
go(i + 1)
path.pop()
go(0)
return res
Prints [[], [], [], []], then [[], [2], [1], [1, 2]] once fixed.
How to fix it
โSave a copy: res.append(path[:]) or list(path).
โJava: res.add(new ArrayList<>(path)). C++ copies on push_back already.
You'll notice: The first test passes; later ones fail with answers that include earlier tests' values.
Something outlives one call: a class-level variable, a global, or a default argument like seen=[] (created once and reused). The first test passes; later ones see its leftovers.
In DSA problems: A memo dict or counter declared on the class instead of inside the method, or def dfs(node, path=[]). LeetCode runs many tests in one go, so this fails there too.
LeetCoderuntime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
An int holds up to about 2.1 billion (2ยณยน โ 1). Go past it and Java wraps around to a negative number with no warning; in C++ it's undefined behaviour, which LeetCode reports as a runtime error. Python's integers never overflow.
In DSA problems: Sums and products of big values, mid = (left + right) / 2 with large indexes, and counting answers that need % 1_000_000_007. Look for constraints like nums[i] โค 10โน.
Breaks (Java)
class Main {
public static void main(String[] a) {
int left = 1_500_000_000, right = 2_000_000_000;
int mid = (left + right) / 2;
System.out.println(mid);
}
}
Fixed
class Main {
public static void main(String[] a) {
int left = 1_500_000_000, right = 2_000_000_000;
int mid = left + (right - left) / 2;
System.out.println(mid);
}
}
Prints -397483648, then 1750000000 once fixed.
How to fix it
โmid = left + (right - left) / 2.
โUse long (Java) or long long (C++) for sums and products of big values.
โBig counts: take % 1_000_000_007 after every addition or multiplication.
Python's // rounds down (โ7 // 2 is โ4) and % follows it (โ7 % 3 is 2); Java and C++ round toward zero (โ7 / 2 is โ3) and % can be negative (โ7 % 3 is โ1). Same code, different answers.
In DSA problems: Evaluate Reverse Polish Notation (division truncates toward zero), negative prefix sums with % k (Subarray Sums Divisible by K), and hashing with negative numbers.
Breaks (Python)
def divide(a, b):
return a // b
Fixed
def divide(a, b):
return int(a / b)
Prints -4, then -3 once fixed.
How to fix it
โNeed truncation toward zero in Python? int(a / b).
โNeed a non-negative remainder in Java / C++? ((x % k) + k) % k.
โRead the problem: "truncate toward zero" is a hint.
In Java, == on objects (Integer, String, lists) asks "is this the same object?", not "is the value equal?". It happens to work for small Integers (โ128 to 127) and literal strings, which makes the bug look random.
In DSA problems: Comparing counts read from two HashMaps (map1.get(c) == map2.get(c)), stack tops (stack.peek() == x), and strings built in a loop.
Breaks (Java)
import java.util.*;
class Main {
public static void main(String[] a) {
Map<Character, Integer> m1 = new HashMap<>(), m2 = new HashMap<>();
m1.put('a', 1000); m2.put('a', 1000);
System.out.println(m1.get('a') == m2.get('a'));
}
}
Fixed
import java.util.*;
class Main {
public static void main(String[] a) {
Map<Character, Integer> m1 = new HashMap<>(), m2 = new HashMap<>();
m1.put('a', 1000); m2.put('a', 1000);
System.out.println(m1.get('a').equals(m2.get('a')));
}
}
Prints false, then true once fixed.
How to fix it
โCompare objects with .equals() (or Objects.equals(a, b) when either may be null).
โUnbox first when you mean numbers: int x = map.get(k).
Too slow, too big, or wrong on LeetCode
LeetCode's verdicts when the code is correct on small inputs but not good enough.
This editorStopped after 5 seconds. Is there a loop that never ends?
LeetCodeTime Limit Exceeded
Either the loop never ends, or the approach does far too much work for the input size. Both look the same: no answer in time.
In DSA problems: A while loop whose pointers don't move on some branch (binary search with left = mid), or an O(nยฒ) loop where n is 10โต. Rule of thumb: about 10โธ simple steps per second, so n = 10โต needs O(n log n) or better.
Breaks (Python)
def has_pair(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return True
return False
Fixed
def has_pair(nums, target):
seen = set()
for x in nums:
if target - x in seen:
return True
seen.add(x)
return False
Prints True, then True once fixed.
How to fix it
โEndless loop? Check that every branch moves a pointer or shrinks the input.
โRead the constraints: n โค 10โต rules out O(nยฒ).
โRepeated searching โ a hash set or map; repeated sums โ prefix sums; sorted input โ binary search or two pointers.
The program keeps too much at once: a huge table, a copy of the input on every call, or a list that grows forever in a loop.
In DSA problems: A full 2D DP table when only the previous row is needed, slicing lists in recursion (nums[1:] copies every time), or a queue that never stops growing because visited nodes are added again.
Breaks (Python)
def total(nums):
if not nums:
return 0
return nums[0] + total(nums[1:])
Fixed
def total(nums, i=0):
if i == len(nums):
return 0
return nums[i] + total(nums, i + 1)
Prints 6, then 6 once fixed.
How to fix it
โPass an index instead of slicing (nums[i:] copies).
โDP that only looks one row back: keep two rows, not the whole table.
โBFS / DFS: mark visited when you add to the queue, not when you pop.
You'll notice: All tests pass in the editor; LeetCode says Wrong Answer and shows one failing input.
The sample tests pass, but LeetCode's hidden tests include cases the samples don't: empty input, one element, duplicates, negatives, the largest values.
In DSA problems: LeetCode shows the failing input after a Wrong Answer: run that exact input by hand. It's almost always one of the edge cases below.
Breaks (Python)
def max_sum(nums):
best = 0
cur = 0
for x in nums:
cur = max(x, cur + x)
best = max(best, cur)
return best
Fixed
def max_sum(nums):
best = nums[0]
cur = 0
for x in nums:
cur = max(x, cur + x)
best = max(best, cur)
return best
Prints 0, then -1 once fixed.
How to fix it
โTry: empty input, one element, all equal, all negative, already sorted, the maximum size.
โDon't start a best value at 0 when every answer could be negative.