Debugging and Systematic Troubleshooting Questions
Diagnosing defects methodically: reproducing failures, forming and testing hypotheses, reading stack traces and logs, bisecting changes, and reasoning about error handling and edge cases. Covers a disciplined root-cause approach that applies from local bugs to production issues, distinct from embedded hardware-level debugging. A universally probed engineering-craft skill.
You receive this Android crash stack trace from a user's device:
FATAL EXCEPTION: main
Process: com.example.app, PID: 12345
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.app.ui.MainActivity.onCreate(MainActivity.java:45)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3000)
Identify the most likely root cause, what you would check in the source at that file and line, and two possible fixes.
Sample Answer
Direct answer
The trace shows a NullPointerException at MainActivity.onCreate(MainActivity.java:45) calling setText on a TextView that is null. The most likely root cause: findViewById for that TextView returned null, almost always because setContentView(...) was called with the wrong layout resource (or not called before the findViewById), or the ID referenced doesn't exist in the layout that actually got inflated (a common cause when the app has multiple layout variants, e.g., separate layout and layout-land XML files, and the ID was added to only one).
Structured elaboration
- Check line 45 of
MainActivity.javadirectly to see which view is being set and whichfindViewByIdcall produced it. - Check the order of
setContentViewandfindViewById. IffindViewByIdruns beforesetContentView, or targets a different content view than the one shown, it will returnnullfor every view ID, since there's no inflated view tree yet to search. - Check for layout-variant mismatches. If the app has alternate layout resources for different screen sizes, orientations, or API levels (
res/layout-land,res/layout-sw600dp, etc.), confirm the view ID referenced actually exists in ALL variants that could be inflated at runtime, not just the one the developer was looking at while writing the code. This is one of the most common real-world causes of this exact crash pattern, since it only manifests on devices/configurations that load the variant missing the ID. - Check for a recent layout XML change that renamed or removed the view ID without updating the corresponding
findViewByIdcall, which is a very common source of this bug after a UI refactor. - Confirm the reproduction path. Since this came from a specific user's device (a crash report, not a local repro), check whether the crash correlates with a specific device model, OS version, or locale, any of which could imply a specific layout variant or resource configuration being loaded.
Two possible fixes, addressing the two most likely root causes:
- If
setContentViewwas called with the wrong layout resource: fix the argument to point at the correct layout that actually contains the referenced view ID. - If the view ID genuinely doesn't exist in a particular layout variant (e.g., a landscape-only layout is missing a view present in portrait): either add the missing view to that variant, or guard the code with a null check before calling
setText, if the view is legitimately optional in some layouts.
Worked example
A crash report shows this NPE occurring only on tablet devices; checking the project's resource folders reveals a layout-sw600dp (tablet-specific) variant of the activity's layout that was created for a redesign but never had the TextView with that specific ID added to it, unlike the phone layout. The fix: add the missing view to the tablet layout (or, if it's intentionally absent there, guard the setText call with a null check specific to that code path).
Trade-offs and pitfalls
A defensive null-check around the setText call would stop the crash but silently hides a genuine layout inconsistency, which is the wrong fix if the view was SUPPOSED to exist in every layout variant: the app now fails silently (missing UI element, no visible error) instead of crashing loudly, which is often harder to notice and diagnose later. The null check is the right fix only when the view is deliberately optional in some configurations; otherwise, fix the actual layout/inflation mismatch.
You receive a bug report: a routine that removes duplicates from an array in place is intermittently failing with out-of-bounds writes in production, but it works fine in tests. Describe how you would debug this, what tests you would add, and which language-specific pitfalls, such as signed versus unsigned indices, integer overflow, or aliasing, you would check first.
Sample Answer
Direct answer
The out-of-bounds write is almost certainly a signed/unsigned index mismatch or an off-by-one in the removal logic itself, both classic in-place-array-manipulation pitfalls that "works in tests" precisely because typical test arrays are small and don't happen to exercise the exact boundary condition that triggers the bug, while production data occasionally does.
Structured elaboration
- Reproduce with a boundary-focused test case first, rather than trying to guess from code review alone: specifically test with an array where duplicates occur near the END of the array (the last one or two elements), since in-place removal algorithms that shift elements left as duplicates are removed are especially prone to write-index errors exactly at the tail, where there's less "room" for an off-by-one to go unnoticed.
- Check for a signed/unsigned index mismatch specifically, since the question calls it out directly: if the write index is computed via a subtraction that can go negative in an edge case (e.g., removing duplicates from a very short array, or one that's ENTIRELY duplicates), and that index is stored in an unsigned integer type, a negative result wraps around to a huge positive value, producing a write far outside the array's actual bounds, which is a classic C/C++/embedded-systems bug (also possible in any language with explicit unsigned integer types) and matches the "out-of-bounds write" symptom precisely, as opposed to a simple off-by-one which would typically write just one slot too far, not wildly out of bounds.
- Check for integer overflow in any index arithmetic if the array or index values could be large enough to approach the integer type's limit, though this is less likely to be the specific cause here unless the array sizes involved are unusually large.
- Check for aliasing/in-place-mutation hazards: if the removal logic reads from and writes to the SAME underlying array simultaneously (common in an in-place algorithm), a read that should happen BEFORE a corresponding write, but doesn't due to a loop-ordering bug, can produce corrupted results distinct from, but sometimes confused with, an out-of-bounds write; confirming which specific failure mode is occurring (via the debugger or a sanitizer) avoids fixing the wrong mechanism.
- What tests to add once the specific mechanism is found: boundary cases specifically (duplicates at the very start, very end, an array that's entirely duplicates, an array with no duplicates at all, a single-element array, an empty array), since these are exactly the cases most likely to expose an off-by-one or signed/unsigned bug that a "typical" test case with duplicates scattered comfortably in the middle would never exercise.
Worked example
Reproducing with an array that's ENTIRELY duplicate values (an aggressive boundary case) triggers the crash reliably, where a more typical mixed test case doesn't. Stepping through with a debugger shows the write index computed as write_pos = write_pos - 1 at one point in the loop, intended to "back up" one slot when a duplicate is detected, but under this specific input pattern, write_pos reaches zero and then goes negative on the next iteration; since it's declared as an unsigned type, that negative value wraps to a very large positive number, and the subsequent array write at that "index" is wildly out of bounds, matching the crash symptom exactly. Fix: change the index variable to a signed type (allowing the intermediate negative value to be handled correctly, with an explicit check before it's ever used as an actual array index) or restructure the loop logic to avoid ever needing to decrement below zero in the first place, whichever better fits the surrounding code's conventions.
Trade-offs and pitfalls
A naive fix like clamping the index to zero whenever it "looks" negative, without understanding WHY it went negative, risks silently producing a different, subtler correctness bug (skipping or duplicating an element) instead of a crash, which is arguably worse, since it fails silently rather than loudly; understanding the exact arithmetic that produces the negative value, and fixing the LOGIC rather than just guarding the symptom, is what actually resolves it correctly.
A production API sometimes returns elements in an inconsistent order across clients because sets are used internally. You are responsible for triage: how do you investigate, explain the nondeterminism to stakeholders, and implement a stable ordering for the API output while keeping acceptable performance?
Sample Answer
Direct answer
Sets in most languages make no guarantee about iteration order, so building API output directly from set iteration produces order that can legitimately differ across processes, language/runtime versions, or even between runs of the SAME process, depending on internal hash-table implementation details; the investigation confirms this mechanism directly, then implements a stable, explicit ordering rather than relying on incidental set-iteration behavior.
Structured elaboration
How to investigate: confirm the specific code path building the API response iterates over a set (or a dict/map in a language where iteration order isn't guaranteed) rather than a list or an explicitly sorted structure; reproduce by calling the endpoint multiple times, or across multiple server instances/processes, and diffing the returned element order directly, which should show inconsistency if a set is indeed the cause, versus consistent-but-simply-unexpected order from some other source (like a database query with no explicit ORDER BY, a related but distinct cause worth ruling out with the same investigative approach).
Explaining the nondeterminism to stakeholders: frame it precisely: this isn't a random or buggy failure, it's the EXPECTED behavior of an unordered collection, and the API was implicitly promising an ordering guarantee it was never actually designed to provide; different clients (or the same client at different times) can legitimately see different orderings today, which may have gone unnoticed as long as most callers didn't depend on order, until a specific consumer's logic (or a stricter test) started depending on stability that was never actually guaranteed.
Implementing stable ordering while maintaining acceptable performance:
- Sort explicitly at the point of serialization, using whatever ordering makes sense for the API's actual semantics (alphabetical, insertion order if that's meaningful and trackable, or a natural key like an ID or timestamp); for most APIs, the cost of sorting a response-sized collection (typically not enormous) is negligible compared to the request's other costs (network, serialization itself).
- If insertion order specifically needs to be preserved (and the language's default set doesn't track it), switch to an ordered-set-like structure if the language provides one (some languages/standard libraries offer collections that combine set semantics with insertion-order iteration), avoiding a separate sort step while still gaining determinism.
- For very large collections where sorting cost genuinely matters, consider whether the ordering can be established earlier in the pipeline (e.g., if the data already comes from a sorted source like a database query with an explicit
ORDER BY, preserving that order through to the response rather than passing it through an unordered set at any intermediate step) rather than re-sorting a large collection at serialization time on every request.
Worked example
Confirming the mechanism: the endpoint's handler collects results into a set (used originally just to deduplicate, with no awareness that its iteration order would become externally visible), then serializes that set directly to the response. Diffing repeated calls to the same endpoint shows genuinely different orderings across calls, confirming set-iteration nondeterminism as the mechanism (as opposed to, for example, a database query lacking an explicit sort, which would tend to be consistent WITHIN one server/database session but could still differ across sessions or after a schema change, a related but mechanistically distinct possibility worth ruling out explicitly rather than assuming). Fix: after deduplicating via the set (keeping that step, since dedup itself is still correct and desired), explicitly convert to a list and sort it by a natural, stable key (the item's own ID) before serializing, at negligible added cost relative to the rest of the request, resolving the nondeterminism while preserving the original deduplication behavior.
Trade-offs and pitfalls
The temptation to "fix" this by simply switching the internal data structure to something that happens to iterate in insertion order today, without an EXPLICIT sort, risks re-introducing the same class of bug if the underlying collection or its implementation ever changes in a future language/runtime version; an explicit, intentional sort at the serialization boundary is more robust than relying on an implementation detail of whatever collection happens to be used internally, even if that detail is currently observed to be stable.
Write a memory-efficient Python function parse_log_counts(file_path, top_n=5) that scans a large server log file, which may be larger than available memory, and returns the top N error types or HTTP status codes by count without loading the whole file into memory. Example lines: 2025-01-01T12:00:00Z INFO request_id=1 status=200 and 2025-01-01T12:00:01Z ERROR request_id=2 status=500 exception=ValueError. Describe edge cases and how your implementation handles gzipped logs and malformed lines.
Sample Answer
Direct answer
Stream the file line by line instead of loading it into memory, maintaining only a bounded Counter of error-type/status-code totals as you go, which keeps memory usage proportional to the number of DISTINCT keys seen rather than the number of lines in the file. Handling gzipped input just means picking the right file-opening function based on the extension; handling malformed lines means skipping them without crashing the whole scan.
Structured elaboration
import gzip
from collections import Counter
from typing import List, Tuple
def parse_log_counts(file_path: str, top_n: int = 5) -> List[Tuple[str, int]]:
counts = Counter()
opener = gzip.open if file_path.endswith('.gz') else open
with opener(file_path, 'rt', errors='replace') as f:
for line in f:
line = line.rstrip('\n')
if not line:
continue
status, exc = None, None
for tok in line.split():
if tok.startswith('status='):
status = tok.split('=', 1)[1]
elif tok.startswith('exception='):
exc = tok.split('=', 1)[1]
if exc:
counts[f'exception:{exc}'] += 1
elif status:
counts[f'status:{status}'] += 1
# lines with neither field are silently skipped as malformed
return counts.most_common(top_n)
Key design points:
- Iterating
for line in freads one line at a time from the underlying file object rather than materializing the whole file in memory; this is what makes the function safe against a 10GB+ input. gzip.openversusopenare chosen based on the file extension, so the same function transparently handles both compressed and uncompressed logs without the caller needing to know which.errors='replace'on the text-mode open prevents a single malformed byte sequence (a truncated write, a binary artifact mid-file) from raising aUnicodeDecodeErrorand aborting the entire scan.- Lines with neither a
status=norexception=token are simply skipped rather than raising, satisfying "handle malformed lines" without crashing on them. Counter.most_common(top_n)does the top-N selection in O(k log n) where k is the number requested, more efficient than sorting the entire counts dictionary when only a few top entries are needed.
Worked example
A synthetic log with 50 status=200 lines, 12 exception=ValueError lines, 8 exception=TimeoutError lines, 20 status=404 lines, plus two malformed lines (one garbage line, one blank):
plain file: [('status:200', 50), ('status:404', 20), ('exception:ValueError', 12), ('exception:TimeoutError', 8)]
gzipped file: [('status:200', 50), ('status:404', 20), ('exception:ValueError', 12), ('exception:TimeoutError', 8)]
top_n=2: [('status:200', 50), ('status:404', 20)]
The gzipped and plain versions of the identical content produce byte-identical results, confirming the compression branch works correctly, and top_n=2 correctly truncates to the two highest counts without needing a separate code path.
Edge cases
- Empty file: the loop simply never executes,
countsstays empty, andmost_common(top_n)returns an empty list, no special-casing needed. - File with only malformed lines: same result, an empty list, which is the correct behavior (nothing to report) rather than an error.
- A line with BOTH
status=andexception=: the current implementation prioritizesexception:(checked first), which is a deliberate choice since an exception is generally the more specific and actionable signal; this priority should be called out explicitly rather than left as an implicit accident of code order. top_nlarger than the number of distinct keys:most_commonsimply returns all available entries, no error.
Trade-offs and pitfalls
This implementation keeps ALL distinct keys in memory (bounded by the number of distinct error types/status codes, not the number of log lines, which is normally small), but if the log contained a very high-cardinality field mistakenly counted this way (say, counting by full request URL instead of status code), memory could still grow unboundedly with the number of distinct values; the safety guarantee here specifically relies on error types and status codes being a naturally small, bounded set.
Given these simplified application logs:
2025-05-01T10:12:01Z [INFO] Start request id=abc123 user=42
2025-05-01T10:12:01Z [ERROR] Database timeout after 30s query='SELECT * FROM orders WHERE id=?' id=42
2025-05-01T10:12:02Z [INFO] End request id=abc123 status=504
What is the most likely cause of the error, and what is your first investigative step? Explain what you would check in the database and the application to reproduce and isolate the timeout.
Sample Answer
Direct answer
The database timeout for id=42 is the direct, proximate cause: the query SELECT * FROM orders WHERE id=? took longer than 30 seconds and was aborted, which propagated up as a 504 (gateway timeout) to the caller. The first investigative step is checking whether that timeout is isolated to this one request/row (a lock, a corrupted index, a full table scan on a specific value) or part of a broader pattern (all queries against this table are slow right now, pointing at load, a missing index, or a database-wide issue).
Structured elaboration
- Read the log sequence in order. The request starts (
Start request), 30 seconds later the database call itself reports a timeout on a specific query with a specific parameter, and the request ends with a 504. This tells you the 504 isn't a generic gateway problem; it has a specific, identified cause one layer down: the query never completed. - Check whether this is isolated or systemic. Query the database's own slow-query log or active-query view for the same time window: are OTHER queries against the
orderstable also running long, or is this specific toid=42? If it's isolated to specific IDs, suspect row-level lock contention (another transaction holding a lock on that row) or a data anomaly specific to that row. If it's systemic, suspect load, a missing/degraded index, or a resource constraint on the database host. - Check the query plan. Run
EXPLAINon the exact query to confirm it's using an index onidas expected; a missing or invalidated index (from a recent migration, a statistics update, or a query planner regression) would turn what should be an instant primary-key lookup into a full table scan, and that would degrade specifically under load or as the table grows, matching an intermittent-timeout symptom. - Check for lock contention specifically. Query the database's lock/transaction views for anything holding a lock on the
ordersrow withid=42at that timestamp; a long-running transaction elsewhere in the system (a batch job, a stuck transaction that never committed) can block an otherwise-instant query indefinitely. - Reproduce and isolate. Once you have a hypothesis (say, a missing index), reproduce the slow query directly against a copy of the database outside the application, confirm the fix (adding the index, or fixing the transaction that was holding a lock) actually resolves the timing, before deploying it.
- Check the application side too, not just the database. Pull the application's own metrics for that window: was there a concurrent spike in request volume or a burst of retries hitting this same endpoint that could itself be driving DB load, independent of any query-plan or locking issue? Check the application's connection-pool usage and configured statement timeout: if the pool was saturated, requests could queue on the application side before ever reaching the database, which looks identical to a slow query from the caller's point of view. Also check whether the application (or a client library's default) is retrying failed calls in a way that amplifies load on the exact query that's already struggling.
Worked example
Checking the database's active-queries view for that exact timestamp shows several OTHER queries against orders also running unusually long, all doing primary-key lookups that should be near-instant. EXPLAIN on the query confirms it's doing a full table scan, not an index seek. Checking recent schema changes shows an index on orders.id was dropped as part of an unrelated migration two days earlier, under the mistaken assumption it was redundant with the primary key, when in fact the table used a different clustering key (the column the database physically sorts and stores rows by on disk; looking a row up by a different column can't reuse that fast physical ordering, so the database falls back to a full table scan). Re-adding the index resolves the timeouts across the board, confirming it as a systemic (not row-specific) cause.
Trade-offs and pitfalls
The trap is fixating on the SPECIFIC request (id=42) and trying to reproduce a timeout on exactly that row, when the actual cause is systemic and would show up on any query hitting the same missing index; checking for a broader pattern FIRST, before deep-diving one instance, avoids wasting time chasing a red herring that happens to be specific to the one log line you were handed.
Unlock Full Question Bank
Get access to all 40 Debugging and Systematic Troubleshooting interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.