cswork / libraryOpen practice workspace

Interview guides · Amneal Pharmaceuticals

Amneal Pharmaceuticals Software Engineer Interview Questions & Guide 2026

Caching practice for Amneal Pharmaceuticals software engineer prep: settle the staleness budget before choosing an invalidation strategy.

The 60-second brief

A Software Engineer at Amneal Pharmaceuticals plays a vital role in bridging the gap between cutting-edge pharmaceutical manufacturing and digital infrastructure. You are responsible for developing, maintaining, and optimizing the software systems that support the company’s mission to provide accessible, high-quality medicines to patients worldwide. Your work ensures that complex data, regulatory compliance, and operational workflows are managed with precision and reliability.

If the loop includes an asynchronous take-home, treat it as a code review of you rather than as a puzzle: structure, what you chose to test, and what you wrote down about the constraint you were working under. Hold the stated time box and say what you would have done with more of it.

Focus areas

  • Make HL7 and X12 ingestion idempotent under replay
  • Authorise every identified read against current consent
  • Hold accumulator limits under concurrent claim adjudication

Overview

This role is particularly critical because your software contributions directly impact the efficiency of internal business processes and the technical systems that underpin a global pharmaceutical leader. You will operate in an environment that values technical agility and the ability to solve practical, real-world problems. Whether you are automating internal tasks or integrating new digital solutions into existing workflows, your success is measured by your ability to deliver stable, scalable, and user-focused engineering outcomes.

Prepare to demonstrate how your technical proficiency translates into tangible operational improvements. At Amneal Pharmaceuticals, the focus is often on practical application over purely theoretical knowledge.

The Amneal Pharmaceuticals interview process

Amneal Pharmaceuticals candidates report 2 rounds · ≈ 2-4 weeks. The stages below are what candidates describe, not a published process.

Initial Screening

Half of this call is the part candidates treat as small talk: start date, notice period, work authorisation and its timing, location and time zone, on-call, and the number. Those are what kill offers late, after several engineers have each spent a day. Surfacing a hard constraint now costs you nothing and occasionally buys you something, since a loop compressed to fit a competing deadline can usually only be arranged if it is asked for early. The common failure is deflecting the compensation question twice, then discovering at offer stage that the band never reached your number.

What to demonstrate

  • Whether your hard constraints are compatible with the role before a loop gets booked: earliest start, notice period, what authorisation you hold and when it needs action, days on site, willingness to carry a pager
  • Whether you give a compensation range with something behind it, such as current total compensation or a competing timeline, rather than leaving the band untested
  • Whether your stated timeline is real, since a competing deadline raised now is something scheduling can sometimes work around and the same deadline raised at offer stage usually is not

How to prepare

  • Write each constraint down in one line before the call and state them as facts rather than negotiating them live under a question you were not expecting
  • Set your range from two or three current data points for that level and location, and name the structure you are quoting in, so the number is comparable to the one they are holding
  • If another process is running, say where it stands and by when, and ask directly whether this loop can be scheduled inside that window

Technical Interviews

Input bounds are the part of the prompt most often skimmed, and they usually contain the answer. They tell you which complexity class is admissible, which narrows the search before you have thought about the problem itself. As a rough planning figure, a compiled language does on the order of 10^8 simple operations per second and an interpreted one roughly an order of magnitude less. So n up to about twenty admits enumerating subsets, a few thousand admits a quadratic pass, and a million admits neither: you need near-linear, or linear with a log factor. If the bounds are missing, ask for them.

What to demonstrate

  • Whether the approach is justified by the stated input size rather than by whichever pattern you recognised first
  • Whether you ask about the properties that change the algorithm: whether the input arrives sorted, whether duplicates occur, whether values are bounded integers, whether it all fits in memory
  • Whether you can name the bottleneck in your own solution and what would remove it, even when you deliberately leave it in place
  • Whether a claimed speedup is real, since memoising a recursion only helps when subproblems genuinely overlap and the state can be keyed cheaply

How to prepare

  • For each algorithm you rely on, write down the largest n it handles in roughly a second, then check two of those figures by timing them in the language you will actually type in
  • For two weeks, write one line naming your target complexity and the bound that justifies it before you write any code, then compare that line with what you ended up submitting
  • Practise the conversion backwards: given a required O(n log n), list the mechanisms that get you there (sorting, a heap, an ordered map, divide and conquer) and choose by what the problem needs to query, not by what you used last

