Android & iPhone apps are coming soon. Log in for a plan and reminders made for you โ†’

Debugging

Errors to look out for

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

  1. 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.
  2. 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.
  3. 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.

Syntax error

PythonJavaC++

You'll see

  • PythonSyntaxError: expected ':'
  • Javaerror: ';' expected
  • C++error: expected ',' or ';' before '}' token

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.

Indentation error

Python

You'll see

  • 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.

Unclosed bracket or brace

PythonJavaC++

You'll see

  • PythonSyntaxError: '(' was never closed
  • Javaerror: reached end of file while parsing
  • C++error: expected '}' at end of input

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.

Name not defined

PythonJavaC++

You'll see

  • PythonNameError: name 'count' is not defined
  • 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).

Incompatible types

JavaC++

You'll see

  • 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.

Missing return statement

Java

You'll see

  • Javaerror: missing return statement

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.

Variable might not have been initialized

Java

You'll see

  • 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.

Index out of range

PythonJavaC++

You'll see

  • PythonIndexError: list index out of range
  • PythonIndexError: string index out of range
  • 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.

Key not found

PythonJava

You'll see

  • PythonKeyError: 'b'
  • 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.

Using None / null

PythonJava

You'll see

  • 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.

Object is not iterable

Python

You'll see

  • PythonTypeError: 'int' object is not iterable

for x in ... needs something to walk through (a list, a string, a range). A single number isn't one.

In DSA problems: Almost always for i in len(nums):. The loop over indexes is for i in range(len(nums)):.

Breaks (Python)
def total(nums):
    s = 0
    for i in len(nums):
        s += nums[i]
    return s
Fixed
def total(nums):
    s = 0
    for i in range(len(nums)):
        s += nums[i]
    return s

How to fix it

  • Indexes: for i in range(len(nums)).
  • Values: for x in nums.
  • Both: for i, x in enumerate(nums).

List index is a float

Python

You'll see

  • 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.
  • int(x) also works, but // says what you mean.

Unhashable type: 'list'

Python

You'll see

  • PythonTypeError: unhashable type: 'list'

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.

Strings can't be changed in place

Python

You'll see

  • 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.

Unsupported operand types

Python

You'll see

  • 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.

Wrong number of arguments

Python

You'll see

  • PythonTypeError: Solution.isEven() takes 1 positional argument but 2 were given
  • PythonTypeError: helper() missing 1 required positional argument: 'j'

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.

Division by zero

PythonJava

You'll see

  • PythonZeroDivisionError: division by zero
  • PythonZeroDivisionError: integer modulo by zero
  • Javajava.lang.ArithmeticException: / by zero
  • This editorFloating point exception

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.

Taking from an empty list, stack or heap

PythonJava

You'll see

  • PythonIndexError: pop from empty list
  • 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).

Too much recursion (stack overflow)

PythonJava

You'll see

  • 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.

Segmentation fault (C++)

C++

You'll see

  • This editorSegmentation fault
  • LeetCodeAddressSanitizer: SEGV on unknown address

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.

Changing a collection while looping over it

PythonJava

You'll see

  • 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.

Returned nothing (None)

Python

You'll see

  • This editorYour function returned nothing (None)

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.

sort(), append() and reverse() return None

Python

You'll notice: The test shows your output as None, though the list looked right.

Methods that change a list in place (sort, append, reverse, extend) return None, not the list. So nums = nums.sort() throws the list away.

In DSA problems: return nums.sort(), path = path.append(x) in backtracking, res = res.reverse(). Use sorted(nums) when you want a new sorted list.

Breaks (Python)
def sorted_squares(nums):
    nums = [x * x for x in nums]
    return nums.sort()
Fixed
def sorted_squares(nums):
    nums = [x * x for x in nums]
    nums.sort()
    return nums

Prints None, then [1, 4, 9] once fixed.

How to fix it

  • Call nums.sort() on its own line, then use nums.
  • Or return sorted(nums), which makes a new list.
  • Same for append, extend, reverse and list.remove.

Off by one

Python

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.

[[0] * n] * m shares one row

Python

You'll notice: Setting one cell changes the same column in every row.

[[0] * n] * m makes m references to the same row, so writing to one row writes to all of them. Each row needs to be its own list.

In DSA problems: DP tables and visited grids: dp = [[0] * cols] * rows makes every row change together and gives wrong answers with no error.

Breaks (Python)
grid = [[0] * 2] * 2
grid[0][0] = 1
print(grid)
Fixed
grid = [[0] * 2 for _ in range(2)]
grid[0][0] = 1
print(grid)

Prints [[1, 0], [1, 0]], then [[1, 0], [0, 0]] once fixed.

How to fix it

  • Build 2D lists with a comprehension: [[0] * cols for _ in range(rows)].
  • [0] * n is fine for one row: numbers aren't shared like lists are.

Appending the same list in backtracking

Python

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.

State left over between tests

Python

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.

Breaks (Python)
def add_item(x, items=[]):
    items.append(x)
    return items
Fixed
def add_item(x, items=None):
    if items is None:
        items = []
    items.append(x)
    return items

Prints [1, 2], then [2] once fixed.

How to fix it

  • Create memos, counters and results inside the method.
  • Default arguments: use None, then create the list inside.
  • Java / C++: fields on the Solution class start fresh per test only if you reset them.

Integer overflow (Java, C++)

Java

You'll see

  • Java-294967296
  • 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.

Division and % with negative numbers

PythonJava

You'll see

  • Python-4
  • Java-3

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.

== on objects in Java

Java

You'll see

  • Javafalse

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.

Too slow (Time Limit Exceeded)

Python

You'll see

  • 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.

Too much memory (Memory Limit Exceeded)

Python

You'll see

  • LeetCodeMemory Limit Exceeded
  • This editorMemoryError

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.

Passes here, Wrong Answer on LeetCode

Python

You'll see

  • LeetCodeWrong Answer

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.
  • Duplicates: does your set or map lose a count?