Coding Challenges: Debugging Production Issues
33 HackerRank-style challenges — 8 on Category 1: Crashes & Exceptions, 7 on Category 2: Performance, and 18 more spanning Categories 3-8 (Memory Leaks, Concurrency & Deadlocks, Data Corruption, Deployment & Environment, Database & API Failures, and Logging & Observability) — auto-graded right in your browser, no local install needed, standard library only. Write your function in the code box, then click Run Tests to check it against a set of test cases (including edge cases). Stuck? Every challenge has a Show Solution reveal at the bottom. Challenges 16-33 model the underlying logic of concurrency, deployment, and database bugs as plain, testable functions — the in-browser grader runs pure functions only, so a real deadlock or a real unpinned dependency can't literally run here the way the lesson's own runnable examples do.
1 Safe Config Get Easy
Write a function safe_get(d, key, default) that returns d[key] if key is present in the dict d, or default otherwise — without ever raising KeyError.
d is a dict; default can be any type.
safe_get({"a": 1}, "a", 0) → 1safe_get({"a": 1}, "b", 0) → 0
Show Solution
def safe_get(d, key, default):
return d.get(key, default)
2 Safe Index Sum Easy
Write a function safe_index_sum(values, indices) that sums values[i] for every i in indices, but skips any index that's out of range instead of raising IndexError.
values is a list of numbers; indices is a list of ints (may include negative or too-large indices).
safe_index_sum([1, 2, 3], [0, 1, 2]) → 6safe_index_sum([1, 2, 3], [0, 5, 10]) → 1
Show Solution
def safe_index_sum(values, indices):
total = 0
for i in indices:
if 0 <= i < len(values):
total += values[i]
return total
3 Catch Only What You Expect Easy
Write a function catch_only_keyerror(d, key, default) that returns d[key], catching only KeyError and returning default in that case — not a bare except:.
d is a dict.
catch_only_keyerror({"a": 1}, "a", 0) → 1catch_only_keyerror({"a": 1}, "b", 99) → 99
Show Solution
def catch_only_keyerror(d, key, default):
try:
return d[key]
except KeyError:
return default
4 Validate Before Arithmetic Easy
Write a function to_number(value) that converts value to a float, whether it arrives as a string like "10" or already as a number.
value is a string or a number that represents a valid number.
to_number("10") → 10.0to_number(10) → 10.0
Show Solution
def to_number(value):
return float(value)
5 Find Index or -1 Medium
Write a function find_index_or_negative_one(items, target) that returns the index of the first item equal to target, or -1 if nothing matches — never None, which would risk an AttributeError/TypeError downstream if a caller tries to use it as a number.
items is a list; target can be any type.
find_index_or_negative_one([10, 20, 30], 20) → 1find_index_or_negative_one([10, 20, 30], 99) → -1
Show Solution
def find_index_or_negative_one(items, target):
for i, item in enumerate(items):
if item == target:
return i
return -1
6 Safe Divide Medium
Write a function safe_divide(a, b) that returns a / b, or None if b is 0 — never raising ZeroDivisionError.
a and b are numbers.
safe_divide(10, 2) → 5.0safe_divide(10, 0) → None
Show Solution
def safe_divide(a, b):
if b == 0:
return None
return a / b
7 Is It Valid JSON? Medium
Write a function is_valid_json(raw_text) that returns True if raw_text can be parsed as JSON with json.loads(), or False otherwise — catching json.JSONDecodeError specifically, never letting it propagate.
raw_text is a string.
is_valid_json('{"a": 1}') → Trueis_valid_json("<html>err</html>") → False
Show Solution
import json
def is_valid_json(raw_text):
try:
json.loads(raw_text)
return True
except json.JSONDecodeError:
return False
8 Will the Countdown Terminate? Medium
A recursive countdown(n) function repeatedly adds step to n until n reaches exactly 0, then stops. Write a function will_terminate(n, step) that predicts — without actually recursing — whether that countdown will ever land exactly on 0 (True) or would recurse forever / hit RecursionError (False).
n and step are integers. If step is 0, the countdown never changes, so it terminates only if n is already 0.
will_terminate(5, -1) → True (5, 4, 3, 2, 1, 0)will_terminate(-5, -1) → False (-5, -6, -7, ... never reaches 0)will_terminate(5, -2) → False (5, 3, 1, -1, -3, ... skips over 0)
Show Solution
def will_terminate(n, step):
if step == 0:
return n == 0
if n == 0:
return True
# moving away from 0 -- n positive and step non-negative, or
# n negative and step non-positive -- can never reach 0
if (n > 0) != (step < 0):
return False
# otherwise, n reaches exactly 0 only if it's an exact multiple
# of step in the direction that closes the distance to 0
return n % step == 0
9 Has a Duplicate? Easy
Write a function has_duplicate(items) that returns True if any value appears more than once in items, or False otherwise. Use a set for the membership check, not repeated in checks against a list.
items is a list of hashable values (numbers or strings).
has_duplicate([1, 2, 3, 2]) → Truehas_duplicate([1, 2, 3]) → False
Show Solution
def has_duplicate(items):
seen = set()
for item in items:
if item in seen:
return True
seen.add(item)
return False
10 Reverse Without Inserting at the Front Easy
Write a function reverse_via_append(items) that returns a new list with items in reverse order, using only .append() and .reverse() — never .insert(0, x).
items is a list.
reverse_via_append([1, 2, 3]) → [3, 2, 1]
Show Solution
def reverse_via_append(items):
result = []
for item in items:
result.append(item)
result.reverse()
return result
11 Cached Uppercase Medium
Write a function cached_upper(keys) that returns a list [results, call_count], where results is key.upper() for every key in keys (in order), and call_count is how many times .upper() actually had to be computed — cache repeated keys so a repeated key is never recomputed.
keys is a list of strings.
cached_upper(["a", "b", "a"]) → [["A", "B", "A"], 2] (2 distinct keys, so only 2 real computations even though 3 lookups happened)
Show Solution
def cached_upper(keys):
cache = {}
call_count = 0
results = []
for key in keys:
if key not in cache:
call_count += 1
cache[key] = key.upper()
results.append(cache[key])
return [results, call_count]
12 Index Records by ID Medium
Write a function index_by_id(records) that builds a dict mapping each record's "id" value to the record itself, then returns it as a list of [id, record] pairs, sorted by id — the one-time setup step that turns a slow nested-loop lookup into a fast dict lookup.
records is a list of dicts, each with an "id" key.
index_by_id([{"id": 1, "name": "x"}]) → [[1, {"id": 1, "name": "x"}]]
Show Solution
def index_by_id(records):
by_id = {r["id"]: r for r in records}
return [[k, v] for k, v in sorted(by_id.items())]
13 Largest Without Sorting Easy
Write a function largest_of(numbers) that returns the largest value in numbers using max() — not sorted(numbers)[-1].
numbers is a non-empty list of numbers.
largest_of([3, 1, 4, 1, 5]) → 5
Show Solution
def largest_of(numbers):
return max(numbers)
14 Stop Early Medium
Write a function first_over_threshold(numbers, threshold) that returns the first value in numbers, doubled, that's greater than threshold — or None if none qualify. Loop and return as soon as a match is found; don't build a full list of every doubled value first.
numbers is a list of numbers; threshold is a number.
first_over_threshold([1, 2, 3, 4, 5], 3) → 4 (2 doubled is 4, the first doubled value over 3)
Show Solution
def first_over_threshold(numbers, threshold):
for n in numbers:
doubled = n * 2
if doubled > threshold:
return doubled
return None
15 Dict Membership, No .keys() Medium
Write a function dict_membership_check(d, keys_to_check) that returns a list of booleans — one per key in keys_to_check, True if that key is in d. Check membership directly against d, never d.keys().
d is a dict; keys_to_check is a list.
dict_membership_check({"a": 1, "b": 2}, ["a", "c"]) → [True, False]
Show Solution
def dict_membership_check(d, keys_to_check):
return [k in d for k in keys_to_check]
16 Bounded Cache Simulator Medium
Write a function bounded_cache_final_state(keys, maxsize) that simulates a simple least-recently-inserted cache: process keys in order, inserting each into the cache (a key already present is not re-inserted or moved). Once the cache would exceed maxsize entries, evict the oldest-inserted key first. Return the final list of keys still in the cache, oldest-inserted first.
keys is a list of hashable values; maxsize is a positive int.
bounded_cache_final_state(["a", "b", "c"], 2) → ["b", "c"] (a is evicted once c pushes past size 2)bounded_cache_final_state(["a", "a", "b"], 2) → ["a", "b"] (repeated "a" is not re-inserted)
Show Solution
def bounded_cache_final_state(keys, maxsize):
cache = []
for key in keys:
if key in cache:
continue
cache.append(key)
if len(cache) > maxsize:
cache.pop(0)
return cache
17 Deep-Copy-or-Not Detector Easy
Write a function would_shallow_copy_leak(original) that returns True if original is a dict containing at least one mutable value (a list or a dict) — meaning a plain .copy() of it would still share that nested value with the original — or False otherwise.
original is a dict; values are ints, strs, lists, or dicts.
would_shallow_copy_leak({"a": 1, "b": "x"}) → Falsewould_shallow_copy_leak({"a": 1, "items": [1, 2]}) → True
Show Solution
def would_shallow_copy_leak(original):
return any(isinstance(v, (list, dict)) for v in original.values())
18 Close Enough Medium
Write a function sums_to_target(values, target) that returns True if sum(values) is close enough to target to count as equal despite floating-point rounding error, using a tolerance-based comparison — never a plain == on floats.
values is a list of floats; target is a float. Use math.isclose.
sums_to_target([0.1] * 10, 1.0) → True (0.1 * 10 is 0.9999999999999999 in float math)sums_to_target([1, 2, 3], 100) → False
Show Solution
import math
def sums_to_target(values, target):
return math.isclose(sum(values), target, rel_tol=1e-9, abs_tol=1e-9)
19 Whole Units Only Easy
Write a function round_to_nearest_unit(quantity) that returns quantity rounded to the nearest whole number (as an int) — not truncated toward zero the way int() would silently do.
quantity is a float.
round_to_nearest_unit(4.9) → 5round_to_nearest_unit(4.1) → 4
Show Solution
def round_to_nearest_unit(quantity):
return round(quantity)
20 Zero-Based Page Slice Medium
Write a function get_page(records, page_number, page_size) that returns the correct slice of records for a 1-based page_number (page 1 is the first page). Never let an off-by-one error drop the first page's records.
records is a list; page_number and page_size are positive ints.
get_page([0,1,2,3,4,5,6,7,8,9], 1, 3) → [0, 1, 2]get_page([0,1,2,3,4,5,6,7,8,9], 2, 3) → [3, 4, 5]
Show Solution
def get_page(records, page_number, page_size):
start = (page_number - 1) * page_size
return records[start:start + page_size]
21 Fixed Column Order Medium
Write a function rows_in_fixed_order(records, column_order) that returns a list of lists — one list of values per record, always in the exact order given by column_order, regardless of the key insertion order inside each record's dict.
records is a list of dicts, all with the same keys; column_order is a list of key names.
rows_in_fixed_order([{"b": 2, "a": 1}], ["a", "b"]) → [[1, 2]]
Show Solution
def rows_in_fixed_order(records, column_order):
return [[record[col] for col in column_order] for record in records]
22 Missing Required Keys Easy
Write a function missing_required_keys(env, required_keys) that returns a sorted list of every key in required_keys that's not present in env — an empty list if nothing's missing. This is the "list everything missing at once" check a startup validator would run before deciding whether to raise.
env is a dict; required_keys is a list of strings.
missing_required_keys({"A": "1", "B": "2"}, ["A", "B"]) → []missing_required_keys({"A": "1"}, ["A", "B", "C"]) → ["B", "C"]
Show Solution
def missing_required_keys(env, required_keys):
return sorted(k for k in required_keys if k not in env)
23 Zero-Based Offset From a 1-Based Page Medium
Write a function utc_hour_matches(local_hour, utc_offset_hours, target_utc_hour) that returns True if a naive local_hour (0-23), combined with a UTC offset, lands on target_utc_hour once converted to UTC — modeling why a naive, timezone-less hour can mean a different real moment depending on where it's interpreted.
local_hour and target_utc_hour are 0-23; utc_offset_hours can be negative. UTC hour = (local_hour - utc_offset_hours) % 24.
utc_hour_matches(9, -5, 14) → True (9am at UTC-5 is 2pm UTC)utc_hour_matches(9, 0, 14) → False (9am UTC is 9 UTC, not 14)
Show Solution
def utc_hour_matches(local_hour, utc_offset_hours, target_utc_hour):
utc_hour = (local_hour - utc_offset_hours) % 24
return utc_hour == target_utc_hour
24 Config From Environment, Not Hardcoded Easy
Write a function resolve_db_url(env, default_url) that returns env["DATABASE_URL"] if it's set, or default_url otherwise — modeling why connection details should come from configuration, never be hardcoded into source code.
env is a dict; default_url is a string.
resolve_db_url({"DATABASE_URL": "prod-host"}, "localhost") → "prod-host"resolve_db_url({}, "localhost") → "localhost"
Show Solution
def resolve_db_url(env, default_url):
return env.get("DATABASE_URL", default_url)
25 Parameterize, Don't Format Medium
Write a function build_safe_query(username) that returns a list [query, params] for a parameterized SQL query looking up a user by username — query must contain a ? placeholder, never the raw username value formatted directly into the string (which would be vulnerable to SQL injection). params is a list containing just username.
username is a string (may contain SQL-special characters).
build_safe_query("ana") → ["SELECT * FROM users WHERE username = ?", ["ana"]]
Show Solution
def build_safe_query(username):
return ["SELECT * FROM users WHERE username = ?", [username]]
26 Join Without N+1 Medium
Write a function attach_authors(books, authors) that returns a new list of book dicts, each with an added "author_name" key looked up from authors (a list of {"id":..., "name":...} dicts) by book["author_id"] — using one dict built up front, never a per-book scan through authors (the N+1 pattern).
books is a list of dicts with "author_id"; authors is a list of dicts with "id" and "name".
attach_authors([{"title": "X", "author_id": 1}], [{"id": 1, "name": "Ana"}]) → [{"title": "X", "author_id": 1, "author_name": "Ana"}]
Show Solution
def attach_authors(books, authors):
names_by_id = {a["id"]: a["name"] for a in authors}
return [
{**book, "author_name": names_by_id.get(book["author_id"])}
for book in books
]
27 Retry With an Idempotency Key Medium
Write a function process_charge(processed, idempotency_key, amount) that simulates a safe retry: processed is a dict mapping idempotency keys already charged to their amount. If idempotency_key is already in processed, return its existing recorded amount unchanged (don't charge again). Otherwise, record amount under that key in processed and return it.
processed is a dict (mutated in place); idempotency_key is a string; amount is a number.
First call
process_charge({}, "req-1", 50) → 50, and processed now has {"req-1": 50}.A retried call
process_charge({"req-1": 50}, "req-1", 50) → 50 (not charged twice).
Show Solution
def process_charge(processed, idempotency_key, amount):
if idempotency_key in processed:
return processed[idempotency_key]
processed[idempotency_key] = amount
return amount
28 Validate the Response Field Easy
Write a function fahrenheit_or_none(weather_response) that reads weather_response["temperature_c"] and converts it to Fahrenheit, returning None instead of crashing if that field is missing or None.
weather_response is a dict that may or may not have a numeric "temperature_c".
fahrenheit_or_none({"temperature_c": 0}) → 32.0fahrenheit_or_none({"temperature_c": None}) → Nonefahrenheit_or_none({}) → None
Show Solution
def fahrenheit_or_none(weather_response):
temp_c = weather_response.get("temperature_c")
if temp_c is None:
return None
return temp_c * 9 / 5 + 32
29 Unknown Is Not "No" Medium
Write a function stock_status(quantity_or_none) that returns "in_stock" if quantity_or_none is a number greater than 0, "out_of_stock" if it's exactly 0, or "unknown" if it's None (standing in for "the inventory service was unreachable") — never conflating "unreachable" with "zero stock."
quantity_or_none is an int or None.
stock_status(5) → "in_stock"stock_status(0) → "out_of_stock"stock_status(None) → "unknown"
Show Solution
def stock_status(quantity_or_none):
if quantity_or_none is None:
return "unknown"
return "in_stock" if quantity_or_none > 0 else "out_of_stock"
30 Redact Before You Log Easy
Write a function redact_sensitive(record, sensitive_keys) that returns a new dict identical to record, except every key listed in sensitive_keys that's present has its value replaced with the string "***".
record is a dict; sensitive_keys is a list of key names (may include keys not present in record).
redact_sensitive({"user": "ana", "password": "hunter2"}, ["password"]) → {"user": "ana", "password": "***"}
Show Solution
def redact_sensitive(record, sensitive_keys):
result = dict(record)
for key in sensitive_keys:
if key in result:
result[key] = "***"
return result
31 Tag Every Log Line With a Correlation ID Medium
Write a function tag_log_lines(correlation_id, messages) that returns a list of strings, each formatted as f"[{correlation_id}] {message}" — so every line from one logical operation can be filtered together in a log aggregator.
correlation_id is a string; messages is a list of strings.
tag_log_lines("order-102", ["validating", "charged"]) → ["[order-102] validating", "[order-102] charged"]
Show Solution
def tag_log_lines(correlation_id, messages):
return [f"[{correlation_id}] {message}" for message in messages]
32 Structured Log Record Medium
Write a function filter_failed_orders_over(log_records, min_amount) that, given a list of structured log dicts each with "order_id", "amount", and "status" keys, returns the list of order_ids where "status" is "failed" and "amount" is greater than min_amount — the exact query that's easy against structured data and painful against free-text log lines.
log_records is a list of dicts; min_amount is a number.
filter_failed_orders_over([{"order_id": 1, "amount": 600, "status": "failed"}, {"order_id": 2, "amount": 100, "status": "failed"}], 500) → [1]
Show Solution
def filter_failed_orders_over(log_records, min_amount):
return [
r["order_id"] for r in log_records
if r["status"] == "failed" and r["amount"] > min_amount
]
33 Symptom Classifier Hard
Write a function classify(description, catalog) where catalog is a list of dicts each with "id" and "keywords" (a list of lowercase strings). Return a sorted list of every catalog entry's "id" whose keywords list has at least one keyword that's a substring of description, checked case-insensitively — each matching id should appear exactly once, even if multiple of its keywords match.
description is a string (any case); catalog is a list of dicts as described.
classify("Getting a KEYERROR in prod", [{"id": 1, "keywords": ["keyerror"]}, {"id": 2, "keywords": ["timeout"]}]) → [1]
Show Solution
def classify(description, catalog):
lowered = description.lower()
matched_ids = [
entry["id"] for entry in catalog
if any(keyword in lowered for keyword in entry["keywords"])
]
return sorted(matched_ids)