Where candidates lose points

Storing monetary amounts as floating-point numbers.

Binary floating point cannot represent values like 0.10 exactly, so summing allowed and paid amounts across millions of claim lines accumulates representation and rounding error. Reconciliation against a remittance file is exact to the cent, so the drift surfaces as a balance that is off by a few cents with no identifiable cause, and engineers lose days looking for a logic bug in code that is correct apart from its numeric type. Integer minor units or an exact decimal type removes the class entirely.

Upserting on the order or result identifier, so a correction overwrites the original row.

It makes the question 'what did the clinician see at 14:02' unanswerable, which is exactly what an incident review or a legal hold asks. It also leaves downstream consumers that already acted on the preliminary value with no correction event to react to, because the state transition was collapsed into a single mutated row and never emitted.

Writing code before the input contract is pinned down

Before the first line, state the types, the size bounds, whether duplicates, negatives or an empty input are possible, whether the input is sorted, whether you may mutate it, and what the function returns when nothing matches. Every one of those answers changes the code, and discovering one at minute twenty costs a rewrite you no longer have time for.

Assuming fixed-width integer arithmetic cannot overflow

In languages with fixed-width integers, including C, C++, Java, Go and Rust, computing a midpoint as (lo + hi) / 2 overflows once the sum passes the type's maximum, so write lo + (hi - lo) / 2 instead. Say which language you are in: arbitrary-precision integers, as in Python or Ruby, remove this specific hazard and none of the others.

Questions & practice

Extract an idempotency key from a raw HL7v2 message

Easy · parsing · idempotency · delimiters

An HL7v2 message arrives as a byte buffer up to 256 KB, segments terminated by carriage return (0x0D), first segment MSH. MSH-1 is the field separator character itself and MSH-2 holds the encoding characters, so splitting the MSH segment on the separator puts MSH-n at index n-1 for n of 2 or more. Return the idempotency key built from MSH-4 sending facility, MSH-3 sending application, MSH-10 message control ID and MSH-7 event timestamp, with escape sequences decoded in each value. Single pass, O(n). Do not hardcode the separator characters.

Approach

  1. Read the delimiters out of the message instead of assuming them: the byte immediately after MSH is the field separator, and the next field's bytes give component, repetition, escape and subcomponent separators in that order. Everything downstream uses those values, because a partner is entitled to send different ones and the common defaults are a convention, not a guarantee.
  2. Verify the first three bytes are MSH before anything else and reject otherwise, since a socket read can begin mid-message. Then bound the segment at the first terminator and split that slice only, applying the n-1 offset that the MSH segment alone requires.
  3. Decode escapes in one left-to-right pass per extracted value: on the escape character, read to the next escape character and map the codes for field, component, subcomponent, repetition and escape back to their literal characters. Treat an unterminated escape as a malformed message rather than dropping the tail silently.
  4. Normalise MSH-7 to UTC before it enters the key. The timestamp may carry an offset or omit one, and two spellings of the same instant must hash identically or the ledger stops deduplicating the moment a partner changes its formatter.
  5. Compose the key as the full tuple, not the control ID alone. The control ID is unique only per sending application and some senders roll the counter over, so facility plus application plus control ID plus instant is the smallest key that survives a rollover.
  6. Cost is O(n) time and O(k) space for the extracted values. Hashing the whole body is also O(n) but cannot distinguish a genuine resend from a corrected retransmission that reuses the control ID, which is a different event.

Follow-up

  • One partner sends MSH-7 with no timezone offset and another sends it with an offset. What do you store, and what do you compare on?
  • A sender rolls its control ID counter over and restarts from zero. Which component of your key absorbs that, and which message pairs would still collide?
  • Segments arrive separated by line feed instead of carriage return, or with a trailing empty field. Which should the parser accept and which should it negatively acknowledge?

Flag a requester reading too many distinct charts per window

Medium · sliding window · two pointers · distinct count

You consume access-audit records (event_ts, requester_id, enterprise_person_id, purpose_of_use, break_glass) at tens of thousands per second, non-decreasing in event_ts. For each requester, emit an alert the first time any sliding 600-second window contains reads of more than D distinct enterprise_person_ids. Break-glass reads count toward the window and are also reported separately. Return (requester_id, window_start_ts, distinct_count). Target O(1) amortised per event and memory proportional to the events resident in the window, not to the day.

Approach

  1. Per requester, hold a deque of (event_ts, person_id) and a hash map from person_id to its occurrence count inside the window, plus a running distinct counter. Push on the right; while the front is older than event_ts minus 600 seconds, pop it, decrement its count and erase the key when the count reaches zero, decrementing the distinct counter. Each event is pushed once and popped once, so the amortised cost is O(1) and the memory is O(W) for window occupancy W.
  2. Test the threshold immediately after each push and nowhere else. Between two consecutive events the window can only lose members as its left edge advances, so the maximum distinct count over all window positions is attained at a position whose right edge is an event. Checking at pushes is therefore exhaustive rather than a sampling approximation.
  3. Latch the alert per requester and re-arm only when the distinct count falls back below D, otherwise one busy stretch emits thousands of near-identical rows and the real signal is buried by its own volume.
  4. Bound memory both per requester and globally. A requester whose window legitimately holds tens of thousands of reads must not hold the process hostage, so cap the deque and degrade above the cap to an approximate distinct counter such as HyperLogLog, stating the error you accept in exchange.
  5. Count break-glass toward the window but carry it in its own output field. Break-glass has to succeed during an emergency, which is exactly why it must be the most visible path in the audit, and excluding it from the count would make the abuse route the quiet one.
  6. State the precondition: this is correct only while input is non-decreasing in event_ts. Out-of-order arrival needs a bounded-lateness buffer and a watermark, and dropping late events without a counter is the failure that hides itself.

Follow-up

  • One region's events arrive up to 90 seconds late. What buffer do you add, and what does that do to alert latency?
  • One person uses two requester accounts. What has to change in the key, and what new false positive does that introduce?
  • How do you restore window state after a process restart without replaying the whole day?

Sum surviving claim versions in one pass over unordered lines

Easy · hash map · versioning · streaming aggregation

You are streamed up to 50 million claim_line records in arbitrary order: claim_id, claim_version, line_number, frequency_code (original, replacement, void), enterprise_person_id, allowed_amount_cents. Every version of a claim shares its claim_id, and a replacement arrives as a higher claim_version. Return total allowed_amount_cents per enterprise_person_id, counting each claim once at its highest version and contributing zero when that version is a void. Amounts are non-negative int64 minor units. Target O(N) time and O(C) space for C distinct claims, single pass, no sort.

Approach

  1. Say the two grains out loud before writing anything: the version lives at claim grain, the money lives at line grain. Every wrong answer here comes from applying a claim-level rule with a line-level filter.
  2. Keep one hash map from claim_id to a small record (best_version, sum_cents, person_id, is_void). Per line: if claim_version is greater than best_version, reset sum_cents to this line's amount and overwrite the person and void flag; if equal, add to it; if lower, discard the line. That reset is what makes the pass order-independent, so a replacement arriving before its original still wins.
  3. Resolve the void at the end, not at ingest. A void only nullifies the claim if it is the surviving version, and zeroing on sight would let an earlier replacement that arrives later resurrect the money.
  4. Fold the C claim records into a person-keyed map in a second phase, O(C). Do not accumulate into the person total during the stream: you cannot subtract a superseded version you have already forgotten.
  5. Cost is O(N) time, O(C) space. The sort-based alternative, group by (claim_id, claim_version) and keep the max, is O(N log N) and needs the set resident; prefer it only when C approaches N and the map will not fit.
  6. Keep cents in int64 throughout. Fifty million lines at a realistic per-line ceiling stay four orders of magnitude below 2^63, so the integer type costs nothing and removes the float drift class entirely.

Worked solution (20 min)

  1. Define the per-claim record and the three-way comparison on claim_version: greater resets, equal accumulates, lower discards.
  2. Run the stream once, touching only the claim map.
  3. Walk the claim map, skipping entries whose surviving version is a void, and add each remaining sum into a person map.
  4. Return the person map sorted descending by total.

Expected result: Claim A: version 1 has lines of 12000 and 8000 cents, version 2 (replacement) has lines of 9000, 8000 and 500. Claim B: version 1 has a single line of 5000, version 2 is a void carrying one zero-amount line. Both claims belong to one person. Your answer is 17500 cents, from claim A's version 2 only. The naive sum over all seven lines is 42500.

Verify it yourself

  • The number of claims contributing equals the number of distinct claim_ids whose highest version is not a void.
  • For a multi-line claim, the addends in its sum equal that surviving version's line count, not one.
  • Shuffling the input and re-running produces an identical result, which is the property the reset-on-higher-version rule buys you.
  • The all-rows sum is greater than or equal to your total, equal only when no claim has a version above 1 and none is a void.

Follow-up

  • You shard the stream across eight workers. Sharding by hash of claim_id works; what exactly breaks if you shard by enterprise_person_id instead?
  • A replacement arrives for a claim_id whose original never appears in the batch. What does your map produce, and is that the financially correct answer or a reconciliation break?
  • The same claim_id is reused by two different submitting organisations. How does the key have to change, and when would you have noticed?

Diagnose why an eligibility lookup ignores its index

Medium · indexing · query planning · partial indexes

A 40-million-row coverage_span serves eligibility lookups with: SELECT coverage_id, plan_id, coverage_order FROM coverage_span WHERE enterprise_person_id = $1 AND valid_to = 'infinity' AND effective_date <= $2 AND (termination_date IS NULL OR termination_date >= $2). An index exists on (effective_date). EXPLAIN (ANALYZE, BUFFERS) shows a sequential scan reading 1.8 million buffers at 2.4 seconds. Explain why that index cannot help, propose the index plus any schema change that makes the predicate index-friendly, and state what you expect the new plan and buffer count to be.

Approach

  1. Read the predicate for selectivity before touching the index. effective_date <= $2 matches most of a 40-million-row history, so a leading range scan on that column returns a large fraction of the table and the planner correctly prefers a sequential scan over millions of random heap fetches. The index is not being ignored; it is being rejected on cost.
  2. Put the equality column first. enterprise_person_id = $1 selects a handful of rows out of 40 million, so it must lead the composite index; a b-tree can only use columns after the first range predicate as filters, not as search bounds.
  3. Turn the open-ended termination into something indexable. The OR ... IS NULL branch forces either a BitmapOr or a post-index filter. Add coverage_end date GENERATED ALWAYS AS (COALESCE(termination_date, DATE '9999-12-31')) STORED and rewrite the predicate to coverage_end >= $2; both COALESCE over a column and a date literal are immutable, so the generated column is legal.
  4. Make the index partial on WHERE valid_to = 'infinity'. Most rows in a bitemporal table are superseded beliefs, so the partial index is a fraction of the full one, stays in cache, and encodes the predicate for free rather than re-checking it per row.
  5. Consider the range alternative honestly: a daterange(effective_date, termination_date + 1, '[)') column with a GiST index and the && operator handles overlap queries and supports an EXCLUDE constraint against overlapping active coverage, but GiST lookups are slower than b-tree for this point-in-time pattern. Pick b-tree for the read path and keep GiST only if you also need the overlap constraint.
  6. Verify rather than assert: re-run EXPLAIN (ANALYZE, BUFFERS) and read Rows Removed by Filter and the shared hit/read split, not just the total time.

Follow-up

  • After the change the plan is still a sequential scan for one particular member. What single query tells you whether that is stale statistics, a genuinely huge row count for that person, or parameter-dependent plan caching?
  • Your generated column needs backfilling on a live table. Does adding a STORED generated column rewrite it, and what does that mean for your maintenance window?
  • How would you serve the same lookup when the answer must be as of a past system-time instant rather than the current belief, given your index is partial on valid_to = 'infinity'?

Fix a paid-amount report that double counts claim versions

Medium · join fan-out · versioned claims · aggregation correctness

claim_line: claim_line_id, claim_id, claim_version smallint, line_number, frequency_code in ('original','replacement','void'), enterprise_person_id, coverage_id, billing_provider_npi, service_from_date, procedure_code, units, billed_amount_cents bigint, allowed_amount_cents, paid_amount_cents, adjudication_status, UNIQUE (claim_id, claim_version, line_number). A monthly report sums paid_amount_cents and joins coverage_span on enterprise_person_id with date overlap to attribute a plan. It overstates payment by roughly 9%, and reconciliation against remittance fails. Name both causes, then write the corrected query returning paid cents and plan per billing_provider_npi for March 2026 service dates.

Approach

  1. Cause one: the SUM spans every claim version. A replacement supersedes a prior claim and a void cancels one, so a replaced claim contributes twice and a voided claim contributes once when it should contribute nothing. Resolve the surviving version per claim_id before aggregating, never by deleting superseded rows.
  2. Cause two: the coverage join is one-to-many. coverage_span carries a system-time version per coverage period, so a person with three beliefs about one period multiplies every claim line by three. The join is for a label, not for filtering, so it must not be allowed to change cardinality.
  3. Collapse the version chain with DISTINCT ON (claim_id) ... ORDER BY claim_id, claim_version DESC, then join the lines back on (claim_id, claim_version), and exclude the surviving version when its frequency_code is 'void'.
  4. Make the coverage lookup cardinality-safe with a LEFT JOIN LATERAL ... LIMIT 1 pinned to valid_to = 'infinity' and ordered by valid_from DESC. LATERAL with LIMIT 1 cannot fan out by construction; a plain join can, and no amount of later DISTINCT repairs a SUM that already doubled.
  5. Keep the money in integer minor units the whole way. SUM(bigint) returns numeric in PostgreSQL, so there is no overflow and no binary floating-point error; cast to a display type only at the edge.

Worked solution (35 min)

  1. Prove cause one with a diagnostic: SELECT claim_id, count(DISTINCT claim_version) FROM claim_line GROUP BY 1 HAVING count(DISTINCT claim_version) > 1 — confirm the affected claims exist and their paid totals.
  2. Prove cause two by running the original report with count(*) alongside the SUM and comparing it to the count of qualifying claim_line rows; any excess is fan-out.
  3. Write the surviving-version CTE with DISTINCT ON (claim_id).
  4. Join the lines to it on both claim_id and claim_version, exclude 'void', filter adjudication_status = 'paid' and the half-open March service-date range.
  5. Attach the plan label through LEFT JOIN LATERAL with LIMIT 1, then re-run the count(*) check and confirm it now equals the qualifying line count exactly.
  6. Diff the new total against remittance and confirm the 9% gap closes to zero cents, not to 'close enough'.

Expected result: WITH surviving AS ( SELECT DISTINCT ON (claim_id) claim_id, claim_version, frequency_code FROM claim_line ORDER BY claim_id, claim_version DESC ) SELECT cl.billing_provider_npi, cov.plan_id, SUM(cl.paid_amount_cents) AS paid_cents FROM claim_line cl JOIN surviving s ON s.claim_id = cl.claim_id AND s.claim_version = cl.claim_version LEFT JOIN LATERAL ( SELECT cs.plan_id FROM coverage_span cs WHERE cs.enterprise_person_id = cl.enterprise_person_id AND cs.valid_to = 'infinity' AND cs.effective_date <= cl.service_from_date AND (cs.termination_date IS NULL OR cs.termination_date >= cl.service_from_date) ORDER BY cs.coverage_order, cs.valid_from DESC LIMIT 1 ) cov ON true WHERE s.frequency_code <> 'void' AND cl.adjudication_status = 'paid' AND cl.service_from_date >= DATE '2026-03-01' AND cl.service_from_date < DATE '2026-04-01' GROUP BY 1, 2;

Verify it yourself

  • Replacing the aggregate with count(*) yields exactly the number of claim_line rows that pass the same predicates without the coverage join — equality proves the LATERAL did not fan out.
  • Removing the LATERAL entirely changes no monetary total, only the plan column; if the total moves, the join is still multiplying.
  • Every claim_id appears with exactly one claim_version in the surviving CTE: count(*) equals count(DISTINCT claim_id).
  • The corrected total reconciles to the remittance file to the cent, and the residual for each voided claim is exactly its previously included paid amount.

Follow-up

  • A replacement arrives before its original. Your surviving-version logic picks max(claim_version) — what does the report show in the window before the original lands, and does the number self-correct?
  • Add a claim_line_adjustment table with several reason codes per line. What does that do to this query, and where do you aggregate to keep it safe?
  • Reconciliation is still off by 400 cents. Which of the two causes could still produce that, and what is your next query?

Can you define specific acronyms related to our EHS (Environmental Health and Safety) protocols?

Medium

Approach

  1. Clarify what is being asked and what a complete answer contains.
  2. Say what you would check first and why it is the highest-information step.
  3. Work from the requirement backwards to the design.

Follow-up

  • How would you know your answer was wrong?
  • What assumption would you test first?

How do you approach learning new technical systems or domain-specific terminology?

Medium

Approach

  1. Work from the requirement backwards to the design.
  2. State your assumptions explicitly before working the problem.
  3. Clarify what is being asked and what a complete answer contains.

Follow-up

  • What assumption would you test first?
  • How would you know your answer was wrong?

Eligibility reads with an as-of date and a payer timeout

Easy · caching · invalidation · degraded-mode · timeout-budget

The eligibility service answers whether a person is covered for a service date and what they will owe. Peak is roughly 4,000 requests per second between 07:00 and 10:00 across several time zones. Locally held coverage_span rows (enterprise_person_id, payer_id, plan_id, effective_date, termination_date, status, valid_from, valid_to) answer most calls, but a real-time inquiry to the external payer takes one to eight seconds and fails outright a few times an hour. Specify the cache key, the time-to-live, the timeout budget, and exactly what registration receives when the payer is unreachable.

Approach

  1. Key the answer on (enterprise_person_id, payer_id, plan_id, service_date) and carry the as_of instant inside the value. Coverage terminates retroactively, so the same tuple can be covered and not covered for the same service date, differing only in when the answer was computed; a key without service_date lets today's answer serve tomorrow's question.
  2. Set the time-to-live from the exposure you are willing to own rather than from the hit rate. Enrolment files land daily to weekly, so a retroactive termination becomes knowable within a day; a 15-minute entry bounds the window in which you keep serving an answer you have already been told is wrong, and costs roughly one origin call per member per morning. Pair it with an explicit invalidation driven by the enrolment loader publishing changed person identifiers.
  3. Budget the external round trip as a chain that fits inside the caller's deadline: compute the local answer first, then a 2-second cap on the payer inquiry inside a 2.5-second caller deadline. The external call is an upgrade to the local answer, not the origin of it.
  4. Decide the degraded behaviour explicitly and label it in the response: return the locally derived answer with its source and as_of set, never a fabricated 'covered'. Registration proceeds with an unverified flag and the encounter is queued for re-verification. Blocking registration on a partner's outage converts someone else's incident into a care-delivery incident.
  5. Name the trade-off rather than implying there is none: you are choosing availability and accepting bounded staleness, and the cost lands weeks later as retroactive denials. Quantify it as unverified encounters per outage minute so it is a decision someone signed rather than a default nobody chose.

Worked solution (20 min)

  1. Write the cache key, the value struct including as_of and source, and the time-to-live, then state in minutes the maximum staleness that combination permits.
  2. Draw the timeline for a file received on the fifth terminating coverage effective the first, and mark every interval in which a stale covered answer can still be served.
  3. Write the timeout budget as explicit numbers that sum to less than the caller's deadline.
  4. Specify the degraded response shape and name the downstream consumer that acts on the unverified flag.

Expected result: A cache key of (enterprise_person_id, payer_id, plan_id, service_date) whose value carries an as_of instant and a source, a time-to-live justified as an exposure bound plus an enrolment-driven invalidation, a payer timeout that fits inside the caller deadline, and a degraded answer that is labelled unverified and queued for re-verification instead of blocking registration.

Verify it yourself

  • Two requests for the same person and plan but different service dates resolve to different cache entries.
  • Terminating a coverage effective 20 days in the past changes the served answer for a service date inside that window within one time-to-live.
  • With the payer endpoint black-holed, the p99 of the eligibility call stays under the caller deadline and no request returns a hard error.
  • Every cached answer can state the instant it was computed as of.

Follow-up

  • The payer responds 'active' while your local coverage_span says terminated effective three days ago. Which answer wins, and what do you store?
  • A cache flush at 07:15 sends every registration desk to the origin for the same plan at once. How do you hold it to one origin call per key?

Patient summary p99 blows up after version resolution ships

Easy · n+1 query · latency regression · versioned reads

The longitudinal record service serves a patient summary that fans out across eight to twelve resource types. After a release, the composite read's p99 went from 180ms to 2.1s while p50 moved from 40ms to 55ms. Database CPU is flat, no statement appears in the slow-query log, and the regression is worst for patients with long histories. The release added a latest-version resolution step so superseded observation_result rows stop appearing. Find the cause and give the fix, including the index it needs.

Approach

  1. Read the p50/p99/p99.9 split before anything else. p50 nearly flat with p99 up twelve-fold means the added work scales with a per-patient quantity — the number of resource versions on the chart — rather than a uniform slowdown. CPU saturation, lock waits and replica lag all move p50 too, so they are already excluded.
  2. Count database round trips per request, not query time. The signature in pg_stat_statements is one statement whose calls grew by orders of magnitude while its mean_exec_time stayed under a millisecond: a cheap query executed once per row. That is exactly why nothing crossed the slow-query threshold.
  3. Read the resolution code. It loops over the fetched rows and issues one query per row to test whether a newer version supersedes it, so the cost is 1 + R round trips for R versions. At 3ms of round trip each, a 600-version chart costs about 1.8s of pure latency with negligible database work.
  4. Replace it with one set-wise query per resource type: SELECT DISTINCT ON (accession_id, loinc_code) ... WHERE enterprise_person_id = $1 ORDER BY accession_id, loinc_code, version DESC, backed by an index on (enterprise_person_id, accession_id, loinc_code, version DESC). Round trips fall from 1 + R to the number of resource types, at most twelve, and the fan-out can run those concurrently.
  5. Name the trade-off against the alternatives. An anti-join on NOT EXISTS (SELECT 1 FROM observation_result o2 WHERE o2.supersedes_observation_id = o.observation_id) is correct against this schema but plans as a second pass over the person's rows. A maintained superseded marker on the predecessor row indexes best but adds a write to a table whose whole guarantee is that rows are never rewritten; DISTINCT ON keeps the append-only property.

Follow-up

  • A correction commits while the summary is being assembled across eight separate queries. Which version does the caller get, and how do you make the composite read consistent — a repeatable-read snapshot, or an as-of timestamp threaded through every query?
  • Would you cache the resolved latest-version set per patient? Corrections are ordinary traffic, so state the invalidation trigger and the worst-case staleness before answering yes.

Suggested practice checklist

For someone who has spent the last few years shipping features and reading other people's code, and who has not solved a timed problem from a blank file in a long time. Five days rebuild the primitives and the patterns that sit on them, working from invariants rather than remembered solutions, and the last two attach that back to the rest of the loop.

Day 1 — Rebuild the primitives by implementing them

  • Implement a dynamic array with doubling growth and an operation counter, then change the growth rule to add a fixed sixteen slots instead, and time both for n of ten thousand, a hundred thousand and a million. The fixed-increment version resizes n/16 times at O(n) each, so its total work is quadratic; doubling is what makes append amortised constant.
  • Implement a hash map with separate chaining and a load-factor resize, then insert ten thousand keys engineered to land in one bucket and record what happens to lookup time, so that average-case O(1) becomes a claim with a stated precondition rather than a reflex.
  • For dynamic-array append and hash-map insert, write down which cost is amortised rather than worst-case, which single operation pays the whole bill, and what a system with a hard per-operation deadline would have to do instead.

Deliverable: Two working implementations plus a timing table showing the input at which each structure's advertised complexity stops holding.

Day 2 — Arrays under an invariant: two pointers, sliding window, binary search

  • Solve longest-subarray-with-sum-at-most-K using a sliding window, then run it on an input containing negative numbers and watch it return the wrong answer: extending the window only moves the sum monotonically when every element is non-negative, and that precondition is the whole reason the technique works.
  • Write the binary search that finds the first index satisfying a predicate rather than an exact value, put the loop invariant above the loop in a comment, and verify termination on the two inputs that break careless versions: the empty range, and a range where every element satisfies the predicate.
  • Compute the midpoint as lo + (hi - lo) / 2 and write one line on why the obvious (lo + hi) / 2 is a genuine defect in a fixed-width integer type and a non-issue in a language with arbitrary-precision integers.

Deliverable: Three solved problems, each with its invariant written above the loop, plus one recorded input on which the sliding window is provably wrong.

Day 3 — Sorting, heaps, and the greedy argument that has to be proved

  • Solve one top-k problem three ways, by full sort, by a size-k heap, and by quickselect, then write the values of n and k at which each becomes the right choice, along with quickselect's quadratic worst case and why a randomised pivot makes that unlikely rather than impossible.
  • Implement bottom-up heapify and count sift-down steps to confirm it does linear work rather than n log n, because most nodes sit near the bottom of the tree and therefore move only a short distance.
  • Take interval scheduling by earliest finishing time and write the exchange argument out in full: given any optimal schedule, swapping in the earliest-finishing interval keeps it feasible and no smaller. Then construct the weighted variant where that same greedy fails and name what has to replace it.

Deliverable: A three-way top-k comparison with measured crossover points, one written exchange argument, and one counterexample to a greedy rule that looks almost identical.

Day 4 — Recursion, memoisation, and the step to a table

  • Take one problem with overlapping subproblems, such as edit distance or coin change, instrument the plain recursion with a call counter to show the blow-up, then add memoisation and re-count.
  • Convert the memoised version to a bottom-up table and state the two properties you relied on: each subproblem's result depends only on its arguments, and the dependencies form a DAG you can enumerate in order.
  • Rewrite one deep recursion with an explicit stack, then find the input length at which the original hits the interpreter's frame limit, which defaults to about a thousand frames in CPython, so you know when the rewrite is required rather than decorative.

Deliverable: One problem in three forms, naive, memoised and tabulated, with call counts for each and the input length at which recursion depth becomes the binding constraint.

Day 5 — Graphs, where most of the work is choosing the traversal

  • Implement BFS and DFS over one adjacency list, then answer for each which finds a shortest path in an unweighted graph and which you would use to detect a cycle in a directed graph, including why the in-progress versus finished distinction matters for the second.
  • Implement topological sort by in-degree, feed it a graph containing a cycle, and confirm the failure signature is that fewer than V nodes come out rather than an exception, then note that the order it produces is one of several valid ones.
  • Run a shortest-path search on a graph with a single negative edge weight and show the wrong answer, then write the precondition Dijkstra actually needs, non-negative weights, because it finalises a node's distance the first time that node is popped, and name the algorithm you would switch to and its own limit.

Deliverable: A small graph library with BFS, DFS and topological sort, plus two inputs that produce documented wrong answers under the wrong algorithm choice.

Day 6 — One day for everything that is not an algorithm

  • Sketch one system only to the depth a coding-heavy loop tends to reach: the endpoints, what the service stores, and the single query pattern that decides the schema. Stop at twenty-five minutes.
  • Prepare the project answer for an interviewer who codes, which means rehearsing the two levels they push to: the specific thing you built, and why you chose that approach over the alternative they will name. Open with a number and be ready to say what it excludes.
  • Prepare the answer to what you would do differently, choosing a real technical mistake with a specific fix rather than a complaint about process or staffing.

Deliverable: One design sketch at endpoint-and-schema depth, plus a project answer rehearsed to two levels of follow-up.

Day 7 — Solve out loud, under time

  • Do three timed problems at twenty-five minutes each in a plain editor with no autocomplete and no execution until the end, then tally separately the failures that were syntax and the ones that were approach, because those two numbers call for different fixes.
  • Narrate one solution from the first sentence, stating the approach and its complexity before writing any code, and rehearse the sentence you will use when you realise mid-solution that the approach is wrong.
  • Re-solve from blank the two problems you were slowest on this week and compare the times against the day they first appeared.

Deliverable: A recording of one fully narrated solution and a tally that separates syntax failures from approach failures.

Outage answers are graded on instruments

Nobody is scoring your stamina at three in the morning. What carries weight is which signal told you something was wrong, what you measured before touching anything, what you rolled back versus what you fixed forward, and why you picked one. 'We restarted it and it went away' is a story about not knowing.

Why didn't you work full-time engineering positions while in undergrad?

Medium · behavioural and engineering judgement

Approach

  1. Name the disagreement and how you resolved it with evidence.
  2. Give the blast radius: what could have broken, and what you measured.
  3. State the situation in two sentences and spend the rest on the reasoning.

Follow-up

  • How did you know your change caused the improvement?
  • What would you do differently if you ran that again?

Tell me about your working capabilities.

Medium · behavioural and engineering judgement

Approach

  1. Give the blast radius: what could have broken, and what you measured.
  2. Close with what you would do differently, concretely.
  3. State the situation in two sentences and spend the rest on the reasoning.

Follow-up

  • What would you do differently if you ran that again?
  • What did you decide not to do, and why?

How would you deal with group partners who are behind on work?

Medium · behavioural and engineering judgement

Approach

  1. Pick a story where you made the decision, not one where you watched it.
  2. Name the disagreement and how you resolved it with evidence.
  3. Close with what you would do differently, concretely.

Follow-up

  • How did you know your change caused the improvement?
  • What would you do differently if you ran that again?

Tell me a little about yourself.

Medium · behavioural and engineering judgement

Approach

  1. Close with what you would do differently, concretely.
  2. Name the disagreement and how you resolved it with evidence.
  3. Pick a story where you made the decision, not one where you watched it.

Follow-up

  • How did you know your change caused the improvement?
  • What did you decide not to do, and why?