# Amazon SDE I / AUTA APJ — Answer Bible (Adarsh Vishwakarma) Answers for live-round questions other SDE I / UTA / AUTA candidates reported, plus resume/GitHub STAR and project talk-tracks. Your loop may differ. Unnamed stays unnamed. Job **10454435** still has **no** public IE that names a live-round question — this file is not a prediction of what 18 Aug will ask. Question index (evidence only): [`Question-Research-BIBLE.md`](Question-Research-BIBLE.md). --- ## 0. Intro + how to use in a 60-min Live Code **Lock:** Adarsh Vishwakarma · SDE I AUTA APJ · Job 10454435 · ADCI Karnataka · Java · Zoom + Amazon Live Code. R1 happened **13 Aug 2026**. R2 is **18 Aug 2026**, 60 min, same Zoom ID. Ignore Round 2 = 14 Aug in older research files. **60-min split (typical two-live UTA/AUTA):** LP 10–15 min → DSA 40–45 min (clarify, brute, optimal, dry run, complexity). Some loops swap that, or replace the second DSA with LLD (logger, dog check-in, locker, unnamed SD). Rate Limiter as a full second-technical is **OA+3 system design, not UTA-default two-DSA** (independent SDE I count = 1). **Java Live Code:** talk while writing. If the editor does not compile/run (Class C process unless the IE said otherwise), dry-run on the example they gave. Name TC/SC out loud. If stuck: write brute, state the optimal DS, then implement the hot loop. **OA is not a round.** Do not study OA problems as “R2”. If an IE numbered OA as Round 1, their “Round 3” / Tech 2 is the analogue of **your** 18 Aug slot. **18 Aug priority:** Rank A consecutive-day named UTA/AUTA second-lives first, then Rank B same-day AUTA. Calendar-close but not UTA: Deepak Jul 2026 (LL→BST + First Missing Positive). Full rank tables live in the research bible §4. **Contents:** §1 18 Aug priority pack · §2 remaining named FTE DSA · §3 OOD/LLD · §4 all 16 LPs + exact §5.D prompts · §5 resume project matrix · §6 GenAI · §7 CS actually asked · §8 INTERN · §9 NOT MY FORMAT · §10 mentor Login Tracker (unverified) · §11 LP × project cheat-sheet. **Scan sheet (clue → DS → Java templates):** [`Cheat-Sheet.md`](Cheat-Sheet.md). **Study book (HTML):** [`interview_bible/index.html`](interview_bible/index.html). **Do not lead with:** Login Tracker (unverified, mentor only — §10), CampusToCareer “APIs/caching” (invented), phishing/InstaRecon internals (ethics one-liner then move to Ylogx/IQVIA/Argus). ## 1. 18 Aug priority pack Notes for Adarsh. These are worked answers to **second-live** questions other SDE I / UTA / AUTA candidates reported. Job **10454435** still has **no** public IE that names a live-round question — this pack is not a prediction that 18 Aug will ask any of these. Unnamed stays unnamed. OA is not a round (B4 is live DSA after an OA-as-R1 remap). Java is canonical. Shared helpers: ```java class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } class TreeNode { int val; TreeNode left, right; TreeNode(int val) { this.val = val; } } ``` --- ### similar to Sum of Subarray Minimums — our R2 — AUTA — https://www.linkedin.com/posts/akash-singh-6778a6265_softwareengineer-amazon-interviewexperience-activity-7448027373821927424-9zuD **What they actually asked** Akash (AUTA portal, R2 27 Feb 2026): a problem **similar to** Sum of Subarray Minimums, plus an optimization ask and a short project. Candidate said **similar**, not an exact titled LC problem — do not treat this as a stamped LC id. **Clarify out loud** 1. Given `arr[0..n-1]`, is the answer `sum over every contiguous subarray of min(subarray)`? 2. Mod `10^9+7`? 64-bit `long` enough? 3. Duplicates: if two equal mins, which index owns the subarray (need a strict side to avoid double-count)? 4. `n` up to? Negative values? 5. Return type `int` vs `long`? 6. Empty array → 0? **Trick / pattern in one sentence** Each `arr[i]` contributes `arr[i] * (count of subarrays where it is the chosen minimum)`; those counts come from previous/next smaller via a monotonic stack, not from enumerating subarrays. **Why this data structure** - brute: nested loops (array only) — too slow for typical `n ~ 10^5` - optimal: **monotonic increasing stack** of indices — O(1) amortized previous/next smaller - refuse: segment tree / sparse table for RMQ on every `[L,R]` — correct but overkill and slower to code in Live Code; refuse a `TreeMap` of values — does not give subarray ranges **Brute** Idea: every `L,R`, scan for min, add it. ```java public int sumSubarrayMinsBrute(int[] arr) { final int MOD = 1_000_000_007; long sum = 0; int n = arr.length; for (int left = 0; left < n; left++) { int minVal = arr[left]; for (int right = left; right < n; right++) { minVal = Math.min(minVal, arr[right]); sum += minVal; if (sum >= MOD) sum -= MOD; } } return (int) sum; } ``` TC `O(n^2)` (O(n³) if you re-scan min every time). SC `O(1)`. Fails `n = 10^5`. **Optimal** 1. For each `i`, `prevLess[i]` = nearest index `j < i` with `arr[j] < arr[i]` (else `-1`). 2. `nextLessEq[i]` = nearest `k > i` with `arr[k] <= arr[i]` (else `n`). One side strict, one `<=`, so equal mins are assigned to the leftmost (or rightmost — pick one and stick). 3. Contribution = `arr[i] * (i - prevLess[i]) * (nextLessEq[i] - i)`. 4. Sum mod. ```java public int sumSubarrayMins(int[] arr) { final int MOD = 1_000_000_007; int n = arr.length; int[] prevLess = new int[n]; int[] nextLessEq = new int[n]; Deque stack = new ArrayDeque<>(); for (int i = 0; i < n; i++) { while (!stack.isEmpty() && arr[stack.peek()] >= arr[i]) { stack.pop(); } prevLess[i] = stack.isEmpty() ? -1 : stack.peek(); stack.push(i); } stack.clear(); for (int i = n - 1; i >= 0; i--) { while (!stack.isEmpty() && arr[stack.peek()] > arr[i]) { stack.pop(); } nextLessEq[i] = stack.isEmpty() ? n : stack.peek(); stack.push(i); } long sum = 0; for (int i = 0; i < n; i++) { long leftCount = i - prevLess[i]; long rightCount = nextLessEq[i] - i; sum = (sum + (arr[i] * leftCount % MOD) * rightCount) % MOD; } return (int) sum; } ``` Dry run `arr = [3, 1, 2, 4]`: | i | arr[i] | prevLess | nextLessEq | left | right | contrib | | --- | ---: | ---: | ---: | ---: | ---: | ---: | | 0 | 3 | -1 | 1 | 1 | 1 | 3 | | 1 | 1 | -1 | 4 | 2 | 3 | 6 | | 2 | 2 | 1 | 4 | 1 | 2 | 4 | | 3 | 4 | 2 | 4 | 1 | 1 | 4 | Sum = 17. Subarrays: `[3]=3, [3,1]=1, [3,1,2]=1, [3,1,2,4]=1, [1]=1, [1,2]=1, [1,2,4]=1, [2]=2, [2,4]=2, [4]=4` → 17. TC `O(n)`. SC `O(n)`. Follow-ups they asked: **optimization** (this stack is the optimization over O(n²)). Short project after. **If you get stuck in Live Code** - Ship the O(n²) min-scan, state the stack, then fill `prevLess` only. - If ties explode the answer, freeze one side as strict and re-dry-run `[1,1]`. --- ### coding UNNAMED — our R2 — AUTA — https://old.reddit.com/r/amazonemployees/comments/1qj304z/amazon_sde_1_interview_india_chennai_experience/ **What they actually asked** AUTA Chennai: R1 12 Dec 2025, R2 **29 Dec 2025**, BR 2 Jan 2026 LP-only. First-hand body: coding in R1 and R2, **titles never posted**. Stay unnamed. Do not guess an LC id. **Clarify out loud** 1. Input types, constraints, one worked example. 2. Mutate in place or return new? 3. Duplicate / null / empty policy. 4. Time they want (Live Code often wants the O-optimal after a working brute). 5. Follow-up expected after first AC-looking code? **Trick / pattern in one sentence** Unknown title → treat it as a 25–30 min medium: state brute, name the DS, then code; Chennai AUTA consecutive-day does not tell us array vs tree vs graph. **Why this data structure** Do not pre-commit. Ask constraints: `n ≤ 100` brute is fine; `n ~ 10^5` needs linear/n-log; graph vs tree vs string changes the DS. Refuse inventing a problem. **Pattern card (not a solution to a guessed problem)** - Hash + array two-pass (freq, prefix, first/last index). - Tree recursion with a return struct (height, sum, balanced). - Graph BFS/DFS on adj list. - Binary search on answer if “min X such that …” - Stack if next-greater / histogram / parse. **Brute / Optimal** Not applicable — no named statement. Write brute of *whatever they typed*, then upgrade. **If you get stuck in Live Code** - Narrate I/O + brute first; ask for a hint rather than inventing a famous LC. - Dry-run their example before optimizing. --- ### row-wise sorted m×n 0/1 matrix, row with max 1s — our R2 — AUTA mail — https://interviewexperiences.in/experience/amazon/amazon-sde-1-interview-experience-2024-grad-17-yoe-tier-3-college-selected **What they actually asked** IE.in 2024-grad AUTA (R2 **4 Dec 2025**): `m×n` matrix of `0/1`, **each row sorted**, find the **row with the maximum number of 1s**. Interviewer walked brute → per-row binary search → `O(m+n)`. Two named LPs in the same hour (not this card). **Clarify out loud** 1. Rows independently sorted (0s then 1s)? 2. Tie: smallest row index, or any? 3. No 1s at all → `-1` or `0`? 4. Only 0/1, or other values? 5. `m,n` up to? 6. Return row index or the count of 1s? **Trick / pattern in one sentence** In a row-sorted 0/1 row, the 1s are a suffix; start at top-right and only move **left on 1** (found a better count) or **down on 0** (this row cannot beat current). **Why this data structure** - brute: scan every cell — array is enough, `O(mn)` - per-row BS: still an array; first `1` via binary search - optimal `O(m+n)`: two indices `(row, col)` — not a heap, not a set - refuse: flattening / sorting the whole matrix — destroys row identity **Brute** ```java public int rowWithMaxOnesBrute(int[][] mat) { int bestRow = -1; int bestCount = -1; for (int r = 0; r < mat.length; r++) { int count = 0; for (int c = 0; c < mat[r].length; c++) { count += mat[r][c]; } if (count > bestCount) { bestCount = count; bestRow = r; } } return bestCount == 0 ? -1 : bestRow; // confirm empty policy } ``` TC `O(mn)`. SC `O(1)`. Fine for tiny matrices; they asked you to beat this. **Optimal** Per-row BS (`O(m log n)`): ```java public int rowWithMaxOnesBinarySearch(int[][] mat) { int bestRow = -1; int bestCount = 0; int n = mat[0].length; for (int r = 0; r < mat.length; r++) { int firstOne = firstOneIndex(mat[r]); int count = (firstOne == -1) ? 0 : n - firstOne; if (count > bestCount) { bestCount = count; bestRow = r; } } return bestRow; } private int firstOneIndex(int[] row) { int lo = 0, hi = row.length - 1, ans = -1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (row[mid] == 1) { ans = mid; hi = mid - 1; } else { lo = mid + 1; } } return ans; } ``` `O(m+n)` staircase (what they pushed): ```java public int rowWithMaxOnes(int[][] mat) { int m = mat.length; int n = mat[0].length; int row = 0; int col = n - 1; int bestRow = -1; while (row < m && col >= 0) { if (mat[row][col] == 1) { bestRow = row; col--; } else { row++; } } return bestRow; } ``` Dry run ``` row0: 0 0 0 1 1 row1: 0 1 1 1 1 row2: 0 0 0 0 0 row3: 0 0 1 1 1 ``` Start `(0,4)=1` → best=0, col=3. `(0,3)=1` → best=0, col=2. `(0,2)=0` → row=1. `(1,2)=1` → best=1, col=1. `(1,1)=1` → best=1, col=0. `(1,0)=0` → row=2. `(2,0)=0` → row=3. `(3,0)=0` → row=4 stop. Answer **row 1** (four 1s). | step | (row,col) | cell | bestRow | next | | ---: | --- | ---: | ---: | --- | | 1 | (0,4) | 1 | 0 | left | | 2 | (0,3) | 1 | 0 | left | | 3 | (0,2) | 0 | 0 | down | | 4 | (1,2) | 1 | 1 | left | | 5 | (1,1) | 1 | 1 | left | | 6 | (1,0) | 0 | 1 | down | | … | … | 0 | 1 | down until end | TC `O(m+n)`. SC `O(1)`. Follow-ups: brute / per-row BS / `O(m+n)` as they asked; column-wise sorted variant; return the count not the index. **If you get stuck in Live Code** - Code per-row `firstOne` BS; that already beats brute. - If staircase indices confuse you, start at top-right on paper for a 3×3 before typing. --- ### Koko Eating Bananas–like binary search — our R2 — UTA — https://medium.com/@nainavangani09/my-amazon-sde-1-interview-experience-2025-selected-dea6b5e9e3e9 **What they actually asked** Naina Vangani (named **UTA**, R2 **19 Jun 2025**): a **Koko Eating Bananas–like** binary search on answer, plus a second tree problem (next card). Live Code: **full I/O + dry run**. Candidate said **like**, not that an LC slug was the prompt. **Clarify out loud** 1. `piles[i]` bananas, `h` hours, speed `k` bananas/hour, one pile per hour, `ceil(pile/k)` hours per pile? 2. Finish all piles in `≤ h` hours; **minimize `k`**? 3. `k` integer? `h >= piles.length`? 4. Max pile as upper bound? 5. Overflow on `long` hours? 6. Empty piles? **Trick / pattern in one sentence** Feasibility `hoursNeeded(k) <= h` is monotonic in `k`, so binary-search the minimum feasible speed. **Why this data structure** - brute: try `k = 1,2,…max(pile)` — no extra DS, `O(max * n)` - optimal: binary search on the integer range `[1, max]`; still an array for the check - refuse: sorting piles (does not change the check); refuse a heap of piles — that solves a different “eat largest first” story, not this hour-budget **Brute** ```java public int minEatingSpeedBrute(int[] piles, int h) { int maxPile = 0; for (int pile : piles) maxPile = Math.max(maxPile, pile); for (int speed = 1; speed <= maxPile; speed++) { if (hoursNeeded(piles, speed) <= h) return speed; } return maxPile; } ``` TC `O(max(pile) * n)`. SC `O(1)`. Dies if piles are `10^9`. **Optimal** ```java public int minEatingSpeed(int[] piles, int h) { int lo = 1; int hi = 0; for (int pile : piles) hi = Math.max(hi, pile); int answer = hi; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (hoursNeeded(piles, mid) <= h) { answer = mid; hi = mid - 1; } else { lo = mid + 1; } } return answer; } private long hoursNeeded(int[] piles, int speed) { long hours = 0; for (int pile : piles) { hours += (pile + (long) speed - 1) / speed; } return hours; } ``` Dry run `piles = [3,6,7,11]`, `h = 8`: | lo | hi | mid | hoursNeeded | action | | ---: | ---: | ---: | ---: | --- | | 1 | 11 | 6 | 1+1+2+2=6 ≤ 8 | hi=5, ans=6 | | 1 | 5 | 3 | 1+2+3+4=10 > 8 | lo=4 | | 4 | 5 | 4 | 1+2+2+3=8 ≤ 8 | hi=3, ans=4 | | 4 | 3 | stop | | **k=4** | TC `O(n log M)` `M=max(pile)`. SC `O(1)`. Follow-ups Naina-style: full I/O; dry run; “why binary search not linear”; overflow; `h` equal to `n` → answer is `max(pile)`. **If you get stuck in Live Code** - Write `hoursNeeded` and linear scan `k`; then wrap it in `lo/hi`. - If off-by-one, re-run the table for `h=8` until `k=4`. --- ### equal-split binary tree (remove one edge) — our R2 — UTA — https://medium.com/@nainavangani09/my-amazon-sde-1-interview-experience-2025-selected-dea6b5e9e3e9 **What they actually asked** Same Naina R2: **equal-split binary tree** by **removing one edge** (two remaining trees have equal sum). Follow-ups: **Why not BFS? no recursion? space?** Full I/O + dry run. GFG-style statement; **no numeric LC id** in the bible. **Clarify out loud** 1. Equal **sum of node values**, or equal **node count**? 2. Exactly one edge removed? Must both sides be non-empty? 3. Values can be 0 / negative? 4. If total sum odd → false? 5. Return boolean, the edge, or the two roots? 6. Tree size? **Trick / pattern in one sentence** If total sum is `S` (even), you can split iff some **subtree sum** equals `S/2` (that subtree is one side after cutting its parent edge). **Why this data structure** - brute: for every edge, DFS both sides’ sums — tree edges, `O(n²)` - optimal: one post-order DFS computing subtree sums — the tree itself - refuse: BFS-first for this question (see follow-up); refuse converting to undirected graph + checking every edge unless they ban recursion and you need parent pointers **Brute** Detach each child once, compare `sum(child)` vs `total - sum(child)`. ```java public boolean canSplitEqualBrute(TreeNode root) { if (root == null) return false; long total = sum(root); return anyCutEquals(root, total); } private boolean anyCutEquals(TreeNode parent, long total) { if (parent == null) return false; if (parent.left != null) { long leftSum = sum(parent.left); if (leftSum == total - leftSum) return true; if (anyCutEquals(parent.left, total)) return true; } if (parent.right != null) { long rightSum = sum(parent.right); if (rightSum == total - rightSum) return true; if (anyCutEquals(parent.right, total)) return true; } return false; } private long sum(TreeNode node) { if (node == null) return 0; return node.val + sum(node.left) + sum(node.right); } ``` TC `O(n²)` (sum re-walks each subtree). SC `O(h)`. **Optimal** One post-order pass. A cut exists iff some **proper** subtree sums to `total/2` (the full tree always sums to `total` — that is “remove nothing”). ```java public boolean canSplitEqual(TreeNode root) { if (root == null) return false; long total = sum(root); if (total % 2 != 0) return false; boolean[] found = { false }; fillAndCheck(root, total / 2, found); return found[0]; } private long fillAndCheck(TreeNode node, long half, boolean[] found) { if (node == null) return 0; long s = node.val + fillAndCheck(node.left, half, found) + fillAndCheck(node.right, half, found); if (s == half) found[0] = true; // proper subtree: root’s s equals total, not half (unless total=0) return s; } ``` If `total == 0`, ask: is a zero-sum child a valid cut? For Live Code, treat `total == 0` as “only if a child subtree exists.” If they want the edge, remember the child node when `s == half`. Single-pass flag is `O(h)` extra. HashSet of all subtree sums is the same idea, `O(n)` extra — skip if they asked space. Dry run — cut the edge under 1 to the right child 3: ``` 1 / \ 2 3 ``` | node | subtree sum | == total/2=3? | | --- | ---: | --- | | 2 | 2 | no | | 3 | 3 | **yes** | | 1 | 6 | ignore (full tree) | Cut `1—3`: `{1,2}` sum 3 and `{3}` sum 3. True. **Why not BFS?** BFS layer-order does not produce **subtree** aggregates. You would still need a post-order (or two-pass with parent pointers + child-done counts). BFS is the wrong traversal for “sum of a cut-off component that is a subtree.” **No recursion?** Iterative post-order: ```java public boolean canSplitEqualIterative(TreeNode root) { if (root == null) return false; Map sub = new HashMap<>(); Deque stack = new ArrayDeque<>(); TreeNode last = null; TreeNode cur = root; while (cur != null || !stack.isEmpty()) { if (cur != null) { stack.push(cur); cur = cur.left; } else { TreeNode peek = stack.peek(); if (peek.right != null && last != peek.right) { cur = peek.right; } else { long s = peek.val + (peek.left == null ? 0 : sub.get(peek.left)) + (peek.right == null ? 0 : sub.get(peek.right)); sub.put(peek, s); last = stack.pop(); } } } long total = sub.get(root); if (total % 2 != 0) return false; long half = total / 2; for (Map.Entry e : sub.entrySet()) { if (e.getKey() != root && e.getValue() == half) return true; } return false; } ``` **Space:** recursion `O(h)` extra; HashSet of subtree sums `O(n)`; iterative post-order `O(n)` map + `O(h)` stack. You cannot beat `O(n)` if you materialize all subtree sums; you can stream a boolean and keep `O(h)` if you only need yes/no (`found` flag, no set). TC `O(n)`. SC `O(n)` with the set, `O(h)` with the flag (careful not to match the root). Follow-ups: Why not BFS; no recursion; space; negatives (then `S/2` subtree can exist in more than one way — still OK if you skip the full tree); return the actual edge. **If you get stuck in Live Code** - Compute `total`, then brute-cut each child with `sum(child) == total/2`. - If recursion is banned, say you will post-order with a stack and a `sub` map. --- ### matrix medium UNNAMED — our R2 — AUTA — https://www.linkedin.com/posts/divanshu-bansal-8979bb235_amazon-has-started-hiring-for-the-2025-batch-activity-7359833353472131073-LgFq **What they actually asked** Divanshu Bansal (AUTA 2025 batch India): R2 May 2025 — **matrix medium UNNAMED** (plus a math medium). Titles stay unnamed. Do not guess Unique Paths / Rotating / DP-on-grid LC ids. **Clarify out loud** 1. Grid values: 0/1, weights, obstacles? 2. Moves: 4-dir, right/down only, 8-dir? 3. Goal: count paths, min cost, max path, flood fill, rotate, set zeroes? 4. In-place? 5. `m,n` and value ranges. **Trick / pattern in one sentence** Unnamed matrix medium in Amazon Live Code is usually DFS/BFS flood, 2D DP (paths/min-cost), or in-place layer/rotate — wait for the prompt. **Why this data structure** - brute: recurse every path / scan `O(mn)` if that is enough - optimal: DP table or BFS queue, or in-place markers - refuse: inventing a famous problem before they finish the statement **Pattern card** - Path-count / min-cost: `dp[i][j]` from up/left; obstacles skip. - Multi-source BFS if “minutes / distance to nearest X”. - Prefix-sum 2D if submatrix queries. - In-place: first row/col flags, or layer-by-layer. **If you get stuck in Live Code** - Draw the grid and one path; code the recurrence they agreed. - If DP states explode, DFS + memo on `(r,c,mask)` only if they stated extra state. --- ### math medium UNNAMED — our R2 — AUTA — https://www.linkedin.com/posts/divanshu-bansal-8979bb235_amazon-has-started-hiring-for-the-2025-batch-activity-7359833353472131073-LgFq **What they actually asked** Same Divanshu R2: **math medium UNNAMED**. Candidate **explained optimal, did not fully code**. Stay unnamed. Do not stamp an LC id. **Clarify out loud** 1. Integer only? Overflow / mod? 2. Closed form vs search vs DP on digits? 3. Constraints (if `n ≤ 10^12`, you cannot DP on `n`). 4. They happy with complexity proof without full code (this IE)? **Trick / pattern in one sentence** Math medium Live Code is often binary exponentiation, gcd/lcm, digit DP, or “min ops on a number” — code the check/loop they defined, not a guessed puzzle. **Why this data structure** Usually **no fancy DS**: a few `long`s, maybe a `boolean[]` sieve if `n` is small. Refuse hashing a “formula from memory” you cannot derive. **Pattern card** - Fast pow / mod mul. - Factor / sieve if `n ≤ 10^6`. - Binary search on answer if monotonic. - Digit greed (max digit, min digits) — related to B4 subtract-digit, but **do not claim Divanshu asked that**. **If you get stuck in Live Code** - Same as this IE: explain the optimal math, then code the inner loop. - Work a 2–3 digit example before generalizing. --- ### Rotate Image — our R2 — AUTA — https://leetcode.com/discuss/post/6806195/amazon-auta-interview-experience-sde-1-2-f90u/ **What they actually asked** LC 6806195 AUTA Bengaluru (R2 May 2025): **Rotate Image** (candidate **LC-linked**). n×n matrix, 90° clockwise, typically **in place**. Same round also Next Permutation **similar** (next card). **Clarify out loud** 1. Clockwise 90°? Counter-clockwise follow-up? 2. Must be in-place `O(1)` extra? 3. Always square? 4. `int` cells only? 5. n = 0 / 1? 6. Anti-clockwise as follow-up? **Trick / pattern in one sentence** Clockwise 90° = **transpose** then **reverse each row** (or rotate layer rings). **Why this data structure** - brute: extra `n×n` matrix — simple, not in-place - optimal: in-place swaps on the 2D array; no extra DS - refuse: flattening to 1D and computing `newIndex = …` with an extra array — same extra space as brute; refuse `Queue` of layers **Brute** ```java public void rotateBrute(int[][] matrix) { int n = matrix.length; int[][] copy = new int[n][n]; for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { copy[c][n - 1 - r] = matrix[r][c]; } } for (int r = 0; r < n; r++) { System.arraycopy(copy[r], 0, matrix[r], 0, n); } } ``` TC `O(n²)`. SC `O(n²)`. **Optimal** ```java public void rotate(int[][] matrix) { int n = matrix.length; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { int tmp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = tmp; } } for (int i = 0; i < n; i++) { int left = 0, right = n - 1; while (left < right) { int tmp = matrix[i][left]; matrix[i][left] = matrix[i][right]; matrix[i][right] = tmp; left++; right--; } } } ``` Dry run ``` 1 2 3 transpose 1 4 7 reverse rows 7 4 1 4 5 6 → 2 5 8 → 8 5 2 7 8 9 3 6 9 9 6 3 ``` | step | op | matrix | | --- | --- | --- | | 0 | start | `[[1,2,3],[4,5,6],[7,8,9]]` | | 1 | swap (0,1)/(1,0) | `[[1,4,3],[2,5,6],[7,8,9]]` | | 2 | swap (0,2)/(2,0) | `[[1,4,7],[2,5,6],[3,8,9]]` | | 3 | swap (1,2)/(2,1) | `[[1,4,7],[2,5,8],[3,6,9]]` | | 4 | reverse rows | `[[7,4,1],[8,5,2],[9,6,3]]` | TC `O(n²)`. SC `O(1)`. Follow-ups: 90° CCW = reverse rows then transpose (or transpose then reverse columns); 180°; layer-by-layer 4-way swap if they ban transpose. **If you get stuck in Live Code** - Allocate `copy` and map `(r,c) → (c, n-1-r)`; then try in-place. - Rotate one ring: `top → right → bottom → left` with 4 temps. --- ### Next Permutation similar — our R2 — AUTA — https://leetcode.com/discuss/post/6806195/amazon-auta-interview-experience-sde-1-2-f90u/ **What they actually asked** Same LC 6806195 R2: **similar to Next Permutation**, **approach only** (not necessarily a full code of an exact LC). Label **similar**, not exact. **Clarify out loud** 1. Next **lexicographic** permutation of the array, in place? 2. If already last permutation, wrap to the first (sorted ascending)? 3. Duplicates allowed? 4. Approach-only OK (this IE) or they want code today? 5. Next permutation of a **number** (digits) vs array? **Trick / pattern in one sentence** Find the rightmost ascent `i` (`a[i] < a[i+1]`), swap `a[i]` with the rightmost successor `> a[i]`, reverse the suffix — that is the next permutation. **Why this data structure** - brute: generate all unique perms, sort, pick next — extra list of perms - optimal: in-place array scans; no extra DS beyond a few indices - refuse: `next_permutation` library as the whole answer (they want the algorithm); refuse a `TreeSet` of all perms **Brute** ```java public void nextPermutationBrute(int[] nums) { int[] original = nums.clone(); Arrays.sort(nums); List all = new ArrayList<>(); permuteUnique(nums, 0, all); all.sort((a, b) -> { for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) return Integer.compare(a[i], b[i]); } return 0; }); // find original, copy the next (or first) } ``` Sketch: `O(n! * n)`. Do not ship this unless n ≤ 7. **Optimal** ```java public void nextPermutation(int[] nums) { int n = nums.length; int i = n - 2; while (i >= 0 && nums[i] >= nums[i + 1]) { i--; } if (i >= 0) { int j = n - 1; while (nums[j] <= nums[i]) { j--; } swap(nums, i, j); } reverse(nums, i + 1, n - 1); } private void swap(int[] nums, int a, int b) { int t = nums[a]; nums[a] = nums[b]; nums[b] = t; } private void reverse(int[] nums, int lo, int hi) { while (lo < hi) { swap(nums, lo++, hi--); } } ``` Dry run `nums = [1, 3, 5, 4, 2]`: | step | what | array | | --- | --- | --- | | 1 | rightmost `i` with `a[i] < a[i+1]` | `i=1` (`3<5`) | | 2 | rightmost `j` with `a[j] > 3` | `j=3` (`4`) | | 3 | swap i,j | `[1, 4, 5, 3, 2]` | | 4 | reverse suffix after i | `[1, 4, 2, 3, 5]` | TC `O(n)`. SC `O(1)`. Follow-ups: previous permutation (mirror inequalities); next permutation of a **string**; they may stop at approach (this IE). **If you get stuck in Live Code** - Sort the whole array (that is the wrap-around case) and say you still need the pivot scan. - Walk `[1,3,2]` → `[2,1,3]` on the whiteboard before coding. --- ### Rotten oranges variation — our R2 — AUTA — https://leetcode.com/discuss/post/7406809/amazon-sde-1-auta-interview-experience-s-k6t7/ **What they actually asked** LC 7406809 AUTA (interviews Nov 2025): **Rotten oranges variation** (candidate LC-linked the family). Multi-source rotting over minutes. Ask what the variation is (8-dir, no mutate, return leftover count, etc.) — do not invent a second problem. **Clarify out loud** 1. `0` empty, `1` fresh, `2` rotten? 2. 4-dir or 8-dir (variation)? 3. One minute = all currently rotten infect neighbors simultaneously? 4. Return minutes, or `-1` if a fresh orange never rots? 5. Mutate the grid? 6. No fresh oranges → `0`? **Trick / pattern in one sentence** All initially rotten oranges are **one BFS wave**; minutes = BFS level; leftover fresh → `-1`. **Why this data structure** - brute: while something changed, scan whole grid — `O(minutes * mn)` with `minutes ≤ mn` - optimal: **queue** of rotten cells (multi-source BFS) - refuse: DFS from one rotten (wrong simultaneity); refuse Dijkstra (unweighted) **Brute** ```java public int orangesRottingBrute(int[][] grid) { int minutes = 0; while (true) { List willRot = new ArrayList<>(); int fresh = 0; for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[0].length; c++) { if (grid[r][c] == 1) { fresh++; if (hasRottenNeighbor(grid, r, c)) willRot.add(new int[] { r, c }); } } } if (willRot.isEmpty()) return fresh == 0 ? minutes : -1; for (int[] cell : willRot) grid[cell[0]][cell[1]] = 2; minutes++; } } ``` TC `O(m²n²)` worst. SC `O(mn)`. **Optimal** ```java public int orangesRotting(int[][] grid) { int rows = grid.length, cols = grid[0].length; Queue queue = new ArrayDeque<>(); int fresh = 0; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) { if (grid[r][c] == 2) queue.add(new int[] { r, c }); else if (grid[r][c] == 1) fresh++; } } if (fresh == 0) return 0; int[][] dirs = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } }; int minutes = 0; while (!queue.isEmpty() && fresh > 0) { int size = queue.size(); for (int i = 0; i < size; i++) { int[] cell = queue.poll(); for (int[] d : dirs) { int nr = cell[0] + d[0], nc = cell[1] + d[1]; if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue; if (grid[nr][nc] != 1) continue; grid[nr][nc] = 2; fresh--; queue.add(new int[] { nr, nc }); } } minutes++; } return fresh == 0 ? minutes : -1; } ``` Dry run ``` 2 1 1 1 1 0 0 1 1 ``` | minute | queue (rotten just processed) | fresh left | | ---: | --- | ---: | | 0 | (0,0) | 6 | | 1 | (0,1),(1,0) | 4 | | 2 | (0,2),(1,1) | 2 | | 3 | (1,2),(2,1) | 1 | | 4 | (2,2) | 0 | Answer **4**. TC `O(mn)`. SC `O(mn)`. Follow-ups: 8-dir (variation — add diagonals); do not mutate (queue of copies / extra visited); count of oranges that never rot. **If you get stuck in Live Code** - Code the “scan until stable” brute; then put initial `2`s in a queue. - If minutes are off by one, only increment after a level that actually rotted something. --- ### All nodes distance K WITHOUT parent map — our R2 — AUTA — https://leetcode.com/discuss/post/7406809/amazon-sde-1-auta-interview-experience-s-k6t7/ **What they actually asked** Same LC 7406809 R2: **All nodes distance K**, **without parent map**, recursive. Candidate LC-linked the family. **Reprint:** LC 7623949 labeled the slot **GenAI Fluency** but the work was this DSA (no parent mapping, O(n)). **Clarify out loud** 1. Binary tree, target node object (or value?), integer `k`? 2. Return values of nodes at distance `k` (any order)? 3. **Forbidden:** `HashMap` parent map? 4. Unique values? 5. `k = 0` → `[target]`? 6. Distance through parent counts? **Trick / pattern in one sentence** Distance-K is BFS on the **undirected** tree; you may build an adjacency list (not a parent map) **or** recurse: after finding target, walk down `k` and, on the way up, walk the sibling with remaining distance. **Why this data structure** - brute: for every node, compute distance to target via two DFS — `O(n²)` - with parent map (they **forbade**): `Map` then BFS - allowed optimal A: **adj list graph** `Map>` then BFS — this is not a parent map - allowed optimal B: **no extra map of parents**; DFS return-distance + `collectDown` - refuse: the forbidden parent HashMap if they restated the constraint **Brute** ```java public List distanceKBrute(TreeNode root, TreeNode target, int k) { List ans = new ArrayList<>(); List nodes = new ArrayList<>(); collect(root, nodes); for (TreeNode node : nodes) { if (dist(node, target, null) == k) ans.add(node.val); } return ans; } private int dist(TreeNode a, TreeNode b, TreeNode banned) { if (a == null) return -1; if (a == b) return 0; // would need undirected walk — brute usually converts to graph first return -1; } ``` Honest brute in Live Code: build undirected graph, then from every node BFS until target — `O(n²)`. **Optimal — version 1: DFS builds undirected graph, then BFS (no parent HashMap)** ```java public List distanceKViaGraph(TreeNode root, TreeNode target, int k) { Map> graph = new HashMap<>(); buildUndirected(root, null, graph); List ans = new ArrayList<>(); Queue queue = new ArrayDeque<>(); Set seen = new HashSet<>(); queue.add(target); seen.add(target); int dist = 0; while (!queue.isEmpty()) { int size = queue.size(); if (dist == k) { for (TreeNode node : queue) ans.add(node.val); return ans; } for (int i = 0; i < size; i++) { TreeNode cur = queue.poll(); for (TreeNode nei : graph.getOrDefault(cur, new ArrayList<>())) { if (seen.add(nei)) queue.add(nei); } } dist++; } return ans; } private void buildUndirected(TreeNode node, TreeNode from, Map> graph) { if (node == null) return; graph.putIfAbsent(node, new ArrayList<>()); if (from != null) { graph.get(node).add(from); graph.get(from).add(node); } buildUndirected(node.left, node, graph); buildUndirected(node.right, node, graph); } ``` `from` is a **call parameter**, not a stored parent map. **Optimal — version 2: recursive, no parent map, no graph (what 7406809 “recursive / no parent map” matches)** ```java public List distanceKNoParentMap(TreeNode root, TreeNode target, int k) { List ans = new ArrayList<>(); find(root, target, k, ans); return ans; } /** @return distance from node down to target, or -1 if target not in this subtree */ private int find(TreeNode node, TreeNode target, int k, List ans) { if (node == null) return -1; if (node == target) { collectDown(node, k, ans); return 0; } int left = find(node.left, target, k, ans); if (left != -1) { if (left + 1 == k) ans.add(node.val); collectDown(node.right, k - left - 2, ans); return left + 1; } int right = find(node.right, target, k, ans); if (right != -1) { if (right + 1 == k) ans.add(node.val); collectDown(node.left, k - right - 2, ans); return right + 1; } return -1; } private void collectDown(TreeNode node, int dist, List ans) { if (node == null || dist < 0) return; if (dist == 0) { ans.add(node.val); return; } collectDown(node.left, dist - 1, ans); collectDown(node.right, dist - 1, ans); } ``` Dry run — target = 5, k = 2: ``` 3 / \ 5 1 / \ / \ 6 2 0 8 / \ 7 4 ``` | call | return dist to 5 | extra collect | ans | | --- | ---: | --- | --- | | find(5) | 0 | down k=2 → 7,4 | 7,4 | | find(3) left=0 | 1 | `1==k`? no; collectDown(1, 0) → **1** | 7,4,1 | Nodes at dist 2: `7, 4, 1`. TC `O(n)`. SC `O(h)` recursion (version 2) or `O(n)` graph (version 1). Follow-ups: print path (their BR was a different tree-path print); O(n) required; GenAI Fluency reprint on LC 7623949 is the same constraint. **If you get stuck in Live Code** - Say you would store parents, then immediately switch to `buildUndirected` if they ban the map. - If graph is also “too much space,” code `find` + `collectDown` only. --- ### Merge k sorted linked lists — our R2 — AUTA — https://leetcode.com/discuss/post/7563011/amazon-sde-1-interview-experience-by-ano-duqw/ **What they actually asked** LC 7563011 AUTA Bengaluru (R2 **1 Aug 2025**): **Merge k sorted linked lists**, plus named LPs (dive deep / project on your own / miss a deadline). **Clarify out loud** 1. `k` lists, each already sorted ascending? 2. Lists can be empty / `k = 0`? 3. Duplicate values OK? 4. New list vs mutate? 5. `n` = total nodes, `k` up to? 6. Singly linked `ListNode`? **Trick / pattern in one sentence** Always take the current smallest head among `k` lists — a **min-heap of list heads** does that in `log k` per node. **Why this data structure** - brute: merge lists one-by-one with two-pointer merge — array of heads, no heap - optimal: `PriorityQueue` ordered by `val` - refuse: putting **all** node values into an array and sorting — loses the “already sorted lists” structure (they may still accept it as a first code) **Brute** ```java public ListNode mergeKListsBrute(ListNode[] lists) { ListNode merged = null; for (ListNode list : lists) { merged = mergeTwo(merged, list); } return merged; } private ListNode mergeTwo(ListNode a, ListNode b) { ListNode dummy = new ListNode(0); ListNode tail = dummy; while (a != null && b != null) { if (a.val <= b.val) { tail.next = a; a = a.next; } else { tail.next = b; b = b.next; } tail = tail.next; } tail.next = (a != null) ? a : b; return dummy.next; } ``` TC `O(k n)` if lists are similar length (`n` total nodes: first merge 2n, then 3n, …). SC `O(1)` extra. **Optimal** ```java public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) return null; PriorityQueue minHeap = new PriorityQueue<>(Comparator.comparingInt(node -> node.val)); for (ListNode head : lists) { if (head != null) minHeap.add(head); } ListNode dummy = new ListNode(0); ListNode tail = dummy; while (!minHeap.isEmpty()) { ListNode node = minHeap.poll(); tail.next = node; tail = tail.next; if (node.next != null) minHeap.add(node.next); } return dummy.next; } ``` Dry run lists `[1→4→5]`, `[1→3→4]`, `[2→6]`: | heap heads | poll | emit so far | | --- | ---: | --- | | 1,1,2 | 1 (list0) | 1 | | 4,1,2 | 1 (list1) | 1→1 | | 4,3,2 | 2 | 1→1→2 | | 4,3,6 | 3 | 1→1→2→3 | | 4,4,6 | 4 (list0) | …→4 | | 5,4,6 | 4 (list1) | …→4 | | 5,6 | 5 | …→5 | | 6 | 6 | 1→1→2→3→4→4→5→6 | TC `O(n log k)`. SC `O(k)`. Follow-ups: divide-and-conquer merge (also `O(n log k)`, no heap); arrays not lists; iterator of k streams. **If you get stuck in Live Code** - Merge two at a time (`mergeKListsBrute`). - If heap comparator NPEs, skip null heads when offering. --- ### Word Ladder — our R2 — AUTA — https://leetcode.com/discuss/post/7035289/amazon-sde-1-offer-by-anonymous_user-3efp/ **What they actually asked** LC 7035289 AUTA: R2 **Word Ladder** and Count Beautiful Splits (next card). Shortest transformation sequence **length** (or 0 if impossible), beginWord → endWord, one letter per step, each intermediate in the word list. **Clarify out loud** 1. Return **length** of shortest ladder (including begin and end) or the list of words? 2. `wordList` contains `endWord`? `beginWord` in the list? 3. Same length words, lowercase? 4. Multiple shortest? 5. `wordList` size / word length? **Trick / pattern in one sentence** Unweighted shortest path in the word graph → **BFS**; neighbors = words differing by one character. **Why this data structure** - brute: DFS all transformations — exponential - optimal: **queue + HashSet** remaining words; optional `Map>` (`*ot` → hot, dot) - refuse: Dijkstra (weights are 1); refuse building `n²` adjacency up front if `n` is huge and `L` is small — generate neighbors by mutating `L` chars **Brute** ```java public int ladderLengthDfs(String begin, String end, List wordList) { Set unused = new HashSet<>(wordList); int[] best = { Integer.MAX_VALUE }; dfs(begin, end, unused, 1, best); return best[0] == Integer.MAX_VALUE ? 0 : best[0]; } private void dfs(String cur, String end, Set unused, int len, int[] best) { if (cur.equals(end)) { best[0] = Math.min(best[0], len); return; } for (String w : new ArrayList<>(unused)) { if (oneDiff(cur, w)) { unused.remove(w); dfs(w, end, unused, len + 1, best); unused.add(w); } } } ``` TC exponential. SC `O(n)` recursion. **Optimal** ```java public int ladderLength(String beginWord, String endWord, List wordList) { Set unused = new HashSet<>(wordList); if (!unused.contains(endWord)) return 0; Queue queue = new ArrayDeque<>(); queue.add(beginWord); unused.remove(beginWord); int length = 1; while (!queue.isEmpty()) { int size = queue.size(); for (int s = 0; s < size; s++) { String cur = queue.poll(); if (cur.equals(endWord)) return length; char[] chars = cur.toCharArray(); for (int i = 0; i < chars.length; i++) { char saved = chars[i]; for (char ch = 'a'; ch <= 'z'; ch++) { chars[i] = ch; String next = new String(chars); if (unused.remove(next)) queue.add(next); } chars[i] = saved; } } length++; } return 0; } ``` Dry run `begin=hit`, `end=cog`, list `hot,dot,dog,lot,log,cog`: | length | queue | popped path idea | | ---: | --- | --- | | 1 | hit | | | 2 | hot | hit→hot | | 3 | dot, lot | hot→dot/lot | | 4 | dog, log | | | 5 | cog | **5** (`hit-hot-dot-dog-cog`) | TC `O(n * L * 26)` with set removals. SC `O(n * L)`. Follow-ups: return one actual ladder (store parent pointers); bidirectional BFS; Word Ladder II all shortest paths (do not start that unless asked). **If you get stuck in Live Code** - BFS storing `(word, dist)` pairs; generate neighbors by scanning the whole list (`O(n² L)`) if 26-letter mutation feels heavy. - If you forget to remove `beginWord`, you may loop — `unused.remove` on enqueue. --- ### Count Beautiful Splits — our R2 — AUTA — https://leetcode.com/discuss/post/7035289/amazon-sde-1-offer-by-anonymous_user-3efp/ **What they actually asked** Same LC 7035289 R2: candidate **named the title** Count Beautiful Splits and **did not link an LC id**. Do **not** invent 2478 / 2767 (or any other id) as “the asked id”. **Clarify out loud** 1. Split a string or an `int[]` into **two non-empty contiguous parts**? 2. What makes a part (or the split) **beautiful**? (ask them to define) 3. Count **ways** (split indices) or min cuts? 4. Overlapping / more than two parts? 5. Mod? **Trick / pattern in one sentence** Standard interpretation when they only named this title: count split indices `i` such that the left piece and the right piece form a **beautiful split** — most commonly, **one piece is a prefix of the other**. **Why this data structure** - brute: try every split, compare prefix arrays/strings - optimal: Z-array or rolling hash so prefix checks are O(1) after O(n) - refuse: stamping an LC number; refuse 3-way palindrome partition unless they said palindrome **Interpretation used below (id not named)** Given `nums[0..n-1]`, count `i` with `0 ≤ i ≤ n-2` such that `nums[0..i]` is a prefix of `nums[i+1..n-1]` **or** `nums[i+1..n-1]` is a prefix of `nums[0..i]`. If their beauty predicate is different (palindrome parts, even digits, …), swap only `isBeautifulSplit`. **Brute** ```java public int countBeautifulSplitsBrute(int[] nums) { int n = nums.length; int count = 0; for (int i = 0; i < n - 1; i++) { if (isPrefix(nums, 0, i + 1, i + 1, n - i - 1) || isPrefix(nums, i + 1, n - i - 1, 0, i + 1)) { count++; } } return count; } private boolean isPrefix(int[] a, int startA, int lenA, int startB, int lenB) { if (lenA > lenB) return false; for (int k = 0; k < lenA; k++) { if (a[startA + k] != a[startB + k]) return false; } return true; } ``` TC `O(n²)`. SC `O(1)`. **Optimal** (Z-function on the array as a sequence; prefix-of-other = `z[i] >= i` for split before `i`, plus the symmetric “right is prefix of left” which is `z` on reversed or a direct `z[0..]` check) For Live Code, rolling hash keeps the code shorter: ```java public int countBeautifulSplits(int[] nums) { int n = nums.length; if (n < 2) return 0; long mod = 1_000_000_007L; long base = 1_000_003L; long[] pow = new long[n + 1]; long[] hash = new long[n + 1]; pow[0] = 1; for (int i = 0; i < n; i++) { pow[i + 1] = pow[i] * base % mod; hash[i + 1] = (hash[i] * base + (nums[i] + 1L)) % mod; } int count = 0; for (int i = 0; i < n - 1; i++) { int leftLen = i + 1; int rightLen = n - i - 1; if (leftLen <= rightLen && rangeHash(hash, pow, 0, leftLen, mod) == rangeHash(hash, pow, i + 1, leftLen, mod)) { count++; } else if (rightLen < leftLen && rangeHash(hash, pow, i + 1, rightLen, mod) == rangeHash(hash, pow, 0, rightLen, mod)) { count++; } } return count; } private long rangeHash(long[] hash, long[] pow, int start, int len, long mod) { long v = (hash[start + len] - hash[start] * pow[len] % mod + mod) % mod; return v; } ``` Dry run `nums = [1, 1, 2, 1]`: | split after i | left | right | prefix? | | ---: | --- | --- | --- | | 0 | `[1]` | `[1,2,1]` | left prefix of right → yes | | 1 | `[1,1]` | `[2,1]` | no | | 2 | `[1,1,2]` | `[1]` | right prefix of left → yes | Count **2**. TC brute `O(n²)`; hash `O(n)` expected. SC `O(n)`. Follow-ups: they define a different beauty; three parts; mod collisions → fallback to verify on hit. **If you get stuck in Live Code** - Nested split + `isPrefix` is enough for n ~ 2000; say you would hash if n is 10^5. - Re-ask the beauty rule before coding palindromes. --- ### string compression wrap count at 9 — our R2 — UTA — https://leetcode.com/discuss/post/6653463/amazon-software-dev-engineer-1-universit-dtk5/ **What they actually asked** LC 6653463 UTA named (R2 Mar–Apr 2025): **string compression**, follow-up **wrap count at 9**. Consecutive runs only. Example discipline: `aaabaaa` → `a3ba3` **not** `a3b3` (do not merge non-adjacent groups). Wrap: a run of 11 `a`s → `a9a2`, not `a11`. **Clarify out loud** 1. Consecutive characters only (classic RLE)? 2. Count `1` omitted (`b` not `b1`)? 3. Wrap: max digit 9, split the run into chunks of 9? 4. In-place `char[]` or return `String`? 5. Only letters? 6. Empty string? **Trick / pattern in one sentence** Walk runs; for each run length `c`, emit the letter plus a count **capped at 9**, repeating until the run is consumed. **Why this data structure** - brute: `StringBuilder` while scanning — this **is** the solution; extra DS not needed - optimal: same one-pass; in-place two pointers if they want `char[]` - refuse: `HashMap` char→total count (that produces the wrong `a3b3` for `aaabaaa`) **Brute** Same as optimal for n Live Code; a worse brute is recursion per character. Sketch: count with a map (wrong for this problem) — mention only to reject it. ```java public String compressWrongMap(String s) { Map freq = new LinkedHashMap<>(); for (char c : s.toCharArray()) freq.merge(c, 1, Integer::sum); // WRONG: aaabaaa → a6b1 return ""; } ``` **Optimal** ```java public String compressWrap9(String s) { if (s == null || s.isEmpty()) return ""; StringBuilder sb = new StringBuilder(); int i = 0; int n = s.length(); while (i < n) { char ch = s.charAt(i); int j = i; while (j < n && s.charAt(j) == ch) j++; int count = j - i; while (count > 0) { int chunk = Math.min(count, 9); sb.append(ch); if (chunk > 1) sb.append(chunk); count -= chunk; } i = j; } return sb.toString(); } ``` If they want **always** write the digit even for 1, drop `if (chunk > 1)`. Ask. Wrap-at-9 still splits 10 → `a9a1` or `a9a`. Dry run `aaabaaa`: | i | run | emit | sb | | ---: | --- | --- | --- | | 0 | `aaa` (3) | `a3` | `a3` | | 3 | `b` (1) | `b` | `a3b` | | 4 | `aaa` (3) | `a3` | `a3ba3` | Dry run wrap `aaaaaaaaaaa` (11 a’s): | remaining | chunk | emit | | ---: | ---: | --- | | 11 | 9 | `a9` | | 2 | 2 | `a2` | Result `a9a2`. TC `O(n)`. SC `O(n)` for the builder (`O(1)` extra if in-place `char[]` with two pointers — tighter to code). Follow-ups: wrap-at-9 (this IE); in-place; digits in the input. **If you get stuck in Live Code** - First emit `letter + count` with no cap; then split `count` with `while (count > 9)`. - If output looks like `a3b3`, you grouped by char not by run — restart with `i,j` pointers. --- ### beautiful nodes adj-matrix — our R2 — UTA — https://leetcode.com/discuss/post/6653463/amazon-software-dev-engineer-1-universit-dtk5/ **What they actually asked** Same LC 6653463 R2: **beautiful nodes** given an **adjacency matrix**. No LC id named. Typical Live Code: graph is `n×n` 0/1 matrix; a node is beautiful if its **neighbors satisfy a predicate** (ask them). Do not invent an LC id. **Clarify out loud** 1. Undirected (`adj[i][j]==adj[j][i]`) or directed? 2. Node values `values[i]`, or beauty is purely structural (degree, isolated)? 3. Predicate: every neighbor has **strictly greater value** (local min)? local max? even degree? 4. Isolated nodes beautiful (vacuous `forall`)? 5. Return indices, count, or the node values? 6. Self-loops `adj[i][i]`? **Trick / pattern in one sentence** Treat each row `i` as the neighbor list; scan `j` where `adj[i][j]==1` and test the predicate — this is a graph, not a matrix-DP problem. **Why this data structure** - brute = optimal for `O(n²)` matrix: the matrix **is** the graph - convert to adj list only if they then want BFS/DFS multi-hop beauty - refuse: assuming a tree parent array; refuse stamping “Good Nodes in Binary Tree” **Brute / Optimal** Same `O(n²)` scan. Below: node `i` is beautiful iff **every neighbor** `j` has `values[j] > values[i]` (local minimum). Isolated → beautiful (say this). If they wanted local max, flip the comparison. ```java public List beautifulNodes(int[][] adj, int[] values) { int n = adj.length; List result = new ArrayList<>(); for (int i = 0; i < n; i++) { boolean beautiful = true; for (int j = 0; j < n; j++) { if (i == j) continue; if (adj[i][j] == 0) continue; if (values[j] <= values[i]) { beautiful = false; break; } } if (beautiful) result.add(i); } return result; } public int countBeautifulNodes(int[][] adj, int[] values) { return beautifulNodes(adj, values).size(); } ``` If beauty needs a **2-hop** predicate (“all nodes at distance 1 and 2 …”), BFS from each `i` with `O(n²)` total still OK for small n: ```java private List neighbors(int[][] adj, int i) { List ns = new ArrayList<>(); for (int j = 0; j < adj.length; j++) { if (i != j && adj[i][j] == 1) ns.add(j); } return ns; } ``` Dry run — undirected, values `[3, 1, 4, 2]`: ``` adj = 0 1 0 0 1 0 1 1 0 1 0 0 0 1 0 0 ``` | i | neighbors | values test | beautiful? | | ---: | --- | --- | --- | | 0 | 1 | 1 > 3? no | no | | 1 | 0,2,3 | 3,4,2 all > 1? yes | **yes** | | 2 | 1 | 1 > 4? no | no | | 3 | 1 | 1 > 2? no | no | Answer `[1]`. TC `O(n²)`. SC `O(1)` extra besides the answer list. Follow-ups: directed edges; “beautiful if degree even”; count connected components of beautiful nodes. **If you get stuck in Live Code** - Print row `i` and check the predicate by hand for n=4, then loop it. - If they add values later, keep the neighbor scan and only change the `if`. --- ### easy hashmap / maps UNNAMED — our R2 — UTA — https://medium.com/@sshiwangi770/my-amazon-interview-experience-1ab2fd4f9e6f **What they actually asked** Shiwangi Medium, UTA named: R2 **16 Dec 2024** — **easy hashmap / maps**, title **UNNAMED**. (R1 was Currency Converter graph; R3 bookstore OOD — not this card.) Do not guess Two Sum / Group Anagrams as the asked id. **Clarify out loud** 1. Key type (string, int, pair)? 2. Frequency, grouping, or first-seen index? 3. Streaming vs full array in memory? 4. Return the map or a derived answer? **Trick / pattern in one sentence** Easy map round: one `HashMap` pass for count / index / grouping; second pass to build the answer. **Why this data structure** `HashMap` for average O(1) lookup. Refuse `TreeMap` unless they asked sorted keys. Refuse nested loops O(n²) if n is large, but for “easy” n it may be the brute they want first. **Pattern card** - Freq: `map.merge(x, 1, Integer::sum)` then scan for max / unique / k-freq. - First unique: freq then left-to-right first with count 1. - Group: `map.computeIfAbsent(key, k -> new ArrayList<>()).add(item)`. - Two-sum family: `value → index` while scanning. **If you get stuck in Live Code** - Write the freq map and a linear scan; that is usually the full easy solution. - If keys are pairs, `Map>` or a packed `long` key. --- ### unnamed System Design rest of hour (after 15–20 min LP) — our R2 — AUTA — https://www.linkedin.com/posts/arijit-char_my-amazon-sde-1-auta-interview-experience-activity-7366548692872433664-Fw-c **What they actually asked** Arijit Char AUTA: Tech 2 **26 Aug 2024** — **15–20 min LP UNNAMED**, then **one unnamed System Design** for the rest of the hour (unexpected for AUTA fresher). **Not** two-DSA. CampusToCareer’s “APIs, databases, caching layers” for Job 10454435 is **Class C invention**, not this IE — do not recite lockers/caches as “what they asked.” **Clarify out loud (questions to ASK, not a fake design)** 1. What is the **core entity** (user? order? document? device?)? 2. Who are the actors and the one **happy-path action**? 3. Scale they care about (QPS, data size, read vs write) — **ask**, do not invent millions? 4. Single host in-memory OK for SDE I, or do they want multiple services? 5. What APIs would they like named (list as proposals, wait for nod)? 6. Consistency: stale reads OK? **Trick / pattern in one sentence** SDE I unnamed SD: pick entities from **their** answers, sketch 4–6 Java classes and 3 APIs, mention one scaling bottleneck only if they ask — do not dump a cache/locker template. **Talk-track (OOD, not DSA brute/optimal)** 1. Restate the prompt in one sentence; if vague, offer two interpretations and let them pick. 2. Board: actors → use cases → objects. Example skeleton **after they name a domain**: ```java // Names below are placeholders you fill from THEIR entity, not a claimed Amazon locker design. interface FooService { FooId create(CreateFooRequest req); Foo get(FooId id); void update(FooId id, UpdateFooRequest req); } final class InMemoryFooService implements FooService { private final Map store = new ConcurrentHashMap<>(); // single-machine default for 40 min; "what breaks at 10× traffic?" if they ask scale } final class Foo { final FooId id; FooState state; Instant updatedAt; } ``` 3. SOLID in one breath: service depends on a store **interface** (D); new store without rewriting APIs (O); one class one reason (S). 4. If they say “scale it”: ask **which** number grew — then consider partitioning **that** entity, not a generic Redis slide. 5. Timebox: APIs + object model first; persistence second; “cache” only as a follow-up question (“is stale OK for get?”), not as the design. **If you get stuck in Live Code / on the call** - Draw 3 boxes (Client → Service → Store) and name methods; ask them to pick the next constraint. - Do not pivot to Amazon Locker / Rate Limiter unless they named it (those are other IEs). --- ### Min Cost Connect Ropes — our R2 — AUTA APAC 2026 same-day — https://leetcode.com/discuss/post/8362604/amazon-sde-1-interview-experience-auta-a-5wmt/ **What they actually asked** LC 8362604 AUTA APAC India 2026 (R1+R2 **same day 27 Mar 2026**): **Minimum Cost to Connect Ropes**. Reprints: 8362603 / 8361451 / 8361452. Also GFG Off-Campus 2025 **our R2** (that loop numbered OA as R1 — Connect Sticks on their R3). HM of 8362604 had **Combine Garlands** (ropes concept) — same heap idea, overflow → `long`. **Clarify out loud** 1. Cost of connecting `a,b` is `a+b`, put `a+b` back into the pile? 2. Minimize **sum of those costs** (not the final rope length)? 3. n=1 → cost 0? 4. Values fit in `int` or need `long` (HM overflow note)? 5. Always combine **two** smallest? **Trick / pattern in one sentence** Always combine the two currently shortest ropes — **min-heap**; greedy is optimal because larger partial sums would be re-added more expensively. **Why this data structure** - brute: try all binary parenthesizations / permutations of merge order — factorial - optimal: `PriorityQueue` min-heap - refuse: sort once and scan adjacent pairs only (wrong: new rope must re-enter the order) **Brute** ```java public int connectRopesBrute(int[] ropes) { return dfs(new ArrayList() {{ for (int r : ropes) add(r); }}); } private int dfs(List cur) { if (cur.size() <= 1) return 0; int best = Integer.MAX_VALUE; for (int i = 0; i < cur.size(); i++) { for (int j = i + 1; j < cur.size(); j++) { List next = new ArrayList<>(cur); int a = next.remove(j); int b = next.remove(i); int cost = a + b; next.add(cost); best = Math.min(best, cost + dfs(next)); } } return best; } ``` TC exponential. SC `O(n)` recursion. **Optimal** ```java public long minCostConnectRopes(int[] ropes) { PriorityQueue minHeap = new PriorityQueue<>(); for (int rope : ropes) minHeap.add((long) rope); long totalCost = 0; while (minHeap.size() > 1) { long a = minHeap.poll(); long b = minHeap.poll(); long merged = a + b; totalCost += merged; minHeap.add(merged); } return totalCost; } ``` Dry run `[4, 3, 2, 6]`: | heap | poll | merge cost | total | | --- | --- | ---: | ---: | | 2,3,4,6 | 2+3 | 5 | 5 | | 4,5,6 | 4+5 | 9 | 14 | | 6,9 | 6+9 | 15 | **29** | TC `O(n log n)`. SC `O(n)`. Follow-ups: Combine Garlands (same); `long`; prove greedy (Huffman / adjacent always-two-smallest). **If you get stuck in Live Code** - Sort, merge first two, insert back with `ArrayList` + sort each time (`O(n² log n)`). - If cost is “final length only,” you over-counted — re-read: sum of **intermediate** merges. --- ### divide students into 2 groups so enemies not same group (bipartite) — our R2 — AUTA APAC 2026 same-day — https://leetcode.com/discuss/post/8362604/amazon-sde-1-interview-experience-auta-a-5wmt/ **What they actually asked** Same 8362604 R2: divide students into **2 groups** so **enemies are not in the same group**. Graph coloring / bipartite. Candidate first said coloring `O(V×E)`, corrected to **`O(V+E)`**. Reprints 8362603/8361451/8361452. **Clarify out loud** 1. `n` students `1..n`, enemy list as pairs? 2. Undirected enmity (if A enemies B then B enemies A)? 3. Students with no enemies can go either group? 4. Return boolean, or the two groups? 5. Disconnected graph (color each component)? 6. Self-enemy / duplicate edges? **Trick / pattern in one sentence** Enemies = edges; groups = 2 colors; the assignment exists iff the graph is **bipartite** (BFS/DFS coloring, no odd cycle). **Why this data structure** - brute: assign each student 2 ways, `O(2^n)` check edges - optimal: **adj list** + `color[]` + BFS queue (or DFS) - refuse: Union-Find without the “split into 2 sets” gadget unless you know bipartite UF; refuse O(V×E) nested scans as the final complexity **Brute** ```java public boolean canDivideBrute(int n, int[][] enemies) { int[] group = new int[n + 1]; return assign(1, n, enemies, group); } private boolean assign(int i, int n, int[][] enemies, int[] group) { if (i > n) return valid(enemies, group); group[i] = 0; if (assign(i + 1, n, enemies, group)) return true; group[i] = 1; return assign(i + 1, n, enemies, group); } ``` TC `O(2^n * E)`. SC `O(n)`. **Optimal** ```java public boolean canDivide(int n, int[][] enemies) { List> adj = new ArrayList<>(); for (int i = 0; i <= n; i++) adj.add(new ArrayList<>()); for (int[] e : enemies) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); } int[] color = new int[n + 1]; // 0 uncolored, 1 / 2 groups Arrays.fill(color, 0); for (int s = 1; s <= n; s++) { if (color[s] != 0) continue; Queue queue = new ArrayDeque<>(); color[s] = 1; queue.add(s); while (!queue.isEmpty()) { int u = queue.poll(); for (int v : adj.get(u)) { if (color[v] == 0) { color[v] = 3 - color[u]; queue.add(v); } else if (color[v] == color[u]) { return false; } } } } return true; } ``` Dry run `n=4`, enemies `(1,2),(2,3),(4,4)` wait — no self. Enemies `(1,2),(2,3)`: | start | color | note | | --- | --- | --- | | 1 | 1 | | | 2 | 2 | enemy of 1 | | 3 | 1 | enemy of 2 | | 4 | 1 | new component | No conflict. If add `(1,3)`: 1 and 3 both color 1 → **false** (odd cycle 1-2-3-1). TC `O(V+E)`. SC `O(V+E)`. Follow-ups: output the two groups from `color[]`; odd-cycle explanation; complexity correction O(V+E) not O(V×E). **If you get stuck in Live Code** - DFS coloring instead of BFS (same `color[v]==color[u]` check). - If disconnected, loop `for s in 1..n` — missing that is the usual bug. --- ### logger system LLD (SOLID, patterns) — our R2 same-day AUTA — https://old.reddit.com/r/LeetcodeDesi/comments/1ueybmg/amazon_sde1_auta_india_interview_experience_offer/ **What they actually asked** Reddit 1ueybmg AUTA India 2025 passout, R1+R2 **same day** Bangalore: R2 **logger system LLD** with **SOLID** and **patterns**. Reprint reddlx / amazonsdeprep `1ueybwz`. R1 greedy/tree/puzzle UNNAMED (not this card). **Clarify out loud** 1. Levels (DEBUG/INFO/WARN/ERROR) and a min-level filter? 2. Destinations: console, file, more later? 3. Format: timestamp, thread, message? 4. Sync vs async? single-threaded OK for 40 min? 5. Multiple loggers vs one facade? **Trick / pattern in one sentence** Logger **facade** + **Strategy** appenders + optional **Decorator** formatters — open to new outputs without editing the logger (OCP). **SOLID mapping** - **S:** `Logger` does not know files; `FileAppender` does not filter levels if `LevelFilter` exists - **O:** new `HttpAppender` implements `LogAppender` - **L:** any `LogAppender` is substitutable - **I:** do not force `close()` on a console appender via a fat interface — `CloseableAppender` extends if needed - **D:** `Logger` depends on `LogAppender`, not `FileWriter` Patterns: Strategy (appender), Decorator (json/timestamp), Composite (fan-out), Factory (assemble). **Optional** Singleton — mention testability cost; prefer DI. ```java enum LogLevel { DEBUG(10), INFO(20), WARN(30), ERROR(40); final int severity; LogLevel(int severity) { this.severity = severity; } } interface LogAppender { void append(LogLevel level, String message); } interface LogFormatter { String format(LogLevel level, String message); } final class TimestampFormatter implements LogFormatter { public String format(LogLevel level, String message) { return Instant.now() + " " + level + " " + message; } } final class ConsoleAppender implements LogAppender { private final LogFormatter formatter; ConsoleAppender(LogFormatter formatter) { this.formatter = formatter; } public void append(LogLevel level, String message) { System.out.println(formatter.format(level, message)); } } final class CompositeAppender implements LogAppender { private final List children; CompositeAppender(List children) { this.children = children; } public void append(LogLevel level, String message) { for (LogAppender child : children) child.append(level, message); } } final class Logger { private final LogLevel minLevel; private final LogAppender appender; Logger(LogLevel minLevel, LogAppender appender) { this.minLevel = minLevel; this.appender = appender; } public void log(LogLevel level, String message) { if (level.severity < minLevel.severity) return; appender.append(level, message); } public void info(String message) { log(LogLevel.INFO, message); } public void error(String message) { log(LogLevel.ERROR, message); } } final class LoggerFactory { static Logger consoleInfo() { return new Logger(LogLevel.INFO, new ConsoleAppender(new TimestampFormatter())); } } ``` Follow-ups: async queue + worker (Producer-Consumer); file rotation (new class, do not edit `Logger`); MDC / request id via decorator. **If you get stuck** - One `Logger` class with `if (file) write else print` — then extract `LogAppender` to recover OCP. - Skip Singleton unless they insist. --- ### Dog check-in / check-out LLD — our R2 — AUTA — https://www.linkedin.com/posts/nisarg-patel-80361a184_amazon-auta-interviewexperience-activity-7361081215673585664-ZGfa **What they actually asked** Nisarg Patel AUTA, **31 Jul 2025** same-day 10:00 / 12:30 / 15:00 Pacific: R2 **LP + LLD dog check-in/out tracking**. Location India not stated. (R1 was long-string sum + k-page sequence — not this card.) **Clarify out loud** 1. One facility, capacity of kennels? 2. Check-in/out by `dogId` + timestamp? 3. Same dog re-enter allowed after checkout? 4. Query: currently boarded, history, duration, owner’s dogs? 5. Concurrent check-in (say single-threaded first)? 6. Double check-in without checkout → error? **Trick / pattern in one sentence** Active stays in a `Map`; history is an append-only list; check-in/out are state transitions, not a graph algorithm. ```java final class Dog { final String dogId; final String name; final String ownerId; Dog(String dogId, String name, String ownerId) { this.dogId = dogId; this.name = name; this.ownerId = ownerId; } } final class Stay { final String dogId; final Instant checkIn; Instant checkOut; Stay(String dogId, Instant checkIn) { this.dogId = dogId; this.checkIn = checkIn; } boolean isActive() { return checkOut == null; } Duration duration(Instant now) { Instant end = checkOut == null ? now : checkOut; return Duration.between(checkIn, end); } } final class Daycare { private final int capacity; private final Map dogs = new HashMap<>(); private final Map active = new HashMap<>(); private final List history = new ArrayList<>(); Daycare(int capacity) { this.capacity = capacity; } public void register(Dog dog) { dogs.put(dog.dogId, dog); } public void checkIn(String dogId, Instant at) { if (!dogs.containsKey(dogId)) throw new IllegalArgumentException("unknown dog"); if (active.containsKey(dogId)) throw new IllegalStateException("already boarded"); if (active.size() >= capacity) throw new IllegalStateException("full"); active.put(dogId, new Stay(dogId, at)); } public void checkOut(String dogId, Instant at) { Stay stay = active.remove(dogId); if (stay == null) throw new IllegalStateException("not boarded"); stay.checkOut = at; history.add(stay); } public boolean isBoarded(String dogId) { return active.containsKey(dogId); } public List currentlyBoarded() { return new ArrayList<>(active.keySet()); } } ``` SOLID: `Daycare` ≠ `Dog`; capacity policy can become `CapacityPolicy` later (OCP). Pattern: like parking-lot tickets, not a strategy zoo. Follow-ups: waitlist; owner billing from `history`; thread-safety `synchronized` / concurrent maps. **If you get stuck** - Two hash maps: `dogId → checkInTime` and a list of completed pairs. - Do not design a social network for dogs unless they ask. --- ### n×n grid paths/rewards (traps -1 / 0; right/down; follow-up max reward) — our R2 — AUTA — OA-as-R1 remapped — https://leetcode.com/discuss/post/6800853/amazon-interview-experience-sde1-by-anon-vdbd/ **What they actually asked** LC 6800853 AUTA. Flag **OA-as-R1**: their R3 = **our R2**. n×n grid, cells **traps -1 / 0**, moves **right/down**, count paths; **follow-up max reward**. Days between lives not stated. Their R2 (our R1) was encoded-string / k-th-from-range — not this card. **Clarify out loud** 1. Start `(0,0)` to `(n-1,n-1)`, only right and down? 2. `-1` blocked, `0` free for the **count** version? 3. Start/end can be traps → 0 paths? 4. Follow-up: cells hold rewards (replace 0s?); maximize sum, still skip `-1`? 5. Unreachable → 0 or `-1`? 6. Mod for path count? **Trick / pattern in one sentence** DAG of only right/down → **2D DP**: paths add from up+left; max reward takes `max` of up/left plus cell. **Why this data structure** - brute: DFS all paths - optimal: `dp[r][c]` table (or 1D rolling) - refuse: Dijkstra (no left/up; unweighted count is not shortest-path); refuse 4-dir BFS unless they add more moves **Brute** ```java public int countPathsBrute(int[][] grid) { return dfs(grid, 0, 0); } private int dfs(int[][] grid, int r, int c) { int n = grid.length; if (r >= n || c >= n || grid[r][c] == -1) return 0; if (r == n - 1 && c == n - 1) return 1; return dfs(grid, r + 1, c) + dfs(grid, r, c + 1); } ``` TC exponential. SC `O(n)` recursion. **Optimal — count paths** ```java public int countPaths(int[][] grid) { int n = grid.length; if (grid[0][0] == -1 || grid[n - 1][n - 1] == -1) return 0; int[][] dp = new int[n][n]; dp[0][0] = 1; for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { if (grid[r][c] == -1) { dp[r][c] = 0; continue; } if (r == 0 && c == 0) continue; int fromUp = r > 0 ? dp[r - 1][c] : 0; int fromLeft = c > 0 ? dp[r][c - 1] : 0; dp[r][c] = fromUp + fromLeft; } } return dp[n - 1][n - 1]; } ``` **Follow-up — max reward** (non-trap cells hold a reward; `-1` still blocked). Unreachable = sentinel. ```java public int maxReward(int[][] grid) { int n = grid.length; int[][] dp = new int[n][n]; for (int[] row : dp) Arrays.fill(row, Integer.MIN_VALUE / 4); if (grid[0][0] == -1) return 0; dp[0][0] = grid[0][0]; for (int r = 0; r < n; r++) { for (int c = 0; c < n; c++) { if (grid[r][c] == -1) continue; if (r > 0 && dp[r - 1][c] > Integer.MIN_VALUE / 8) { dp[r][c] = Math.max(dp[r][c], dp[r - 1][c] + grid[r][c]); } if (c > 0 && dp[r][c - 1] > Integer.MIN_VALUE / 8) { dp[r][c] = Math.max(dp[r][c], dp[r][c - 1] + grid[r][c]); } } } return Math.max(0, dp[n - 1][n - 1]); // confirm unreachable policy } ``` Dry run count ``` 0 0 -1 0 -1 0 0 0 0 ``` | cell | dp | | --- | ---: | | (0,0) | 1 | | (0,1) | 1 | | (0,2) | 0 trap | | (1,0) | 1 | | (1,1) | 0 trap | | (2,0) | 1 | | (2,1) | 1 | | (2,2) | 1 | One path: down, down, right, right. TC `O(n²)`. SC `O(n²)` (`O(n)` rolling). Follow-ups: max reward (this IE); obstacles as 1 vs -1 naming; mod 10^9+7. **If you get stuck in Live Code** - Recursion + `memo[r][c]`. - For max, copy the count loops and switch `+` to `max`. --- ### min ops subtract a digit of n until 0 (27→5) — our R2 — AUTA — OA-as-R1 remapped — https://leetcode.com/discuss/post/6800853/amazon-interview-experience-sde1-by-anon-vdbd/ **What they actually asked** Same LC 6800853 their R3 / **our R2**: **minimum operations**: subtract **a digit of the current n** until 0. Sample **27 → 5**. Two LP UNNAMED in that hour. **Clarify out loud** 1. Each op: pick a digit that **appears in the current decimal representation**, subtract that digit from n? 2. Digit `0` allowed (no-op) — skip 0? 3. n up to? (`27` is tiny; if `n ≤ 10^6` DP on n is fine) 4. Return ops count only? **Trick / pattern in one sentence** From n you can go to `n-d` for each non-zero digit `d` of n; min ops is shortest path on `0..n` (DP) — and **greedy subtract max digit** matches the 27→5 sample. **Why this data structure** - brute: BFS from n to 0, each edge subtract a digit - optimal for small n: `int[] dp` or greedy max-digit if they accept it after you verify DP - refuse: subtracting `n`’s original digits only (digits **change** after each subtract) **Brute** ```java public int minOpsBfs(int n) { if (n == 0) return 0; Queue queue = new ArrayDeque<>(); boolean[] seen = new boolean[n + 1]; queue.add(n); seen[n] = true; int ops = 0; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { int cur = queue.poll(); if (cur == 0) return ops; for (int d : digits(cur)) { if (d == 0) continue; int next = cur - d; if (next >= 0 && !seen[next]) { seen[next] = true; queue.add(next); } } } ops++; } return -1; } private List digits(int x) { List ds = new ArrayList<>(); if (x == 0) ds.add(0); while (x > 0) { ds.add(x % 10); x /= 10; } return ds; } ``` TC `O(n log n)`-ish visits. SC `O(n)`. **Optimal — DP (safe) and greedy (sample)** ```java public int minOpsDp(int n) { int[] dp = new int[n + 1]; Arrays.fill(dp, Integer.MAX_VALUE / 4); dp[0] = 0; for (int x = 1; x <= n; x++) { int t = x; while (t > 0) { int d = t % 10; t /= 10; if (d > 0) dp[x] = Math.min(dp[x], dp[x - d] + 1); } } return dp[n]; } public int minOpsGreedyMaxDigit(int n) { int ops = 0; while (n > 0) { int maxDigit = 0; int t = n; while (t > 0) { maxDigit = Math.max(maxDigit, t % 10); t /= 10; } n -= maxDigit; ops++; } return ops; } ``` Dry run **27 → 5** (greedy max digit): | n | max digit | n after | ops | | ---: | ---: | ---: | ---: | | 27 | 7 | 20 | 1 | | 20 | 2 | 18 | 2 | | 18 | 8 | 10 | 3 | | 10 | 1 | 9 | 4 | | 9 | 9 | 0 | **5** | TC DP `O(n log n)`. SC `O(n)`. Greedy `O(ops * log n)` time, `O(1)` space — confirm against DP for a few n if they doubt greedy. Follow-ups: 27→5 sample; `long` n too big for `dp[n]` → greedy or digit-aware math; skip digit 0. **If you get stuck in Live Code** - Simulate greedy on 27 until 0, then write the while-loop. - If n is 10^12, do **not** allocate `dp[n]`; stay greedy or BFS is impossible. --- ### LL → height-balanced BST — our R2 — not UTA — snippet — https://www.linkedin.com/posts/deepak-gautam-a77b93222_amazon-sde-interviewexperience-activity-7485166684211671040-d-gv **What they actually asked** Deepak Gautam LinkedIn, **Jul 2026 next day** (closest **calendar** to 18 Aug 2026, **not named UTA**). Snippet reliability: **LL → height-balanced BST**. Also First Missing Positive (next card). Do not over-read the snippet. **Clarify out loud** 1. Is the linked list **already sorted** ascending? 2. Height-balanced = AVL-style `|lh-rh|≤1` for every node? 3. Unique values? 4. Singly list? 5. In-place list nodes vs new `TreeNode`s? **Trick / pattern in one sentence** If sorted: mid of the (sub)list becomes root (inorder = sorted order). If unsorted: copy to array, **sort**, then same mid-build (ask before sorting). **Why this data structure** - brute: put values in `ArrayList`, sort if needed, naive “insert into BST” without balancing — can skew - optimal: `ArrayList` + recursive mid; or slow/fast mid on the list without extra array - refuse: random inserts; refuse claiming an LC id the snippet did not name **Brute** ```java public TreeNode sortedListToBstBrute(ListNode head) { List vals = new ArrayList<>(); for (ListNode p = head; p != null; p = p.next) vals.add(p.val); TreeNode root = null; for (int v : vals) root = insertBst(root, v); // NOT height-balanced return root; } ``` **Optimal (sorted list — mid as root)** ```java public TreeNode sortedListToBST(ListNode head) { List vals = new ArrayList<>(); for (ListNode p = head; p != null; p = p.next) vals.add(p.val); return build(vals, 0, vals.size() - 1); } private TreeNode build(List vals, int lo, int hi) { if (lo > hi) return null; int mid = lo + (hi - lo) / 2; TreeNode root = new TreeNode(vals.get(mid)); root.left = build(vals, lo, mid - 1); root.right = build(vals, mid + 1, hi); return root; } /** O(1) extra besides tree: slow/fast mid, break list */ public TreeNode sortedListToBSTInPlace(ListNode head) { if (head == null) return null; if (head.next == null) return new TreeNode(head.val); ListNode prev = null, slow = head, fast = head; while (fast != null && fast.next != null) { prev = slow; slow = slow.next; fast = fast.next.next; } prev.next = null; TreeNode root = new TreeNode(slow.val); root.left = sortedListToBSTInPlace(head); root.right = sortedListToBSTInPlace(slow.next); return root; } ``` Dry run list `1→2→3→4→5`: | lo,hi | mid val | left range | right range | | --- | ---: | --- | --- | | 0,4 | 3 | 1,2 | 4,5 | | 0,1 | 1 | empty | 2 | | 3,4 | 4 | empty | 5 | Tree: ``` 3 / \ 1 4 \ \ 2 5 ``` Height-balanced. TC `O(n)` with array; in-place `O(n log n)` from repeated scans. SC `O(n)` array + `O(log n)` recursion. Follow-ups: unsorted list (sort first — `n log n`); doubly linked; prove height `O(log n)`. **If you get stuck in Live Code** - Dump to `ArrayList` and `build(lo,hi)` — clearest. - If they say unsorted, sort the array and say that out loud. --- ### First Missing Positive — our R2 — not UTA — snippet — https://www.linkedin.com/posts/deepak-gautam-a77b93222_amazon-sde-interviewexperience-activity-7485166684211671040-d-gv **What they actually asked** Same Deepak Jul 2026 snippet R2: **First Missing Positive**. Snippet reliability. Not named UTA. **Clarify out loud** 1. Unsorted `int[]`, find smallest **missing positive** (`1,2,3,…`)? 2. In-place `O(1)` extra, `O(n)` time? 3. Negatives and zeros present? 4. Duplicates? 5. If `1..n` all present → return `n+1`? **Trick / pattern in one sentence** The answer is in `1..n+1`; place each value `x` at index `x-1` (cycle swap), then the first index whose value is not `i+1` is the answer. **Why this data structure** - brute: `HashSet` of nums, scan `1,2,3,…` - optimal: the **array itself** as a set of presence (index as key) - refuse: sorting if they want O(n) (`O(n log n)` is the fallback); refuse a boolean `[n+2]` if they want O(1) extra **Brute** ```java public int firstMissingPositiveBrute(int[] nums) { Set seen = new HashSet<>(); for (int x : nums) if (x > 0) seen.add(x); int missing = 1; while (seen.contains(missing)) missing++; return missing; } ``` TC `O(n)`. SC `O(n)`. **Optimal** ```java public int firstMissingPositive(int[] nums) { int n = nums.length; for (int i = 0; i < n; i++) { while (nums[i] >= 1 && nums[i] <= n && nums[nums[i] - 1] != nums[i]) { int dest = nums[i] - 1; int tmp = nums[i]; nums[i] = nums[dest]; nums[dest] = tmp; } } for (int i = 0; i < n; i++) { if (nums[i] != i + 1) return i + 1; } return n + 1; } ``` Dry run `nums = [3, 4, -1, 1]`: | i | action | array | | ---: | --- | --- | | 0 | swap 3 with index 2 | `[-1, 4, 3, 1]` | | 0 | `-1` stop | | | 1 | swap 4 with index 3 | `[-1, 1, 3, 4]` | | 1 | swap 1 with index 0 | `[1, -1, 3, 4]` | | 2–3 | already 3,4 | | | scan | index 1 is not 2 | **2** | TC `O(n)`. SC `O(1)` extra. Follow-ups: cannot mutate → HashSet; “similar to cyclic sort” (other IEs, not this snippet). **If you get stuck in Live Code** - HashSet brute is correct; then try to reuse indices `1..n`. - If infinite swap, you forgot `nums[dest] != nums[i]` (duplicates). --- ## 2. DSA answer cards (named FTE from bible §5.A) Notes for Adarsh. Java is canonical. These are answers to questions **other** India SDE I / UTA / AUTA candidates reported in live rounds. Your loop may differ. Unnamed stays unnamed. No invented Job **10454435** list. OA is not a round. Intern cards live in another fragment. **This fragment skips A-1’s 18 Aug priority pack:** Sum of Subarray Minimums similar; max-1s row matrix; Koko-like; equal-split tree; Rotate Image; Next Perm similar; Rotten oranges; Distance K no parent; Merge k sorted linked lists; Word Ladder; Count Beautiful Splits; string compression wrap-at-9; beautiful nodes adj-matrix; Connect Ropes/Sticks; bipartite students; grid paths/rewards; subtract-digit; LL→BST; First Missing Positive; unnamed A2/A5/A13. **Group map:** heap/stream → graph → tree (Daily Temperatures is **stack**, filed next to Naina’s R1 tree slot) → DP → binary search → sliding window/string/hash → linked list/array → unnamed §5.B → older GFG. **Matrix:** Number of Islands (graph) + Maximum Rectangle (DP) + Prince right/diag path (DP). **Stack/greedy:** Daily Temperatures, Asteroid Collision, Next Greater, Remove K Digits, Next permutation, Min Arrows, min platforms. Heaters is **BS**, filed with 7035289’s tree pair. **Shared Live-Code types** (declare once if the editor is blank): ```java class ListNode { int val; ListNode next; ListNode(int v) { val = v; } ListNode(int v, ListNode n) { val = v; next = n; } } class TreeNode { int val; TreeNode left, right; TreeNode(int v) { val = v; } } class GraphNode { int val; List neighbors = new ArrayList<>(); GraphNode(int v) { val = v; } } ``` --- ### Heap / stream ### Median of Data Stream — mapped R1 (also 6475219 R1) — AUTA Y (8362604) — [LC 8362604](https://leetcode.com/discuss/post/8362604/amazon-sde-1-interview-experience-auta-a-5wmt/) **What they actually asked:** Find median from a stream (named). AUTA APAC India 2026, same-day R1 with Number of Islands. Reprint: [LC 6475219](https://leetcode.com/discuss/post/6475219/amazon-sde-1-interview-experience-bangal-4aa6/) Bangalore R1 “Find Median from stream”. **Clarify out loud** - Integer vs float median when even count? - `addNum` then `findMedian`, or batch? - Duplicates allowed? (yes) - Count fit in memory? (yes for Live Code) - Need remove / sliding-window median? (only if they ask) **Trick / pattern in one sentence:** Two heaps — max-heap of the lower half, min-heap of the upper half — so the median is always at a heap top. **Why this data structure** - brute DS: `ArrayList` + sort after every insert — too slow for a stream - optimal DS: `PriorityQueue` max-heap + min-heap, sizes differ by at most 1 - refuse: one sorted `TreeSet` of values — duplicates break uniqueness; a `TreeMap` of counts works but is slower to explain than two heaps **Brute** ```java class MedianFinderBrute { List a = new ArrayList<>(); void addNum(int num) { a.add(num); } double findMedian() { Collections.sort(a); int n = a.size(); if ((n & 1) == 1) return a.get(n / 2); return (a.get(n / 2 - 1) + a.get(n / 2)) / 2.0; } } ``` TC: `add` O(1), `findMedian` O(n log n). SC: O(n). Fails a long stream of inserts. **Optimal** 1. `lo` = max-heap (lower half). `hi` = min-heap (upper half). 2. Insert into `lo`, then move `lo.peek()` to `hi`. If `hi.size() > lo.size()`, move `hi.peek()` back to `lo`. 3. Odd count → median = `lo.peek()`. Even → average of both tops. ```java class MedianFinder { PriorityQueue lo = new PriorityQueue<>(Collections.reverseOrder()); PriorityQueue hi = new PriorityQueue<>(); void addNum(int num) { lo.offer(num); hi.offer(lo.poll()); if (hi.size() > lo.size()) lo.offer(hi.poll()); } double findMedian() { if (lo.size() > hi.size()) return lo.peek(); return (lo.peek() + hi.peek()) / 2.0; } } ``` **Dry run** `add` 1, 2, 3 | op | lo (max) | hi (min) | median | | --- | --- | --- | --- | | +1 | [1] | [] | 1 | | +2 | [1] | [2] | 1.5 | | +3 | [2,1] | [3] | 2 | TC: add O(log n), find O(1). SC: O(n). **Follow-ups they asked:** TC/SC out loud (8362604). 6475219 also asked max-sum BT level same round. **If you get stuck in Live Code** - Sort-on-query brute, then say “two heaps next.” - Insertion-sort into an `ArrayList` (O(n) add) if heap API is rusty. --- ### Top K Frequent Elements — mapped R1 — AUTA Y — [LC 7406809](https://leetcode.com/discuss/post/7406809/amazon-sde-1-auta-interview-experience-s-k6t7/) **What they actually asked:** Top K Frequent Elements (LC linked). AUTA Nov 2025 R1 with generate-all-subsets. Reprint angle: Sachin LinkedIn R1 Q2 “m most frequent elements” (no LC id for that Q2) — same pattern, do not invent an id. [Sachin](https://www.linkedin.com/posts/sachinchoudhary0_amazon-interview-experience-sde1-applied-activity-7465822262709886976-lgWi) **Clarify out loud** - If ties, any k or deterministic order? - k always valid? nums empty? - Need the elements or (element, count) pairs? - Stream vs static array? **Trick / pattern in one sentence:** Count with HashMap, then a size-k min-heap of frequencies — never full-sort unless n is tiny. **Why this data structure** - brute: sort all unique by count O(u log u) - optimal: HashMap + min-heap of size k, or bucket sort by count if values are ints - refuse: max-heap of everything — wastes work when k ≪ u **Brute** ```java int[] topKBrute(int[] nums, int k) { Map freq = new HashMap<>(); for (int x : nums) freq.merge(x, 1, Integer::sum); List pairs = new ArrayList<>(); for (var e : freq.entrySet()) pairs.add(new int[]{e.getKey(), e.getValue()}); pairs.sort((a, b) -> b[1] - a[1]); int[] ans = new int[k]; for (int i = 0; i < k; i++) ans[i] = pairs.get(i)[0]; return ans; } ``` TC: O(n + u log u). SC: O(u). **Optimal** ```java int[] topKFrequent(int[] nums, int k) { Map freq = new HashMap<>(); for (int x : nums) freq.merge(x, 1, Integer::sum); PriorityQueue pq = new PriorityQueue<>((a, b) -> a[1] - b[1]); // min count for (var e : freq.entrySet()) { pq.offer(new int[]{e.getKey(), e.getValue()}); if (pq.size() > k) pq.poll(); } int[] ans = new int[k]; for (int i = k - 1; i >= 0; i--) ans[i] = pq.poll()[0]; return ans; } ``` **Dry run** nums = `[1,1,1,2,2,3]`, k = 2 | num | freq map | heap (val,c) after unique | | --- | --- | --- | | done | 1→3, 2→2, 3→1 | keep (1,3),(2,2) after evicting (3,1) | TC: O(n + u log k). SC: O(u). Bucket O(n) if you list indices 0..n. **If you get stuck:** sort uniques by count; then “heap of size k.” --- ### Dynamic k-th largest (k changes) — mapped R3 — UTA N — [LC 7850431](https://leetcode.com/discuss/post/7850431/amazon-sde-1-interview-experience-by-imx-xitu/) **What they actually asked:** Dynamic k-th largest where **k changes** (snippet). Same loop as Cheapest Flights–like + power allocation (R1) and Connect Sticks + sum-0 (R2). GenAI slot also had this DSA. **Clarify out loud** - Operations: add only, or add/remove, and a separate `setK`? - k can grow larger than current size? - Duplicates? - Need exact k-th after every op? **Trick / pattern in one sentence:** Same two-heap / size-k min-heap as stream k-th largest, but when k grows you refill from a side structure of the rest. **Why this data structure** - brute: keep all numbers, sort after every query - optimal: min-heap of current “top k” plus a max-heap (or TreeMap) of the remainder so `setK` can move elements - refuse: re-sort from scratch if they want many updates **Brute** ```java class KthDynamicBrute { List a = new ArrayList<>(); int k; KthDynamicBrute(int k, int[] nums) { this.k = k; for (int x : nums) a.add(x); } void add(int val) { a.add(val); } void setK(int newK) { k = newK; } int kth() { List b = new ArrayList<>(a); Collections.sort(b, Collections.reverseOrder()); return b.get(k - 1); } } ``` TC: query O(n log n). Fails many updates. **Optimal** — min-heap of size k for the largest k; `TreeMap` (multiset) of the rest, largest of rest = `rest.lastKey()`. ```java class KthDynamic { int k; PriorityQueue top = new PriorityQueue<>(); // min of current k largest TreeMap rest = new TreeMap<>(); // remaining, sorted int restSize = 0; KthDynamic(int k, int[] nums) { this.k = k; for (int x : nums) add(x); } void inc(TreeMap m, int x) { m.merge(x, 1, Integer::sum); } void dec(TreeMap m, int x) { int c = m.get(x); if (c == 1) m.remove(x); else m.put(x, c - 1); } void add(int val) { top.offer(val); if (top.size() > k) { inc(rest, top.poll()); restSize++; } } void setK(int newK) { while (k < newK && restSize > 0) { // need a bigger top int x = rest.lastKey(); dec(rest, x); restSize--; top.offer(x); k++; } while (k > newK && !top.isEmpty()) { // shrink top inc(rest, top.poll()); restSize++; k--; } k = newK; } int kth() { return top.peek(); } } ``` **Dry run** nums = `[4,5,8,2]`, k = 3, then add 3, then setK(2) | after | top min-heap (size k) | kth | | --- | --- | --- | | init k=3 | [4,5,8] | 4 | | +3 | [4,5,8] (3 to rest) | 4 | | setK(2) | [5,8] | 5 | TC: add O(log n), setK amortized O(|Δk| log n), kth O(1). SC: O(n). **If you get stuck:** brute sort; then “size-k heap, rest in a sorted map for k changes.” --- ### Combine Garlands (ropes concept) — mapped R3 HM — AUTA Y — [LC 8362604](https://leetcode.com/discuss/post/8362604/amazon-sde-1-interview-experience-auta-a-5wmt/) **What they actually asked:** Minimum Cost to Combine Garlands (ropes concept); overflow → **long**. Same HM as Find-All-Anagrams variation. Connect Ropes/Sticks itself is **A-1** — do not duplicate that card. **Clarify / Trick:** Always combine the two cheapest; cost = sum; push back. Use `long`. Same Huffman / min-heap as Connect Ropes. **Why DS:** min-heap. Brute: rescan min two each time O(n²). **Optimal (cross-ref A-1 Connect Ropes; type `long`):** ```java long combineGarlands(int[] len) { PriorityQueue pq = new PriorityQueue<>(); for (int x : len) pq.offer((long) x); long cost = 0; while (pq.size() > 1) { long a = pq.poll(), b = pq.poll(); cost += a + b; pq.offer(a + b); } return cost; } ``` **Dry run** `[4, 3, 2, 6]`: 2+3=5 (cost 5), 4+5=9 (14), 6+9=15 (29). TC: O(n log n). SC: O(n). **Stuck:** say “same as Connect Sticks, watch `int` overflow.” --- ### Matrix Number of Islands (below, graph flood). max-1s row is **A-1**. Maximum Rectangle all 1s and Prince right/diag path are under DP. ### Graph ### Number of Islands — mapped R1 (8029194 R2 similar) — AUTA Y (8362604) + others — [LC 8362604](https://leetcode.com/discuss/post/8362604/amazon-sde-1-interview-experience-auta-a-5wmt/) **What they actually asked:** Number of Islands. Reprints: [8014509](https://leetcode.com/discuss/post/8014509/amazon-sde-1-interview-experience-by-pra-azvd/) R2; [8029194](https://leetcode.com/discuss/post/8029194/amazon-interview-sde-1-selected-by-anony-qatd/) R2 “similar to Number of Islands”; [6653845](https://leetcode.com/discuss/post/6653845/amazon-sde-1-auta-interview-missed-hr-ca-4jw3/) AUTA R1 only named DSA; Deepak Jul 2026 R1 with Min Arrows. **Clarify out loud** - 4-dir or 8-dir? - `'1'`/`'0'` chars vs ints? land value? - Mutate grid OK? - Empty grid / all water? **Trick / pattern in one sentence:** Each DFS/BFS flood from an unvisited land cell is one island; mark visited so you never double-count. **Why this data structure** - brute: nothing fancy — still DFS/BFS; “brute” is extra visited matrix + recursion without mutating - optimal: mutate grid to `'0'` (or a visited[][]) + DFS/BFS / Union-Find - refuse: Dijkstra / heap — this is unweighted connectivity **Brute** — extra visited, 4-dir DFS: ```java int numIslandsBrute(char[][] g) { int m = g.length, n = g[0].length, ans = 0; boolean[][] vis = new boolean[m][n]; for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (g[i][j] == '1' && !vis[i][j]) { ans++; dfs(g, vis, i, j); } return ans; } void dfs(char[][] g, boolean[][] vis, int i, int j) { if (i < 0 || j < 0 || i >= g.length || j >= g[0].length || vis[i][j] || g[i][j] != '1') return; vis[i][j] = true; dfs(g, vis, i + 1, j); dfs(g, vis, i - 1, j); dfs(g, vis, i, j + 1); dfs(g, vis, i, j - 1); } ``` TC: O(mn). SC: O(mn) visited + recursion. **Optimal** — sink island in-place (iterative BFS if they ban recursion): ```java int numIslands(char[][] g) { int m = g.length, n = g[0].length, ans = 0; int[] di = {1, -1, 0, 0}, dj = {0, 0, 1, -1}; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (g[i][j] != '1') continue; ans++; ArrayDeque q = new ArrayDeque<>(); g[i][j] = '0'; q.offer(new int[]{i, j}); while (!q.isEmpty()) { int[] p = q.poll(); for (int k = 0; k < 4; k++) { int ni = p[0] + di[k], nj = p[1] + dj[k]; if (ni < 0 || nj < 0 || ni >= m || nj >= n || g[ni][nj] != '1') continue; g[ni][nj] = '0'; q.offer(new int[]{ni, nj}); } } } } return ans; } ``` **Dry run** ``` 1 1 0 1 0 0 0 0 1 ``` First land (0,0) floods three 1s → island 1. (2,2) → island 2. Answer 2. TC: O(mn). SC: O(mn) queue worst-case, O(1) extra if recursive mutate. **Follow-ups:** max-area island; number of distinct islands; 8-dir. **If you get stuck:** nested loops + recursive flood; then BFS if stack overflow (Akash Path-Sum round probed recursion depth — same fear). --- ### Currency Converter (graph) — mapped R1 — UTA Y — [Shiwangi](https://medium.com/@sshiwangi770/my-amazon-interview-experience-1ab2fd4f9e6f) **What they actually asked:** Currency Converter graph. Candidate wrote “Link”; href **not** in the body — **do not invent an LC id**. Full I/O. UTA named, 2 Dec 2024. **Clarify out loud** - Quotes as `from, to, rate`? Bidirectional `1/rate`? - Query: amount in A → B? missing path → -1 / error? - Cycles / arbitrage? (usually ignore; just reachability × product) - Multiple hops? **Trick / pattern in one sentence:** Weighted graph of currencies; DFS/BFS multiply rates along a path; do not invent a LeetCode number. **Why this data structure** - brute: try all paths, explode on cycles - optimal: adj list `Map>`, visited set, DFS product (or Bellman-Ford on `-log(rate)` if they want best rate) - refuse: stamping “Evaluate Division LC 399” as *what they asked* — same family, they did not name it **Brute** — DFS all simple paths: ```java double dfsBrute(Map> g, String a, String b, double acc, Set vis) { if (a.equals(b)) return acc; vis.add(a); double ans = -1; for (String[] e : g.getOrDefault(a, List.of())) { if (vis.contains(e[0])) continue; double r = dfsBrute(g, e[0], b, acc * Double.parseDouble(e[1]), vis); if (r >= 0) { ans = r; break; } } vis.remove(a); return ans; } ``` TC: exponential in hops. SC: O(V). **Optimal** — first path is enough if rates are consistent (no need for shortest): ```java double convert(String[][] quotes, double amount, String from, String to) { Map> g = new HashMap<>(); for (String[] q : quotes) { g.computeIfAbsent(q[0], z -> new ArrayList<>()).add(new doubleEdge(q[1], Double.parseDouble(q[2]))); g.computeIfAbsent(q[1], z -> new ArrayList<>()).add(new doubleEdge(q[0], 1.0 / Double.parseDouble(q[2]))); } if (!g.containsKey(from) || !g.containsKey(to)) return -1; ArrayDeque dq = new ArrayDeque<>(); // node, prod Set vis = new HashSet<>(); dq.offer(new Object[]{from, 1.0}); vis.add(from); while (!dq.isEmpty()) { Object[] cur = dq.poll(); String u = (String) cur[0]; double p = (Double) cur[1]; if (u.equals(to)) return amount * p; for (doubleEdge e : g.getOrDefault(u, List.of())) { if (vis.add(e.to)) dq.offer(new Object[]{e.to, p * e.rate}); } } return -1; } class doubleEdge { String to; double rate; doubleEdge(String t, double r) { to = t; rate = r; } } ``` **Dry run** quotes USD→INR 83, INR→JPY 1.8, amount 2 USD → JPY: 2 × 83 × 1.8 = 298.8 | node | prod from USD | | --- | --- | | USD | 1 | | INR | 83 | | JPY | 149.4 | TC: O(V+E). SC: O(V+E). **If you get stuck:** draw 3 currencies on paper, multiply; then BFS. --- ### similar to Cheapest Flights Within K Stops — mapped R1 — UTA N — [LC 7850431](https://leetcode.com/discuss/post/7850431/amazon-sde-1-interview-experience-by-imx-xitu/) **What they actually asked:** similar to Cheapest Flights Within K Stops (snippet). **Similar-not-exact** — do not stamp a live “they asked LC 787.” **Clarify out loud** - K = stops or flights (edges = K+1)? - Directed? Negative weights? (no) - No path → -1? - City count n given? **Trick / pattern in one sentence:** Shortest path with a hop cap — Bellman-Ford for `K+1` relaxations, not plain Dijkstra (unless you put stops in the state). **Why this data structure** - brute: DFS all paths with hop ≤ K+1 - optimal: `dist[v]` relaxed K+1 times from a snapshot (Bellman-Ford), or PQ on `(cost, city, stops)` - refuse: unweighted BFS — edges have prices **Brute** ```java int dfs(List[] g, int u, int dst, int hopsLeft, int cost) { if (u == dst) return cost; if (hopsLeft < 0) return Integer.MAX_VALUE / 4; int best = Integer.MAX_VALUE / 4; for (int[] e : g[u]) best = Math.min(best, dfs(g, e[0], dst, hopsLeft - 1, cost + e[1])); return best; } ``` TC: exponential. Fails n ~ 100. **Optimal** — Bellman-Ford K+1 rounds: ```java int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { int INF = Integer.MAX_VALUE / 4; int[] dist = new int[n]; Arrays.fill(dist, INF); dist[src] = 0; for (int i = 0; i <= k; i++) { int[] nd = dist.clone(); for (int[] f : flights) { int u = f[0], v = f[1], w = f[2]; if (dist[u] < INF) nd[v] = Math.min(nd[v], dist[u] + w); } dist = nd; } return dist[dst] >= INF ? -1 : dist[dst]; } ``` **Dry run** n=3, flights `0→1 100`, `1→2 100`, `0→2 500`, src=0 dst=2 k=1 (one stop allowed): after 2 relaxations, path 0-1-2 costs 200 vs 500. | round | dist[0] | dist[1] | dist[2] | | --- | --- | --- | --- | | 0 | 0 | INF | INF | | 1 | 0 | 100 | 500 | | 2 (k=1) | 0 | 100 | 200 | TC: O(K · E). SC: O(n). **If you get stuck:** Dijkstra without K, then add `stops` to the PQ state. --- ### Detonate the Maximum Bombs — mapped R1 — UTA N — [LC 7724048](https://leetcode.com/discuss/post/7724048/amazon-sde-1-interview-experience-by-ano-t6fz/) **What they actually asked:** Detonate the Maximum Bombs (snippet). Same IE later R2 Aggressive Cows, R3 Next Greater. **Clarify out loud** - Bomb i detonates j if dist² ≤ r_i² (directed! radii differ) - Count bombs in the cascade from a start, maximize - n up to? (usually ≤ 100 → O(n³) OK) **Trick / pattern in one sentence:** Build a directed reachability graph (circle contains center), then DFS/BFS from each bomb. **Why this data structure** - brute: from each start, simulate with a queue, recompute distances every time - optimal: precompute adj[i] = bombs i can directly set off; then n DFS - refuse: undirected union-find — A can trigger B but not vice versa **Brute** — no precomputed graph, O(n²) per start: ```java int maximumDetonationBrute(int[][] bombs) { int n = bombs.length, best = 0; for (int s = 0; s < n; s++) { boolean[] vis = new boolean[n]; ArrayDeque q = new ArrayDeque<>(); vis[s] = true; q.offer(s); int c = 0; while (!q.isEmpty()) { int i = q.poll(); c++; long x = bombs[i][0], y = bombs[i][1], r = bombs[i][2]; for (int j = 0; j < n; j++) if (!vis[j]) { long dx = x - bombs[j][0], dy = y - bombs[j][1]; if (dx * dx + dy * dy <= r * r) { vis[j] = true; q.offer(j); } } } best = Math.max(best, c); } return best; } ``` TC: O(n³). SC: O(n). Fine if n≤100. **Optimal** — same complexity, cleaner graph: ```java int maximumDetonation(int[][] bombs) { int n = bombs.length; List[] g = new List[n]; for (int i = 0; i < n; i++) g[i] = new ArrayList<>(); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (i != j) { long dx = (long) bombs[i][0] - bombs[j][0]; long dy = (long) bombs[i][1] - bombs[j][1]; long r = bombs[i][2]; if (dx * dx + dy * dy <= r * r) g[i].add(j); } int best = 0; for (int s = 0; s < n; s++) { boolean[] vis = new boolean[n]; ArrayDeque q = new ArrayDeque<>(); vis[s] = true; q.offer(s); int c = 0; while (!q.isEmpty()) { int u = q.poll(); c++; for (int v : g[u]) if (!vis[v]) { vis[v] = true; q.offer(v); } } best = Math.max(best, c); } return best; } ``` **Dry run** bombs `(0,0,r=2)`, `(1,1,r=1)`, `(4,0,r=1)`: bomb 0 reaches 1 (dist√2≤2), not 2. Start 0 → 2 bombs. Start 2 → 1. TC: O(n³). SC: O(n²). Use `long` for dist². **If you get stuck:** “directed graph of who ignites whom, BFS from each.” --- ### similar to Open the Lock — mapped R1 — UTA N — [LC 7623949](https://leetcode.com/discuss/post/7623949/amazon-sde-1-application-interview-exper-92xt/) **What they actually asked:** similar to Open the Lock (snippet). Same IE: GenAI Fluency slot was Distance K DSA (A-1). **Similar-not-exact.** **Clarify out loud** - 4 wheels 0000→target? deadends? - Wrap 9↔0? - Moves = +1/−1 per wheel? **Trick / pattern in one sentence:** Unweighted graph of 10000 codes; BFS from `0000`; skip deadends. **Why this data structure** - brute: DFS / recursion on 4 wheels - optimal: BFS + `Set` visited/dead - refuse: Dijkstra — every turn costs 1 **Brute** — DFS with depth cap, can TLE / miss shortest. ```java int dfs(char[] cur, String target, Set dead, Set vis, int depth, int cap) { String s = new String(cur); if (s.equals(target)) return depth; if (depth == cap || dead.contains(s)) return Integer.MAX_VALUE / 4; int best = Integer.MAX_VALUE / 4; for (int i = 0; i < 4; i++) { char orig = cur[i]; for (int d : new int[]{1, -1}) { cur[i] = (char) ('0' + (orig - '0' + d + 10) % 10); String ns = new String(cur); if (vis.add(ns)) best = Math.min(best, dfs(cur, target, dead, vis, depth + 1, cap)); cur[i] = orig; } } return best; } ``` **Optimal** ```java int openLock(String[] deadends, String target) { Set dead = new HashSet<>(Arrays.asList(deadends)); if (dead.contains("0000")) return -1; ArrayDeque q = new ArrayDeque<>(); Set vis = new HashSet<>(); q.offer("0000"); vis.add("0000"); int steps = 0; while (!q.isEmpty()) { for (int sz = q.size(); sz > 0; sz--) { String u = q.poll(); if (u.equals(target)) return steps; char[] c = u.toCharArray(); for (int i = 0; i < 4; i++) { char orig = c[i]; for (int d : new int[]{1, -1}) { c[i] = (char) ('0' + (orig - '0' + d + 10) % 10); String v = new String(c); if (!dead.contains(v) && vis.add(v)) q.offer(v); c[i] = orig; } } } steps++; } return -1; } ``` **Dry run** target `0202`, no dead: 0000 → 1000/9000/0100/… BFS layer until `0202`. Example shortest often 6. TC: O(10⁴ · 8). SC: O(10⁴). **If you get stuck:** “each wheel ±1, BFS like Word Ladder” (Word Ladder full card is A-1). --- ### Clone Graph — mapped R2 — UTA N — [LC 7280347](https://leetcode.com/discuss/post/7280347/amazon-india-sde-1-interview-experience-2ogbw/) **What they actually asked:** Clone Graph (R2), same IE as Next Palindromic Number and R1 Diameter variation. **Clarify out loud** - Node has `val` + `neighbors` list? Connected? Cycles? - Clone must be deep; original untouched - Null graph? **Trick / pattern in one sentence:** HashMap old→new; DFS/BFS create nodes first, then wire neighbors. **Why this data structure** - brute: none that survives cycles without a map - optimal: `HashMap` - refuse: clone by val only if vals are not unique **Brute** — same as optimal without map → infinite loop on a cycle. That *is* the failure. **Optimal** ```java GraphNode cloneGraph(GraphNode node) { if (node == null) return null; Map map = new HashMap<>(); ArrayDeque q = new ArrayDeque<>(); map.put(node, new GraphNode(node.val)); q.offer(node); while (!q.isEmpty()) { GraphNode u = q.poll(); for (GraphNode v : u.neighbors) { if (!map.containsKey(v)) { map.put(v, new GraphNode(v.val)); q.offer(v); } map.get(u).neighbors.add(map.get(v)); } } return map.get(node); } ``` **Dry run** 1—2, 1—3, 2—3 (triangle). Map creates 1',2',3' then each neighbor list copies. | visit u | map keys | u'.neighbors | | --- | --- | --- | | 1 | 1,2,3 | 2',3' | | 2 | 1,2,3 | 1',3' | | 3 | 1,2,3 | 1',2' | TC: O(V+E). SC: O(V). **If you get stuck:** recursive DFS + map; mention cycle. --- ### Keys and Rooms — mapped R2 — UTA N — [LC 6491881](https://leetcode.com/discuss/post/6491881/amazon-sde1-feb-2025-offer-by-anonymous_-skmr/) **What they actually asked:** Keys and Rooms (named). R2 after Zig-Zag + Largest BST on R1. **Clarify out loud** - `rooms[i]` = keys in room i? Start room 0 unlocked? - Need visit **all** rooms? - Duplicate keys? **Trick / pattern in one sentence:** Graph where rooms are nodes and keys are edges; DFS/BFS from 0; visited size == n. **Why this data structure** - brute: simulation with a set of keys, rescan rooms - optimal: adj list already given; BFS/DFS visited - refuse: Union-Find unless they ask components **Brute** ```java boolean canVisitAllRoomsBrute(List> rooms) { int n = rooms.size(); boolean[] open = new boolean[n]; open[0] = true; boolean changed = true; while (changed) { changed = false; for (int i = 0; i < n; i++) if (open[i]) for (int k : rooms.get(i)) if (!open[k]) { open[k] = true; changed = true; } } for (boolean b : open) if (!b) return false; return true; } ``` TC: O(n · (n+E)). SC: O(n). **Optimal** ```java boolean canVisitAllRooms(List> rooms) { boolean[] vis = new boolean[rooms.size()]; ArrayDeque q = new ArrayDeque<>(); vis[0] = true; q.offer(0); int seen = 0; while (!q.isEmpty()) { int u = q.poll(); seen++; for (int k : rooms.get(u)) if (!vis[k]) { vis[k] = true; q.offer(k); } } return seen == rooms.size(); } ``` **Dry run** `[[1],[2],[3],[]]` → 0→1→2→3, seen=4. `[[1,3],[3,0,1],[2],[0]]` room 2 never reached → false. TC: O(n+E). SC: O(n). **If you get stuck:** “start at 0, collect keys, BFS.” --- ### Dijkstra with PQ — mapped R2 — UTA N — [Sachin](https://www.linkedin.com/posts/sachinchoudhary0_amazon-interview-experience-sde1-applied-activity-7465822262709886976-lgWi) **What they actually asked:** Dijkstra using PQ (R2 with House Robber II). No LC id. **Clarify out loud** - Directed? Non-negative weights? (must be) - Source-to-all or source-to-target? - 1-indexed cities? **Trick / pattern in one sentence:** Min-heap of `(dist, node)`; skip stale heap entries; relax neighbors. **Why this data structure** - brute: Bellman-Ford O(VE) - optimal: binary heap Dijkstra O((V+E) log V) - refuse: BFS — weights are not all 1 **Brute** — scan min unused vertex each time O(V²) (OK if dense): ```java int[] dijkstraDense(int n, List[] g, int src) { int INF = Integer.MAX_VALUE / 4; int[] d = new int[n]; boolean[] used = new boolean[n]; Arrays.fill(d, INF); d[src] = 0; for (int it = 0; it < n; it++) { int u = -1; for (int i = 0; i < n; i++) if (!used[i] && (u < 0 || d[i] < d[u])) u = i; if (u < 0 || d[u] >= INF) break; used[u] = true; for (int[] e : g[u]) d[e[0]] = Math.min(d[e[0]], d[u] + e[1]); } return d; } ``` **Optimal** ```java int[] dijkstra(int n, List[] g, int src) { int INF = Integer.MAX_VALUE / 4; int[] d = new int[n]; Arrays.fill(d, INF); d[src] = 0; PriorityQueue pq = new PriorityQueue<>((a, b) -> a[0] - b[0]); pq.offer(new int[]{0, src}); while (!pq.isEmpty()) { int[] cur = pq.poll(); int du = cur[0], u = cur[1]; if (du != d[u]) continue; for (int[] e : g[u]) { int v = e[0], w = e[1]; if (d[v] > du + w) { d[v] = du + w; pq.offer(new int[]{d[v], v}); } } } return d; } ``` **Dry run** 0→1 2, 0→2 5, 1→2 1. Source 0: pop (0,0), relax 1=2, 2=5; pop (2,1), relax 2=3. | pop | d | | --- | --- | | (0,0) | [0,2,5] | | (2,1) | [0,2,3] | | (3,2) | done | TC: O((V+E) log V). SC: O(V+E). **If you get stuck:** O(V²) scan; then “PQ instead of linear min.” --- ### Course Schedule II — mapped later live / unlabeled — UTA N — [LC 6282609](https://leetcode.com/discuss/post/6282609/) **LC 210 linked on this post only** **What they actually asked:** Course Schedule II. Body Cloudflare this pass; SERP has LC **210** linked **on this post**. Reprint family: [LC 6425074](https://leetcode.com/discuss/post/6425074/amazon-sde-1-bangalore-by-anonymous_user-6w45/) R2 “similar to Course Schedule II (LC linked)”. **Do not attach this to LC 6369243** (delivery stations + parcels + classes + topo is a different first-hand wording). **Clarify out loud** - `prerequisites[i] = [a,b]` means b before a? - Any valid order or unique? Cycle → empty array? **Trick / pattern in one sentence:** Kahn’s algorithm: indegree 0 queue, emit order, fail if `order.length < n`. **Why this data structure** - brute: DFS all topological permutations - optimal: adj list + indegree + queue - refuse: copying this onto delivery-stations 6369243 **Brute** — DFS backtrack permutations O(n!). **Optimal** ```java int[] findOrder(int n, int[][] pre) { List[] g = new List[n]; int[] indeg = new int[n]; for (int i = 0; i < n; i++) g[i] = new ArrayList<>(); for (int[] p : pre) { g[p[1]].add(p[0]); indeg[p[0]]++; } ArrayDeque q = new ArrayDeque<>(); for (int i = 0; i < n; i++) if (indeg[i] == 0) q.offer(i); int[] ord = new int[n]; int k = 0; while (!q.isEmpty()) { int u = q.poll(); ord[k++] = u; for (int v : g[u]) if (--indeg[v] == 0) q.offer(v); } return k == n ? ord : new int[0]; } ``` **Dry run** n=4, pre `[1,0],[2,0],[3,1],[3,2]`: start 0 → 1,2 → 3. One valid: `0,1,2,3`. TC: O(n+E). SC: O(n+E). **If you get stuck:** DFS with 3-color cycle detect + reverse finish times. --- ### Delivery stations / parcels + classes + topological sort — mapped R2 — UTA N — [LC 6369243](https://leetcode.com/discuss/post/6369243/amazon-sde-1-interview-experience-accept-kize/) **What they actually asked:** Delivery stations / parcels + classes + topological sort. First-hand wording. **Not** LC 210. **Not** LC 962. Same IE R1: max sum switching two sorted linked lists (also not 962). **Clarify out loud** - Station objects: id, parcels, downstream stations? - Must deliver prerequisites first (topo)? - Cycle in station graph → error? - How many classes they want (5–6 mentioned in older notes — confirm with interviewer, do not invent a class diagram they did not ask) **Trick / pattern in one sentence:** Machine-coding: model `Station` / `Parcel` / `Network`, then Kahn topo to order work — describe *their* entities, do not stamp Course Schedule II. **Why this data structure** - brute: recurse “deliver this station” without memo → exponential / cycles hang - optimal: classes + indegree queue - refuse: “this is LC 210” — it is a domain wrapper around topo, different IE **Brute** — DFS “complete deps then me” without indegree, no cycle check. **Optimal** — Live-Code skeleton (names from candidate wording, not a LeetCode slug): ```java class Parcel { String id; int stationId; } class Station { int id; List parcels = new ArrayList<>(); List mustFinishBefore = new ArrayList<>(); // downstream depends on this } class DeliveryNetwork { Map stations = new HashMap<>(); List deliveryOrder() { Map indeg = new HashMap<>(); Map> g = new HashMap<>(); for (int id : stations.keySet()) { indeg.putIfAbsent(id, 0); g.putIfAbsent(id, new ArrayList<>()); } for (Station s : stations.values()) { for (int nxt : s.mustFinishBefore) { g.get(s.id).add(nxt); indeg.merge(nxt, 1, Integer::sum); indeg.putIfAbsent(s.id, 0); } } ArrayDeque q = new ArrayDeque<>(); for (var e : indeg.entrySet()) if (e.getValue() == 0) q.offer(e.getKey()); List order = new ArrayList<>(); while (!q.isEmpty()) { int u = q.poll(); order.add(u); for (int v : g.getOrDefault(u, List.of())) if (indeg.merge(v, -1, Integer::sum) == 0) q.offer(v); } if (order.size() != stations.size()) throw new IllegalStateException("cycle"); return order; } } ``` **Dry run** stations A→B, A→C, B→D, C→D: order starts A, then B/C, then D. | indeg | queue | emit | | --- | --- | --- | | A0 B1 C1 D2 | A | A | | B0 C0 D2 | B,C | A,B,C | | D0 | D | A,B,C,D | TC: O(V+E). SC: O(V+E). **If you get stuck:** list classes first on the whiteboard, then “same Kahn loop as any topo — but I am not calling this Course Schedule II.” --- ### Tree ### Path Sum–like — mapped R1 — AUTA Y — [Akash](https://www.linkedin.com/posts/akash-singh-6778a6265_softwareengineer-amazon-interviewexperience-activity-7448027373821927424-9zuD) **What they actually asked:** Path Sum–like tree (snippet). Recursion depth / stack overflow; LP first ~15 min UNNAMED; dry run. AUTA portal Jan 2026. **Clarify out loud** - Root-to-leaf only, or any path? - Node values negative? - Return boolean or the path list? - Empty tree? **Trick / pattern in one sentence:** DFS remaining target; subtract `node.val`; true when leaf and remain == 0. **Why this data structure** - brute: enumerate all root-to-leaf lists then sum - optimal: one DFS, O(h) extra - refuse: BFS unless they want all paths (then queue of (node, remain)) **Brute** ```java boolean hasPathSumBrute(TreeNode root, int target) { List path = new ArrayList<>(); return dfsCollect(root, path, target); } boolean dfsCollect(TreeNode n, List path, int target) { if (n == null) return false; path.add(n.val); if (n.left == null && n.right == null) { int s = 0; for (int x : path) s += x; path.remove(path.size() - 1); return s == target; } boolean ok = dfsCollect(n.left, path, target) || dfsCollect(n.right, path, target); path.remove(path.size() - 1); return ok; } ``` TC: O(n · h) if you resums. SC: O(h). **Optimal** ```java boolean hasPathSum(TreeNode root, int target) { if (root == null) return false; if (root.left == null && root.right == null) return root.val == target; return hasPathSum(root.left, target - root.val) || hasPathSum(root.right, target - root.val); } boolean hasPathSumIter(TreeNode root, int target) { if (root == null) return false; ArrayDeque ns = new ArrayDeque<>(); ArrayDeque rs = new ArrayDeque<>(); ns.push(root); rs.push(target - root.val); while (!ns.isEmpty()) { TreeNode n = ns.pop(); int rem = rs.pop(); if (n.left == null && n.right == null && rem == 0) return true; if (n.right != null) { ns.push(n.right); rs.push(rem - n.right.val); } if (n.left != null) { ns.push(n.left); rs.push(rem - n.left.val); } } return false; } ``` **Dry run** tree `5 / 4 8`, `4 / 11`, target 20: 5-4-11 = 20 true. | node | remain after visit | | --- | --- | | 5 | 15 | | 4 | 11 | | 11 leaf | 0 → true | TC: O(n). SC: O(h). Iterative if they probe stack overflow (they did). **If you get stuck:** write recursive boolean; then explicit stack. --- ### Stack / greedy Daily Temperatures, Asteroid Collision, Next Greater, Remove K Digits, Next permutation, Min Arrows, min platforms — full cards sit in tree / string / array groups where the IE paired them. Heaters is BS (with 7035289). ### Daily Temperatures–like (monotonic stack) — mapped R1 — UTA Y — [Naina](https://medium.com/@nainavangani09/my-amazon-sde-1-interview-experience-2025-selected-dea6b5e9e3e9) **What they actually asked:** Daily Temperatures–like monotonic stack. Full I/O + dry run. UTA 12 Jun 2025. **Stack, not tree.** Same R1 as logic-heavy non-standard UNNAMED. **Clarify out loud** - For each day, days until a strictly warmer day? 0 if none? - Equal temps: not warmer? - Return array of waits? **Trick / pattern in one sentence:** Decreasing stack of indices; when a warmer day arrives, pop and fill `j - i`. **Why this data structure** - brute: nested loops O(n²) - optimal: monotonic decreasing stack of indices - refuse: heap of (temp, i) — stack already gives next greater in O(n) **Brute** ```java int[] dailyBrute(int[] t) { int n = t.length; int[] ans = new int[n]; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (t[j] > t[i]) { ans[i] = j - i; break; } return ans; } ``` TC: O(n²). SC: O(1) extra. **Optimal** ```java int[] dailyTemperatures(int[] t) { int n = t.length; int[] ans = new int[n]; ArrayDeque st = new ArrayDeque<>(); // indices, temps decreasing for (int i = 0; i < n; i++) { while (!st.isEmpty() && t[i] > t[st.peek()]) { int j = st.pop(); ans[j] = i - j; } st.push(i); } return ans; } ``` **Dry run** `[73,74,75,71,69,72,76,73]` | i | t | stack after | ans writes | | --- | --- | --- | --- | | 0 | 73 | [0] | | | 1 | 74 | [1] | ans[0]=1 | | 2 | 75 | [2] | ans[1]=1 | | 5 | 72 | [2,5] | ans[4]=1, ans[3]=2 | TC: O(n). SC: O(n). **If you get stuck:** brute nested; then “stack of unresolved colder days.” --- ### Heaters — mapped R1 — AUTA Y — [LC 7035289](https://leetcode.com/discuss/post/7035289/amazon-sde-1-offer-by-anonymous_user-3efp/) **What they actually asked:** Heaters (R1 with Max Width BT). AUTA email then offer. **BS + sort**, grouped here because it shipped with the tree question. **Clarify out loud** - Houses and heaters on a line (ints)? - Minimize radius r so every house is within r of some heater? - Heaters can sit on houses? **Trick / pattern in one sentence:** Sort heaters; for each house binary-search closest heater; answer = max of those distances. **Why this data structure** - brute: for each house scan all heaters - optimal: sort + BS (or two pointers after both sorted) - refuse: graph BFS on the line — overkill **Brute** ```java int findRadiusBrute(int[] houses, int[] heaters) { int ans = 0; for (int h : houses) { int best = Integer.MAX_VALUE; for (int t : heaters) best = Math.min(best, Math.abs(h - t)); ans = Math.max(ans, best); } return ans; } ``` TC: O(H · T). SC: O(1). **Optimal** ```java int findRadius(int[] houses, int[] heaters) { Arrays.sort(heaters); int ans = 0; for (int h : houses) { int i = Arrays.binarySearch(heaters, h); if (i < 0) i = -i - 1; int d1 = i < heaters.length ? heaters[i] - h : Integer.MAX_VALUE; int d0 = i > 0 ? h - heaters[i - 1] : Integer.MAX_VALUE; ans = Math.max(ans, Math.min(d0, d1)); } return ans; } ``` **Dry run** houses `[1,2,3,4]`, heaters `[1,4]`: house 2 → dist 1, house 3 → dist 1, radius 1. TC: O((H+T) log T) after sort. SC: O(1) besides sort. **If you get stuck:** BS-on-answer on r, then greedy cover (also valid; slower to code). --- ### Max Width of Binary Tree — mapped R1 — AUTA Y — [LC 7035289](https://leetcode.com/discuss/post/7035289/amazon-sde-1-offer-by-anonymous_user-3efp/) **What they actually asked:** Max Width of Binary Tree (same R1 as Heaters). **Clarify out loud** - Width = last-first index + 1 on a level, counting null gaps as in a heap numbering? - Overflow if using `2*i` on deep trees? (use `long` or reindex per level) **Trick / pattern in one sentence:** BFS with heap-style indices; width = rightIndex − leftIndex + 1; subtract level-min index to avoid overflow. **Why this data structure** - brute: materialize nulls per level — explodes - optimal: queue of (node, col) - refuse: storing full 2^h arrays **Brute** — list every slot including nulls, O(2^h) memory. Fails deep skinny trees that are still wide in indexing. **Optimal** ```java int widthOfBinaryTree(TreeNode root) { if (root == null) return 0; int ans = 1; ArrayDeque q = new ArrayDeque<>(); q.offer(new Object[]{root, 0L}); while (!q.isEmpty()) { int sz = q.size(); long left = (Long) q.peek()[1], right = left; for (int i = 0; i < sz; i++) { Object[] cur = q.poll(); TreeNode n = (TreeNode) cur[0]; long idx = (Long) cur[1]; right = idx; long norm = idx - left; // reindex if (n.left != null) q.offer(new Object[]{n.left, 2 * norm}); if (n.right != null) q.offer(new Object[]{n.right, 2 * norm + 1}); } ans = (int) Math.max(ans, right - left + 1); } return ans; } ``` **Dry run** complete 3-node: indices 0 / 0,1 → width 2. Full 7-node level-2: width 4. TC: O(n). SC: O(w). **If you get stuck:** BFS pairs; mention `long` / reindex. --- ### Diameter of Binary Tree variation — mapped R1 — UTA N — [LC 7280347](https://leetcode.com/discuss/post/7280347/amazon-india-sde-1-interview-experience-2ogbw/) **What they actually asked:** Diameter of Binary Tree **variation** (not stamped as exact LC 543). Same IE as Clone Graph R2. **Clarify out loud** - Diameter in edges or nodes? - Through root only or any node? - Weighted edges? (usually unweighted) **Trick / pattern in one sentence:** Post-order height; at each node candidate = leftH + rightH; track global max. **Why this data structure** - brute: for every node, height(left)+height(right), height is O(n) → O(n²) - optimal: one post-order returning height, updating ans - refuse: converting to graph then BFS twice unless they made it a general tree **Brute** ```java int diameterBrute(TreeNode root) { if (root == null) return 0; int through = height(root.left) + height(root.right); return Math.max(through, Math.max(diameterBrute(root.left), diameterBrute(root.right))); } int height(TreeNode n) { if (n == null) return 0; return 1 + Math.max(height(n.left), height(n.right)); } ``` TC: O(n²). SC: O(h). **Optimal** ```java int ans = 0; int diameter(TreeNode root) { ans = 0; depth(root); return ans; } int depth(TreeNode n) { if (n == null) return 0; int L = depth(n.left), R = depth(n.right); ans = Math.max(ans, L + R); // edges return 1 + Math.max(L, R); } ``` **Dry run** 1 / 2 3, 2 / 4 5: at 2, L+R=2; at 1, 2+1=3. Diameter 3 edges. | node | L | R | ans | | --- | --- | --- | --- | | 4,5,3 | 0 | 0 | 0 | | 2 | 1 | 1 | 2 | | 1 | 2 | 1 | 3 | TC: O(n). SC: O(h). **If you get stuck:** brute heights; then “return height, update global.” --- ### Uni-valued subtrees — mapped R1 — UTA N — [LC 6461439](https://leetcode.com/discuss/post/6461439/amazon-sde-1-feb-2025-interview-experien-wv10/) **What they actually asked:** Uni-valued subtrees (R1 with Search in Rotated Sorted Array). **Clarify out loud** - Count subtrees where every node has the same value? - Single nodes count? (yes) - Return count or boolean “is unival”? **Trick / pattern in one sentence:** Post-order: a node is unival if left/right are unival (or null) and child vals match node. **Why this data structure** - brute: for every node, scan its subtree - optimal: one post-order returning (isUnival, count contrib) - refuse: extra HashSet per subtree of all values — O(n²) **Brute** ```java int countUnivalBrute(TreeNode root) { if (root == null) return 0; int c = isUnival(root, root.val) ? 1 : 0; return c + countUnivalBrute(root.left) + countUnivalBrute(root.right); } boolean isUnival(TreeNode n, int v) { if (n == null) return true; return n.val == v && isUnival(n.left, v) && isUnival(n.right, v); } ``` TC: O(n²). SC: O(h). **Optimal** ```java int count; int countUnivalSubtrees(TreeNode root) { count = 0; uni(root); return count; } boolean uni(TreeNode n) { if (n == null) return true; boolean L = uni(n.left), R = uni(n.right); if (!L || !R) return false; if (n.left != null && n.left.val != n.val) return false; if (n.right != null && n.right.val != n.val) return false; count++; return true; } ``` **Dry run** 5 / 1 5, 1 / 5 5, right 5 / null 5: leaves all unival; left-1 not; some 5s yes. TC: O(n). SC: O(h). **If you get stuck:** define “this subtree all equal,” recurse. --- ### Count BT nodes with two children — mapped R1 — UTA Y — [LC 6653463](https://leetcode.com/discuss/post/6653463/amazon-software-dev-engineer-1-universit-dtk5/) **What they actually asked:** count BT nodes with two children. UTA named. Same R1 as student HashMap OOD. **Clarify out loud** - Both left and right non-null? - Count nodes, not subtrees? **Trick / pattern in one sentence:** DFS/BFS; increment when `left != null && right != null`. **Why this data structure** - brute = optimal here; tree walk is the problem - refuse: converting to array **Brute / Optimal** (same) ```java int countFullNodes(TreeNode root) { if (root == null) return 0; int me = (root.left != null && root.right != null) ? 1 : 0; return me + countFullNodes(root.left) + countFullNodes(root.right); } ``` **Dry run** 1 / 2 3, 2 / 4 null: only node 1 has two children → 1. TC: O(n). SC: O(h). **If you get stuck:** say the predicate out loud, then recurse. --- ### Zig-Zag Binary Tree — mapped R1 — UTA N — [LC 6491881](https://leetcode.com/discuss/post/6491881/amazon-sde1-feb-2025-offer-by-anonymous_-skmr/) **What they actually asked:** Print Zig-Zag Binary Tree. Full code + dry run. Same R1 as Largest BST. **Clarify out loud** - Level 0 L→R, level 1 R→L, …? - Return list of lists or print? **Trick / pattern in one sentence:** BFS; reverse odd levels (or two stacks / deque addFirst-addLast). **Why this data structure** - brute: BFS then reverse odd lists - optimal: same O(n); deque version avoids extra reverse - refuse: recursion by height without a queue — painful **Brute** ```java List> zigzagBrute(TreeNode root) { List> ans = new ArrayList<>(); if (root == null) return ans; ArrayDeque q = new ArrayDeque<>(); q.offer(root); boolean ltr = true; while (!q.isEmpty()) { int sz = q.size(); List row = new ArrayList<>(); for (int i = 0; i < sz; i++) { TreeNode n = q.poll(); row.add(n.val); if (n.left != null) q.offer(n.left); if (n.right != null) q.offer(n.right); } if (!ltr) Collections.reverse(row); ans.add(row); ltr = !ltr; } return ans; } ``` TC: O(n). SC: O(w). Reverse is O(w) extra per odd level — still O(n). **Optimal** — LinkedList addFirst/addLast: ```java List> zigzagLevelOrder(TreeNode root) { List> ans = new ArrayList<>(); if (root == null) return ans; ArrayDeque q = new ArrayDeque<>(); q.offer(root); boolean ltr = true; while (!q.isEmpty()) { int sz = q.size(); LinkedList row = new LinkedList<>(); for (int i = 0; i < sz; i++) { TreeNode n = q.poll(); if (ltr) row.addLast(n.val); else row.addFirst(n.val); if (n.left != null) q.offer(n.left); if (n.right != null) q.offer(n.right); } ans.add(row); ltr = !ltr; } return ans; } ``` **Dry run** 3 / 9 20 / 15 7: `[[3],[20,9],[15,7]]`. TC: O(n). SC: O(w). **If you get stuck:** normal level order, reverse alternate. --- ### Largest BST in Binary Tree — mapped R1 — UTA N — [LC 6491881](https://leetcode.com/discuss/post/6491881/amazon-sde1-feb-2025-offer-by-anonymous_-skmr/) **What they actually asked:** Largest BST in Binary Tree. Full code + dry run. **Clarify out loud** - Largest by node count or by sum? - BST definition: left < node < right, strict? - Whole tree may not be BST **Trick / pattern in one sentence:** Post-order return `{isBST, min, max, size}`; if children are BSTs and `left.max < node < right.min`, size = 1+L+R. **Why this data structure** - brute: for every node, validate BST on that subtree O(n²) - optimal: one post-order Info object - refuse: inorder dump + longest increasing — that is a sequence, not a subtree **Brute** ```java int largestBSTBrute(TreeNode root) { if (root == null) return 0; if (isBST(root, Long.MIN_VALUE, Long.MAX_VALUE)) return size(root); return Math.max(largestBSTBrute(root.left), largestBSTBrute(root.right)); } boolean isBST(TreeNode n, long lo, long hi) { if (n == null) return true; if (n.val <= lo || n.val >= hi) return false; return isBST(n.left, lo, n.val) && isBST(n.right, n.val, hi); } int size(TreeNode n) { return n == null ? 0 : 1 + size(n.left) + size(n.right); } ``` TC: O(n²). SC: O(h). **Optimal** ```java class Info { boolean bst; int min, max, sz, best; Info(boolean b, int mn, int mx, int s, int be) { bst=b; min=mn; max=mx; sz=s; best=be; } } int largestBSTSubtree(TreeNode root) { return dfs(root).best; } Info dfs(TreeNode n) { if (n == null) return new Info(true, Integer.MAX_VALUE, Integer.MIN_VALUE, 0, 0); Info L = dfs(n.left), R = dfs(n.right); if (L.bst && R.bst && L.max < n.val && n.val < R.min) { int sz = 1 + L.sz + R.sz; return new Info(true, Math.min(n.val, L.min), Math.max(n.val, R.max), sz, Math.max(sz, Math.max(L.best, R.best))); } return new Info(false, 0, 0, 0, Math.max(L.best, R.best)); } ``` **Dry run** 10 / 5 15 / 1 8 and 7 17: subtree at 5 is BST size 3; whole tree fails because 7 < 10 on the right. Best 3. TC: O(n). SC: O(h). **If you get stuck:** brute isBST+size; then Info struct. --- ### Max sum level in Binary Tree — mapped R1 — UTA N — [LC 6475219](https://leetcode.com/discuss/post/6475219/amazon-sde-1-interview-experience-bangal-4aa6/) **What they actually asked:** maximum sum level in Binary Tree. Same R1 as Find Median from stream (heap card). No LP (time). **Clarify out loud** - Return the max sum, or the 1-based level index? (LC 1161 is max sum; some ask level number) - Ties: smallest level? **Trick / pattern in one sentence:** BFS; sum each level; track max. **Why this data structure** - brute: DFS with (node, depth) into `Map` - optimal: BFS - refuse: storing all nodes per level if you only need the sum **Brute** — DFS map: ```java void dfs(TreeNode n, int d, Map m) { if (n == null) return; m.merge(d, (long) n.val, Long::sum); dfs(n.left, d + 1, m); dfs(n.right, d + 1, m); } ``` TC: O(n). SC: O(h + height). **Optimal** ```java int maxLevelSum(TreeNode root) { ArrayDeque q = new ArrayDeque<>(); q.offer(root); long best = Long.MIN_VALUE; int bestLvl = 1, lvl = 1; while (!q.isEmpty()) { int sz = q.size(); long s = 0; for (int i = 0; i < sz; i++) { TreeNode n = q.poll(); s += n.val; if (n.left != null) q.offer(n.left); if (n.right != null) q.offer(n.right); } if (s > best) { best = s; bestLvl = lvl; } lvl++; } return bestLvl; // or return (int) best if they want the sum } ``` **Dry run** 1 / 7 0 / 7 -8: level2 sum 7, level3 sum −1 → level 2. TC: O(n). SC: O(w). **If you get stuck:** BFS sums. --- ### Validate Sum Tree — mapped R2 — UTA N — [LC 6629948](https://leetcode.com/discuss/post/6629948/amazon-sde-1-20232024-graduate-round-2-b-v6wy/) **What they actually asked:** Validate Sum Tree (LC linked). Same R2 as Minimum Knight Moves. **Clarify out loud** - For every non-leaf, `node.val == sum(left subtree) + sum(right subtree)` or only immediate children? - Classic GFG Sum Tree = **subtree** sums, not just children. **Trick / pattern in one sentence:** Post-order return subtree sum; check `node.val == leftSum + rightSum` for non-leaves. **Why this data structure** - brute: recompute subtree sum at every node O(n²) - optimal: one post-order - refuse: inorder **Brute** ```java boolean isSumTreeBrute(TreeNode root) { if (root == null || (root.left == null && root.right == null)) return true; int s = sum(root.left) + sum(root.right); return root.val == s && isSumTreeBrute(root.left) && isSumTreeBrute(root.right); } int sum(TreeNode n) { return n == null ? 0 : n.val + sum(n.left) + sum(n.right); } ``` TC: O(n²). SC: O(h). **Optimal** ```java boolean ok = true; boolean isSumTree(TreeNode root) { ok = true; subtree(root); return ok; } int subtree(TreeNode n) { if (n == null) return 0; if (n.left == null && n.right == null) return n.val; int s = subtree(n.left) + subtree(n.right); if (n.val != s) ok = false; return n.val + s; // GFG often returns total including node for parent } ``` Careful: GFG `isSumTree` parent check uses **children subtree totals including those nodes’ values**, and the function returns the full subtree sum (`node.val + left + right` vs check `node.val == left+right` where left/right are full subtree sums of children). Live-Code: confirm with a 3-node example: `26 / 10 3 / 4 6 and 3` → 10==4+6, 3==3 (leaf-child), 26==10+3+3? Standard GFG: 26 == 10+16? Use the example they draw. **Dry run** (GFG classic) 26 / 10 3, 10 / 4 6, 3 / null 3: 4+6=10, 0+3=3, 10+3+3=16 wait — classic tree is 26 == 10 + 16? The stored 3 on right has a child 3 so right subtree sum is 6. Confirm on their diagram. Safer check used in interviews: ```java class Pair { boolean ok; int sum; Pair(boolean o, int s) { ok=o; sum=s; } } Pair rec(TreeNode n) { if (n == null) return new Pair(true, 0); if (n.left == null && n.right == null) return new Pair(true, n.val); Pair L = rec(n.left), R = rec(n.right); boolean good = L.ok && R.ok && n.val == L.sum + R.sum; return new Pair(good, n.val + L.sum + R.sum); } ``` TC: O(n). SC: O(h). **If you get stuck:** brute sums; then return sum from DFS. --- ### Burning Tree — mapped R1 — UTA N — [GFG fresher](https://www.geeksforgeeks.org/interview-experiences/amazon-interview-experience-for-sde1-fresher-off-campus/) **What they actually asked:** Burning Tree (GFG named). Same R1 as Merge Intervals. 25 Jan 2025 fresher off-campus. **Clarify out loud** - Start node given as target value? Time = minutes until all nodes burnt? - Fire spreads to parent and children 1 min? **Trick / pattern in one sentence:** Build parent pointers (or undirected graph), BFS from target; answer = last BFS layer. **Why this data structure** - brute: at each minute scan all nodes O(n²) - optimal: parent map + BFS - refuse: only child DFS without parent — fire must go up **Brute** — simulate sets of burning nodes, each minute expand neighbors O(n · time). **Optimal** ```java int amountOfTime(TreeNode root, int start) { Map par = new HashMap<>(); TreeNode src = mapParents(root, null, par, start); ArrayDeque q = new ArrayDeque<>(); Set vis = new HashSet<>(); q.offer(src); vis.add(src); int min = 0; while (!q.isEmpty()) { int sz = q.size(); for (int i = 0; i < sz; i++) { TreeNode u = q.poll(); for (TreeNode v : new TreeNode[]{u.left, u.right, par.get(u)}) { if (v != null && vis.add(v)) q.offer(v); } } if (!q.isEmpty()) min++; } return min; } TreeNode mapParents(TreeNode n, TreeNode p, Map par, int start) { if (n == null) return null; par.put(n, p); if (n.val == start) { mapParents(n.left, n, par, start); mapParents(n.right, n, par, start); return n; } TreeNode L = mapParents(n.left, n, par, start); if (L != null) { mapParents(n.right, n, par, start); return L; } return mapParents(n.right, n, par, start); } ``` **Dry run** start at leaf: time = depth to farthest node via parent. TC: O(n). SC: O(n). **If you get stuck:** “undirected tree, BFS from fire.” Distance K no-parent-map is A-1 — here parents are allowed. --- ### DP ### House Robber I then II (circular) — mapped R1 + Sachin R2 LC 213 — UTA N — [LC 8029194](https://leetcode.com/discuss/post/8029194/amazon-interview-sde-1-selected-by-anony-qatd/) **What they actually asked:** House Robber then House Robber II circular (named) onsite Mar 2026 BLR R1. Reprint: [Sachin](https://www.linkedin.com/posts/sachinchoudhary0_amazon-interview-experience-sde1-applied-activity-7465822262709886976-lgWi) R2 **LC 213**. Same 8029194 R2 also had jumps UNNAMED (pattern card below). **Clarify out loud** - Cannot rob adjacent; circular means first and last are adjacent? - Negative money? (no) - Empty / one house? **Trick / pattern in one sentence:** Linear HR is `dp[i] = max(dp[i-1], dp[i-2]+a[i])`; circular = max(rob `[0..n-2]`, rob `[1..n-1]`). **Why this data structure** - brute: 2^n subsets - optimal: O(n) DP, two variables - refuse: heap **Brute** ```java int robBrute(int[] a, int i, int last) { if (i > last) return 0; return Math.max(robBrute(a, i + 1, last), a[i] + robBrute(a, i + 2, last)); } ``` TC: O(2^n). SC: O(n) stack. **Optimal** ```java int robLinear(int[] a, int l, int r) { // inclusive int prev2 = 0, prev1 = 0; for (int i = l; i <= r; i++) { int cur = Math.max(prev1, prev2 + a[i]); prev2 = prev1; prev1 = cur; } return prev1; } int rob(int[] a) { // House Robber I return robLinear(a, 0, a.length - 1); } int rob2(int[] a) { // House Robber II LC 213 int n = a.length; if (n == 1) return a[0]; return Math.max(robLinear(a, 0, n - 2), robLinear(a, 1, n - 1)); } ``` **Dry run** `[2,3,2]` circular: rob 0..1 → max 3; rob 1..2 → max 3; answer 3 (cannot take both 2s). | range | prev1 | | --- | --- | | [2,3] | 3 | | [3,2] | 3 | TC: O(n). SC: O(1). **If you get stuck:** linear first, then “drop first or drop last.” --- ### Trapping Rainwater + Stocks DP — mapped R1 (OA-as-R1 first live) — UTA N — [igreaper](https://igreaper.medium.com/amazon-sde-1-interview-experience-a69578a4f699) **What they actually asked:** Trapping Rainwater; DP on Stocks. Candidate R2 → **our R1**. Their R3 Rotten + Max Rectangle → our R2 (Rotten is A-1; Max Rectangle in this file). **Clarify out loud (rain):** bars of width 1? water above each index = min(leftMax, rightMax) − h if positive? **Clarify out loud (stocks):** one transaction? unlimited? cooldown? at most k? — **ask**; igreaper said “DP on Stocks,” not a numbered LC. **Trick / pattern:** Rain = prefix/suffix max (or two pointers). Stocks = `dp` hold/cash states. **Why this data structure** - rain brute: for each i scan left max and right max O(n²) - rain optimal: two arrays or two pointers O(n) - stocks brute: recurse buy/sell days - stocks optimal: 1–2 state variables unless k is large **Brute rain** ```java int trapBrute(int[] h) { int n = h.length, water = 0; for (int i = 0; i < n; i++) { int L = 0, R = 0; for (int j = 0; j <= i; j++) L = Math.max(L, h[j]); for (int j = i; j < n; j++) R = Math.max(R, h[j]); water += Math.min(L, R) - h[i]; } return water; } ``` TC: O(n²). SC: O(1). **Optimal rain** ```java int trap(int[] h) { int l = 0, r = h.length - 1, lmax = 0, rmax = 0, ans = 0; while (l < r) { if (h[l] < h[r]) { if (h[l] >= lmax) lmax = h[l]; else ans += lmax - h[l]; l++; } else { if (h[r] >= rmax) rmax = h[r]; else ans += rmax - h[r]; r--; } } return ans; } ``` **Dry run rain** `[0,1,0,2,1,0,1,3,2,1,2,1]` classic answer 6. Index 2: min(1,2)−0 = 1, etc. **Stocks — start with unlimited (k = ∞), then one-txn, then cooldown if they push:** ```java int maxProfitUnlimited(int[] p) { int cash = 0, hold = Integer.MIN_VALUE / 4; for (int x : p) { cash = Math.max(cash, hold + x); hold = Math.max(hold, cash - x); // unbounded: cash already new } return cash; } int maxProfitOne(int[] p) { int min = Integer.MAX_VALUE, ans = 0; for (int x : p) { min = Math.min(min, x); ans = Math.max(ans, x - min); } return ans; } int maxProfitCooldown(int[] p) { int cash = 0, hold = Integer.MIN_VALUE / 4, prevCash = 0; for (int x : p) { int newCash = Math.max(cash, hold + x); hold = Math.max(hold, prevCash - x); prevCash = cash; cash = newCash; } return cash; } ``` TC: O(n) each. SC: O(1). **If you get stuck (rain):** leftMax[]/rightMax[]. **Stocks:** write states “hold vs cash” before code. --- ### Falling Path Sum variation — mapped R2 — UTA N — [LC 6461439](https://leetcode.com/discuss/post/6461439/amazon-sde-1-feb-2025-interview-experien-wv10/) **What they actually asked:** Falling Path Sum **variation** (R2 with Rotten variation — Rotten is A-1). Not stamped as exact LC 931. **Clarify out loud** - Start any cell on first row? Move down to `j-1,j,j+1`? - Min or max path? - Square matrix? **Trick / pattern in one sentence:** DP `dp[r][c] = a[r][c] + min/max of allowed parents`. **Why this data structure** - brute: DFS from each top cell exponential - optimal: in-place or 1D rolling DP - refuse: Dijkstra unless weights negative and they want a graph speech **Brute** ```java int dfs(int[][] a, int r, int c) { int n = a.length; if (c < 0 || c >= n) return Integer.MAX_VALUE / 4; if (r == n - 1) return a[r][c]; int best = Integer.MAX_VALUE / 4; for (int dc = -1; dc <= 1; dc++) best = Math.min(best, dfs(a, r + 1, c + dc)); return a[r][c] + best; } ``` TC: O(3^n · n) starts. Fails n~100. **Optimal** (min falling) ```java int minFallingPathSum(int[][] a) { int n = a.length; int[] dp = a[0].clone(); for (int r = 1; r < n; r++) { int[] nd = new int[n]; for (int c = 0; c < n; c++) { int best = dp[c]; if (c > 0) best = Math.min(best, dp[c - 1]); if (c + 1 < n) best = Math.min(best, dp[c + 1]); nd[c] = a[r][c] + best; } dp = nd; } int ans = dp[0]; for (int x : dp) ans = Math.min(ans, x); return ans; } ``` **Dry run** `[[2,1,3],[6,5,4],[7,8,9]]`: row1 → 7,6,5; row2 → 13,13,14; min 13. TC: O(n²). SC: O(n). **If you get stuck:** mutate matrix top-down. --- ### Matrix max-path right/diag (not identical Falling Path) — mapped R2 — UTA N Job 3057703 — [Prince](https://medium.com/@princepandey20022002/amazon-sde-1-interview-experience-off-campus-57825c172e2f) **What they actually asked:** matrix max-path **right/diag** — candidate said **not identical** to Falling Path. Job 3057703. Same loop R1 LC 424. **Clarify out loud** - Moves: only right, and diagonal (which diagonal — down-right / up-right)? - Start column 0 any row? End last column? - Max sum? Obstacles? **Trick / pattern in one sentence:** Grid DP with **their** move set; do not copy Falling Path’s down+diag. **Why this data structure** - brute: DFS - optimal: `dp[r][c]` from allowed predecessors - refuse: stamping LC 931 / 64 **Brute** — DFS from each start on left column. **Optimal** — assume start any row col 0, moves right `(0,+1)` and down-right `(+1,+1)` (confirm): ```java int maxPath(int[][] a) { int m = a.length, n = a[0].length; int[][] dp = new int[m][n]; for (int i = 0; i < m; i++) dp[i][0] = a[i][0]; for (int j = 1; j < n; j++) { for (int i = 0; i < m; i++) { int best = dp[i][j - 1]; // right from same row if (i > 0) best = Math.max(best, dp[i - 1][j - 1]); // down-right into i dp[i][j] = a[i][j] + best; } } int ans = Integer.MIN_VALUE; for (int i = 0; i < m; i++) ans = Math.max(ans, dp[i][n - 1]); return ans; } ``` **Dry run** 2×3 `1 2 3 / 4 5 6` with those moves: path 4-5-6 = 15 vs 1-2-3 = 6. TC: O(mn). SC: O(mn) or rolling column. **If you get stuck:** write the 2–3 allowed deltas they stated, then DP. --- ### Race Car — mapped R1 — UTA N — [GFG sde-1-34](https://www.geeksforgeeks.org/interview-experiences/amazon-interview-experience-for-sde-1-34/) **What they actually asked:** Race Car (`race-car` slug). ~2024. Reprint: `sde-1off-campus-2023` ≡ sde-1-34. Not UTA-default. **Clarify out loud** - Position 0, speed +1; instructions `A` (pos+=speed; speed*=2) and `R` (speed = speed>0 ? −1 : 1)? - Target position? Min instructions? **Trick / pattern in one sentence:** BFS on `(position, speed)` until position == target; bound position to ~2·target. **Why this data structure** - brute: recurse all A/R strings - optimal: BFS state - refuse: greedy “always A then R” — not optimal **Brute** — DFS with cap on length. Exponential. **Optimal** ```java int racecar(int target) { ArrayDeque q = new ArrayDeque<>(); // pos, speed, steps Set vis = new HashSet<>(); q.offer(new int[]{0, 1, 0}); vis.add("0,1"); while (!q.isEmpty()) { int[] c = q.poll(); int pos = c[0], sp = c[1], steps = c[2]; if (pos == target) return steps; // A int np = pos + sp, ns = sp * 2; if (Math.abs(np) <= 2 * target + 2) { String k = np + "," + ns; if (vis.add(k)) q.offer(new int[]{np, ns, steps + 1}); } // R int rs = sp > 0 ? -1 : 1; String k2 = pos + "," + rs; if (vis.add(k2)) q.offer(new int[]{pos, rs, steps + 1}); } return -1; } ``` **Dry run** target 3: `A A` → pos 0→1→3, speed 1→2→4. Steps 2. | seq | pos | speed | | --- | --- | --- | | "" | 0 | 1 | | A | 1 | 2 | | AA | 3 | 4 | TC: BFS over states; empirically OK for typical targets. SC: states visited. **If you get stuck:** “state = position + speed, BFS.” --- ### Stone Collision + reconstruct coins from ways-DP — mapped R2 — UTA N — [LC 6606011](https://leetcode.com/discuss/post/6606011/amazon-sde-1-interview-experience-27-mar-ermb/) **What they actually asked:** Stone Collision — **UNNAMED beyond that phrase**; Reconstruct coins from ways-DP — **UNNAMED**. Consecutive-day loop. **Pattern cards — do not invent LC ids.** #### Stone Collision (pattern) Phrase only. Adjacent families (say which you are assuming): (1) smash two heaviest (Last Stone Weight — PQ); (2) Asteroid Collision signed array (stack — full card later in this file). Ask: signs? all positive stones? two at a time? **PQ smash pattern (if all positive, two heaviest collide):** ```java int lastStone(int[] s) { PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); for (int x : s) pq.offer(x); while (pq.size() > 1) { int a = pq.poll(), b = pq.poll(); if (a != b) pq.offer(a - b); } return pq.isEmpty() ? 0 : pq.peek(); } ``` TC: O(n log n). If they meant asteroids, jump to the Asteroid Collision card. #### Reconstruct coins from ways-DP (pattern) Given `dp[x] = number of ways to make amount x` (classic coin-change-ways), recover a coin set. Unnamed beyond the phrase. Typical interview: coins unlimited, `dp[0]=1`, `dp[x] += dp[x-c]`. Inverse is underdetermined; talk greedy: smallest c>0 with `dp[c]>0` is a coin, then “divide out” that coin’s contribution — **only works under extra assumptions they must state**. ```java // Pattern talk: do not claim this was the hidden LC. // If dp is the *minimum coins* array, coins are indices where dp[i]==1 and i not sum of smaller. List guessCoinsFromWays(int[] dp) { List coins = new ArrayList<>(); for (int c = 1; c < dp.length; c++) { if (dp[c] > 0 && (c == 1 || dp[c] == dp[c - 1] + /* unknown */ 0)) { // stop: need their recurrence. Ask for a tiny example. } } return coins; } ``` **Stuck:** write the **forward** coin-change-ways DP they know, then invert on a 3-coin example they give. --- ### Count Complete Subarrays — mapped R1 (OA-as-R1) — UTA N (consec-day, not named UTA) — [GFG 2025](https://www.geeksforgeeks.org/interview-experiences/amazon-interview-experience-for-sde-i-off-campus-2025/) **What they actually asked:** Count Complete Subarrays. Candidate R2 → our R1. Rank C consecutive-day, **not** named UTA. **Clarify out loud** - Complete = subarray distinct count equals distinct count of the **whole** array? - Array values range? **Trick / pattern in one sentence:** Let `need = distinct(nums)`. Count subarrays with ≥ `need` distinct = `atMost(n) − atMost(need−1)` window. **Why this data structure** - brute: all i,j with a HashSet O(n²) - optimal: sliding window + freq map, two-pointer - refuse: sorting the array — order matters **Brute** ```java int countCompleteBrute(int[] a) { Set all = new HashSet<>(); for (int x : a) all.add(x); int need = all.size(), n = a.length, ans = 0; for (int i = 0; i < n; i++) { Set s = new HashSet<>(); for (int j = i; j < n; j++) { s.add(a[j]); if (s.size() == need) ans++; } } return ans; } ``` TC: O(n²). SC: O(u). **Optimal** — number of subarrays whose distinct ≥ need is: for each r, smallest l such that `[l,r]` has `need` distinct, then all i≤l work. ```java int countCompleteSubarrays(int[] a) { Set all = new HashSet<>(); for (int x : a) all.add(x); int need = all.size(); return atMost(a, a.length) - atMost(a, need - 1); } int atMost(int[] a, int k) { if (k < 0) return 0; Map freq = new HashMap<>(); int l = 0, ans = 0; for (int r = 0; r < a.length; r++) { freq.merge(a[r], 1, Integer::sum); while (freq.size() > k) { int x = a[l++]; int c = freq.get(x) - 1; if (c == 0) freq.remove(x); else freq.put(x, c); } ans += r - l + 1; } return ans; } ``` Wait: complete means **exactly** `need` distinct, and `need` is already the global max, so **exactly need = at least need**. `atMost(n) - atMost(need-1)` is exactly ≥ need, which equals exactly need. Good. **Dry run** `[1,3,1,2,2]`, global distinct {1,3,2}=3. Complete subarrays are those that contain 1,2,3. TC: O(n). SC: O(u). **If you get stuck:** brute i,j set; then “window of distinct.” --- ### Count Number of Nice Subarrays — mapped BR — AUTA Y — [LC 6806195](https://leetcode.com/discuss/post/6806195/amazon-auta-interview-experience-sde-1-2-f90u/) **What they actually asked:** Count Number of Nice Subarrays (LC linked) on AUTA BR. Same loop R1 Capacity + Asteroid similar; R2 Rotate + Next Perm similar (A-1). **Clarify out loud** - Nice = exactly k odd numbers in the subarray? - Evens are free? **Trick / pattern in one sentence:** Treat odd=1 even=0; count subarrays with sum k = `atMost(k) − atMost(k−1)` or prefix-count HashMap. **Why this data structure** - brute: all subarrays count odds - optimal: sliding window atMost, or prefix `Map` - refuse: DP O(n²) **Brute** ```java int niceBrute(int[] a, int k) { int n = a.length, ans = 0; for (int i = 0; i < n; i++) { int odd = 0; for (int j = i; j < n; j++) { if ((a[j] & 1) == 1) odd++; if (odd == k) ans++; } } return ans; } ``` TC: O(n²). SC: O(1). **Optimal** ```java int numberOfSubarrays(int[] a, int k) { return atMostOdd(a, k) - atMostOdd(a, k - 1); } int atMostOdd(int[] a, int k) { if (k < 0) return 0; int l = 0, odd = 0, ans = 0; for (int r = 0; r < a.length; r++) { if ((a[r] & 1) == 1) odd++; while (odd > k) { if ((a[l++] & 1) == 1) odd--; } ans += r - l + 1; } return ans; } ``` **Dry run** `[1,1,2,1,1]`, k=3 → 2. | r | window odds | ans contrib | | --- | --- | --- | | atMost 3 vs 2 | difference 2 | 2 | TC: O(n). SC: O(1). **If you get stuck:** prefix odds + HashMap. --- ### Maximum Rectangle all 1s — mapped R2 (OA-as-R1) — UTA N — [igreaper](https://igreaper.medium.com/amazon-sde-1-interview-experience-a69578a4f699) **What they actually asked:** Maximum Rectangle all 1s. Candidate R3 → our R2 (with Rotten — A-1). **Clarify out loud** - Largest area rectangle of 1s in a binary matrix? (histogram stack) - Or largest square? (different DP) **Trick / pattern in one sentence:** For each row, treat consecutive 1s as histogram heights; largest rectangle in histogram via monotonic stack. **Why this data structure** - brute: O(m²n²) check all rectangles - optimal: O(mn) heights + O(n) stack per row - refuse: only maximal square DP unless they said square **Brute** ```java int maximalRectangleBrute(char[][] g) { int m = g.length, n = g[0].length, best = 0; for (int r1 = 0; r1 < m; r1++) for (int r2 = r1; r2 < m; r2++) for (int c1 = 0; c1 < n; c1++) for (int c2 = c1; c2 < n; c2++) { boolean ok = true; for (int i = r1; i <= r2 && ok; i++) for (int j = c1; j <= c2; j++) if (g[i][j] != '1') { ok = false; break; } if (ok) best = Math.max(best, (r2 - r1 + 1) * (c2 - c1 + 1)); } return best; } ``` TC: O(m²n² · mn). Fails. **Optimal** ```java int maximalRectangle(char[][] g) { int m = g.length, n = g[0].length, best = 0; int[] h = new int[n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) h[j] = g[i][j] == '1' ? h[j] + 1 : 0; best = Math.max(best, largestRectangle(h)); } return best; } int largestRectangle(int[] h) { int n = h.length, best = 0; ArrayDeque st = new ArrayDeque<>(); for (int i = 0; i <= n; i++) { int cur = i == n ? 0 : h[i]; while (!st.isEmpty() && cur < h[st.peek()]) { int height = h[st.pop()]; int L = st.isEmpty() ? -1 : st.peek(); best = Math.max(best, height * (i - L - 1)); } st.push(i); } return best; } ``` **Dry run** row heights `[2,0,2,1,1]` → largest 3 (last three width 3 height 1) or 2×1s. TC: O(mn). SC: O(n). **If you get stuck:** “histogram per row, stack.” --- ### Split Array Largest Sum — mapped R2 — UTA N — [LC 6630775](https://leetcode.com/discuss/post/6630775/amazon-sde1-round-2-by-harry_potter_10-zubi/) **What they actually asked:** Split Array Largest Sum (LC linked). Same R2 as Remove K Digits. OA-as-R1 phone then this live. **Clarify out loud** - Split into **m** non-empty contiguous parts; minimize the max part sum? - m vs k naming? **Trick / pattern in one sentence:** Binary search the max-sum; greedy count how many parts you need. **Why this data structure** - brute: DP `dp[i][k]` min-max split O(n² m) - optimal: BS-on-answer O(n log sum) - refuse: random splits **Brute DP** ```java int splitBrute(int[] a, int k) { int n = a.length; int[] pref = new int[n + 1]; for (int i = 0; i < n; i++) pref[i + 1] = pref[i] + a[i]; int[][] dp = new int[n + 1][k + 1]; for (int[] row : dp) Arrays.fill(row, Integer.MAX_VALUE / 4); dp[0][0] = 0; for (int i = 1; i <= n; i++) for (int p = 1; p <= Math.min(k, i); p++) for (int t = 0; t < i; t++) dp[i][p] = Math.min(dp[i][p], Math.max(dp[t][p - 1], pref[i] - pref[t])); return dp[n][k]; } ``` TC: O(n² k). SC: O(nk). **Optimal** ```java int splitArray(int[] a, int k) { int lo = 0, hi = 0; for (int x : a) { lo = Math.max(lo, x); hi += x; } while (lo < hi) { int mid = lo + (hi - lo) / 2; if (parts(a, mid) <= k) hi = mid; else lo = mid + 1; } return lo; } int parts(int[] a, int cap) { int cnt = 1, s = 0; for (int x : a) { if (s + x > cap) { cnt++; s = 0; } s += x; } return cnt; } ``` **Dry run** `[7,2,5,10,8]`, k=2: cap 18 works (7+2+5 and 10+8). TC: O(n log sum). SC: O(1). **If you get stuck:** “same as Capacity to Ship — BS the bottleneck.” --- ### jumps / max reachable index DP UNNAMED — mapped R2 — UTA N — [LC 8029194](https://leetcode.com/discuss/post/8029194/amazon-interview-sde-1-selected-by-anony-qatd/) **What they actually asked:** maximum reachable index / jumps DP **UNNAMED**. Pattern only — do not stamp Jump Game / LC 45 / 55. **Clarify:** Can you jump `a[i]` steps from i? Reach last index boolean, or min jumps, or farthest index? **Pattern:** greedy farthest (`end`, `farthest`, `jumps`) or DP `dp[i] = min jumps to i`. ```java boolean canReach(int[] a) { // boolean family int far = 0; for (int i = 0; i < a.length; i++) { if (i > far) return false; far = Math.max(far, i + a[i]); } return true; } int minJumps(int[] a) { // min-jumps family int jumps = 0, end = 0, far = 0; for (int i = 0; i < a.length - 1; i++) { far = Math.max(far, i + a[i]); if (i == end) { jumps++; end = far; } } return jumps; } ``` TC: O(n). SC: O(1). Ask which of the two they want, then dry-run `[2,3,1,1,4]`. --- ### Binary search ### Capacity to Ship Packages Within D Days — mapped R1 (7563011 similar) — AUTA Y — [LC 6806195](https://leetcode.com/discuss/post/6806195/amazon-auta-interview-experience-sde-1-2-f90u/) **What they actually asked:** Capacity to Ship Packages Within D Days (LC linked). AUTA Bengaluru R1 with Asteroid similar. Reprint: [LC 7563011](https://leetcode.com/discuss/post/7563011/amazon-sde-1-interview-experience-by-ano-duqw/) R1 **similar to** Capacity to Ship + Rotten (Rotten A-1). **Clarify out loud** - Packages in order (cannot reorder)? - Days = D consecutive days, each day capacity `cap`? - Minimize `cap`? **Trick / pattern in one sentence:** BS capacity in `[max(weight), sum]`; greedy count days needed. **Why this data structure** - brute: try every cap - optimal: BS-on-answer + linear feasible - refuse: DP split (same as Split Array Largest Sum — that card) unless D is tiny **Brute** ```java int shipBrute(int[] w, int days) { int lo = 0, hi = 0; for (int x : w) { lo = Math.max(lo, x); hi += x; } for (int cap = lo; cap <= hi; cap++) if (daysNeeded(w, cap) <= days) return cap; return hi; } ``` TC: O((sum−max) · n). Fails large sums. **Optimal** ```java int shipWithinDays(int[] w, int days) { int lo = 0, hi = 0; for (int x : w) { lo = Math.max(lo, x); hi += x; } while (lo < hi) { int mid = lo + (hi - lo) / 2; if (daysNeeded(w, mid) <= days) hi = mid; else lo = mid + 1; } return lo; } int daysNeeded(int[] w, int cap) { int d = 1, s = 0; for (int x : w) { if (s + x > cap) { d++; s = 0; } s += x; } return d; } ``` **Dry run** `[1,2,3,4,5,6,7,8,9,10]`, days=5 → 15. | cap | days needed | | --- | --- | | 15 | 5 | | 14 | 6 | TC: O(n log sum). SC: O(1). **If you get stuck:** “feasible(mid) is the interview.” Same skeleton as Split Array / Aggressive Cows / power allocation. --- ### Search in Rotated Sorted Array — mapped R1 — UTA N — [LC 6461439](https://leetcode.com/discuss/post/6461439/amazon-sde-1-feb-2025-interview-experien-wv10/) **What they actually asked:** Search in Rotated Sorted Array. Reprints: [LC 8014509](https://leetcode.com/discuss/post/8014509/amazon-sde-1-interview-experience-by-pra-azvd/) R1 LC linked (with circular Kadane). **Clarify out loud** - Distinct vs duplicates (if dups, worst O(n) shrink)? - Return index or boolean? - Rotation count unknown? **Trick / pattern in one sentence:** One BS: the sorted half is the one where `a[lo] <= a[mid]`; go into the half that can contain target. **Why this data structure** - brute: linear scan - optimal: modified BS - refuse: unrotate then BS (O(n) find pivot is OK as a fallback) **Brute** ```java int searchBrute(int[] a, int t) { for (int i = 0; i < a.length; i++) if (a[i] == t) return i; return -1; } ``` TC: O(n). SC: O(1). **Optimal** (distinct) ```java int search(int[] a, int t) { int lo = 0, hi = a.length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (a[mid] == t) return mid; if (a[lo] <= a[mid]) { if (a[lo] <= t && t < a[mid]) hi = mid - 1; else lo = mid + 1; } else { if (a[mid] < t && t <= a[hi]) lo = mid + 1; else hi = mid - 1; } } return -1; } ``` **Dry run** `[4,5,6,7,0,1,2]`, t=0: mid 7, right half unsorted contains 0. | lo | hi | mid | a[mid] | | --- | --- | --- | --- | | 0 | 6 | 3 | 7 | | 4 | 6 | 5 | 1 | | 4 | 4 | 4 | 0 | TC: O(log n). SC: O(1). **If you get stuck:** find pivot with BS, then BS in the correct side. --- ### Aggressive Cows — mapped R2 — UTA N — [LC 7724048](https://leetcode.com/discuss/post/7724048/amazon-sde-1-interview-experience-by-ano-t6fz/) **What they actually asked:** Aggressive Cows (R2). Same IE R1 Detonate Bombs, R3 Next Greater. **Clarify out loud** - Place `k` cows in sorted stalls; maximize minimum pairwise distance? - One cow per stall? **Trick / pattern in one sentence:** Sort stalls; BS the min-distance; greedy place next cow at `last + mid`. **Why this data structure** - brute: try distances from high to low - optimal: BS-on-answer - refuse: DP subsets of stalls unless k tiny **Brute** — for d from max gap down to 1, first feasible. TC: O(maxGap · n). **Optimal** ```java int aggressiveCows(int[] stalls, int k) { Arrays.sort(stalls); int lo = 0, hi = stalls[stalls.length - 1] - stalls[0], ans = 0; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (canPlace(stalls, k, mid)) { ans = mid; lo = mid + 1; } else hi = mid - 1; } return ans; } boolean canPlace(int[] s, int k, int dist) { int cnt = 1, last = s[0]; for (int i = 1; i < s.length; i++) { if (s[i] - last >= dist) { cnt++; last = s[i]; } } return cnt >= k; } ``` **Dry run** stalls `[1,2,4,8,9]`, k=3 → 3 (1,4,9 or 1,4,8). | mid | place? | | --- | --- | | 4 | no (1, then 8, then 12 out) | | 3 | yes | TC: O(n log n + n log range). SC: O(1) besides sort. **If you get stuck:** “monotonic: if dist d works, d−1 works.” --- ### Single element in sorted array — mapped R2 — UTA N — [LC 6475219](https://leetcode.com/discuss/post/6475219/amazon-sde-1-interview-experience-bangal-4aa6/) **What they actually asked:** Single Element from sorted array. Same R2 as remove consecutive LL nodes sum 0. **Clarify out loud** - Every element twice except one? Sorted? - XOR vs log n required? **Trick / pattern in one sentence:** Pairs occupy even-odd indices until the single; BS on even index. **Why this data structure** - brute: XOR all O(n) — correct but not log n - optimal: BS - refuse: HashMap **Brute** ```java int singleBrute(int[] a) { int x = 0; for (int v : a) x ^= v; return x; } ``` TC: O(n). SC: O(1). Fine if they do not require log n. **Optimal** ```java int singleNonDuplicate(int[] a) { int lo = 0, hi = a.length - 1; while (lo < hi) { int mid = lo + (hi - lo) / 2; if ((mid & 1) == 1) mid--; // even if (a[mid] == a[mid + 1]) lo = mid + 2; else hi = mid; } return a[lo]; } ``` **Dry run** `[1,1,2,3,3,4,4,8,8]`: mid even 4, a[4]==a[5]=3, go right; eventually 2. TC: O(log n). SC: O(1). **If you get stuck:** XOR first, then “even-index partner.” --- ### Power allocation max-min (BS-on-answer) — mapped R1 — UTA N — [LC 7850431](https://leetcode.com/discuss/post/7850431/amazon-sde-1-interview-experience-by-imx-xitu/) **What they actually asked:** power allocation max-min (BS-on-answer) — snippet only. Same R1 as Cheapest Flights similar. **Clarify out loud** - Allocate integer power to n devices from a budget? Maximize the **minimum** allocated? - Constraints: each device min 1? some cannot exceed cap[i]? - Contiguous? (if it is split-array style, reuse that predicate) **Trick / pattern in one sentence:** Maximize `mid` such that `canAllocate(mid)` is true — same monotonic pattern as cows / ship. **Why this data structure** - brute: try minPower downward - optimal: BS + greedy/check - refuse: inventing a LeetCode id for this snippet **Brute** — for x from sum/n down to 0, first feasible. **Optimal** — template after they state the constraint. Example: budget `P`, n devices, each gets ≥ x, leftover free: ```java int maxMinPower(int n, int P) { int lo = 0, hi = P, ans = 0; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if ((long) mid * n <= P) { ans = mid; lo = mid + 1; } else hi = mid - 1; } return ans; } ``` If devices have demand windows or stations on a line, `can(mid)` becomes greedy place / prefix — **write `can` with them**. Dry-run a tiny P,n they give. TC: O(check · log range). SC: O(1) or O(n) for the check. **If you get stuck:** “I’ll binary search the minimum power and write a boolean checker.” --- ### sqrt + 8 decimals — mapped R1 — UTA N — [LC 6573582](https://leetcode.com/discuss/post/6573582/amazon-sde-1-bangalore-offer-by-anonymou-92zg/) **What they actually asked:** square root + **8 decimal** precision. Same R1 as GetRandom O(1) + duplicates. **Clarify out loud** - Integer n or double? Print 8 digits after decimal? - Newton vs BS on real range? **Trick / pattern in one sentence:** Binary search `double` in `[0, max(1,n)]` until `hi-lo < 1e-9` (one extra digit of safety). **Why this data structure** - brute: increment 0.00000001 — too slow - optimal: real BS or Newton - refuse: `Math.sqrt` without discussing precision unless they allow it — then still format 8 decimals **Brute** ```java double sqrtBrute(double n) { double x = 0; while (x * x <= n) x += 1e-8; return x - 1e-8; } ``` TC: O(n · 1e8). Unusable. **Optimal** ```java double sqrt8(double n) { if (n < 0) throw new IllegalArgumentException(); double lo = 0, hi = Math.max(1.0, n); for (int i = 0; i < 80; i++) { // 80 iters << 1e-8 double mid = (lo + hi) / 2; if (mid * mid <= n) lo = mid; else hi = mid; } return lo; } String print8(double n) { return String.format("%.8f", sqrt8(n)); } ``` Newton sidecar: ```java double newton(double n) { double x = n > 1 ? n : 1; for (int i = 0; i < 40; i++) x = 0.5 * (x + n / x); return x; } ``` **Dry run** n=2 → 1.41421356… | iter | mid | mid² vs 2 | | --- | --- | --- | | first | 1 | 1 < 2 | | … | ~1.41421356 | ≈2 | TC: O(80) or O(log(n/eps)). SC: O(1). **If you get stuck:** integer sqrt BS first, then “same on doubles.” --- ### Sliding window / string / hash ### Generate all subsets — mapped R1 — AUTA Y — [LC 7406809](https://leetcode.com/discuss/post/7406809/amazon-sde-1-auta-interview-experience-s-k6t7/) **What they actually asked:** Generate all subsets (LC linked). Same R1 as Top K Frequent. **Clarify out loud** - Distinct nums? If dups, unique subsets only? - Include empty set? - Return list of lists? **Trick / pattern in one sentence:** Backtrack include/exclude, or bitmasks 0..(1<> subsetsBits(int[] a) { int n = a.length; List> ans = new ArrayList<>(); for (int m = 0; m < (1 << n); m++) { List cur = new ArrayList<>(); for (int i = 0; i < n; i++) if ((m & (1 << i)) != 0) cur.add(a[i]); ans.add(cur); } return ans; } ``` **Optimal backtrack** (Live-Code friendly) ```java List> subsets(int[] a) { List> ans = new ArrayList<>(); back(a, 0, new ArrayList<>(), ans); return ans; } void back(int[] a, int i, List path, List> ans) { if (i == a.length) { ans.add(new ArrayList<>(path)); return; } back(a, i + 1, path, ans); path.add(a[i]); back(a, i + 1, path, ans); path.remove(path.size() - 1); } ``` **Dry run** `[1,2]`: `[] [2] [1] [1,2]`. TC: O(n · 2^n). SC: O(n) stack + output. **If you get stuck:** nested loops for n≤3 then “bitmask.” --- ### Group anagrams (LC 49 mods) — mapped R1 — UTA N — [Sachin](https://www.linkedin.com/posts/sachinchoudhary0_amazon-interview-experience-sde1-applied-activity-7465822262709886976-lgWi) **What they actually asked:** LC **49** group anagrams **small modifications**. Same R1 as m most frequent (Top-K card). **Clarify out loud** - What modification? (unicode? return map? sort groups? ignore case?) - Empty strings? **Trick / pattern in one sentence:** HashMap from canonical key (sorted chars or 26-count) to list. **Why this data structure** - brute: pairwise anagram checks O(n² · L) - optimal: map of key → list - refuse: sorting the whole list of words as the only step (that groups nothing unless you sort by key) **Brute** ```java boolean ana(String a, String b) { if (a.length() != b.length()) return false; int[] c = new int[26]; for (int i = 0; i < a.length(); i++) { c[a.charAt(i) - 'a']++; c[b.charAt(i) - 'a']--; } for (int x : c) if (x != 0) return false; return true; } ``` **Optimal** ```java List> groupAnagrams(String[] strs) { Map> m = new HashMap<>(); for (String s : strs) { int[] c = new int[26]; for (int i = 0; i < s.length(); i++) c[s.charAt(i) - 'a']++; StringBuilder sb = new StringBuilder(); for (int x : c) sb.append(x).append('#'); m.computeIfAbsent(sb.toString(), z -> new ArrayList<>()).add(s); } return new ArrayList<>(m.values()); } ``` **Dry run** `eat tea tan ate nat bat` → three groups. TC: O(n L). SC: O(n L). **If you get stuck:** sort each string as key. --- ### Longest Repeating Character Replacement (LC 424) — mapped R1 — UTA N Job 3057703 — [Prince](https://medium.com/@princepandey20022002/amazon-sde-1-interview-experience-off-campus-57825c172e2f) **What they actually asked:** Longest Repeating Character Replacement **variation**, **LC 424** linked. Off-campus Job 3057703. **Clarify out loud** - At most k replacements to make the window one letter? - Uppercase only? **Trick / pattern in one sentence:** Sliding window; window is valid while `len - maxFreq <= k`. **Why this data structure** - brute: try all windows, count majority - optimal: two pointers + 26-count - refuse: DP O(n²) **Brute** ```java int brute(String s, int k) { int n = s.length(), best = 0; for (int i = 0; i < n; i++) { int[] c = new int[26]; int mx = 0; for (int j = i; j < n; j++) { mx = Math.max(mx, ++c[s.charAt(j) - 'A']); if (j - i + 1 - mx <= k) best = Math.max(best, j - i + 1); } } return best; } ``` TC: O(n²). SC: O(1). **Optimal** ```java int characterReplacement(String s, int k) { int[] c = new int[26]; int l = 0, mx = 0, best = 0; for (int r = 0; r < s.length(); r++) { mx = Math.max(mx, ++c[s.charAt(r) - 'A']); while (r - l + 1 - mx > k) c[s.charAt(l++) - 'A']--; best = Math.max(best, r - l + 1); } return best; } ``` **Dry run** `AABABBA`, k=1 → 4 (`AABA` or `ABBA`). TC: O(n). SC: O(1). **If you get stuck:** “window − majority ≤ k.” --- ### Longest subarray sum = 0 — mapped R2 — UTA N — [LC 7850431](https://leetcode.com/discuss/post/7850431/amazon-sde-1-interview-experience-by-imx-xitu/) **What they actually asked:** longest subarray sum = 0. Same R2 as Connect Sticks (A-1). **Clarify out loud** - Longest length or the subarray itself? - Negatives present? (yes — otherwise trivial) **Trick / pattern in one sentence:** Prefix sums; HashMap first index of each prefix; if `pref` seen, length = i − first[pref]; also `pref==0` → i+1. **Why this data structure** - brute: all i,j sums - optimal: prefix + HashMap - refuse: sliding window assuming positives **Brute** ```java int longest0Brute(int[] a) { int n = a.length, best = 0; for (int i = 0; i < n; i++) { int s = 0; for (int j = i; j < n; j++) { s += a[j]; if (s == 0) best = Math.max(best, j - i + 1); } } return best; } ``` TC: O(n²). SC: O(1). **Optimal** ```java int longestZeroSum(int[] a) { Map first = new HashMap<>(); first.put(0, -1); int pref = 0, best = 0; for (int i = 0; i < a.length; i++) { pref += a[i]; if (first.containsKey(pref)) best = Math.max(best, i - first.get(pref)); else first.put(pref, i); } return best; } ``` **Dry run** `[15,−2,2,−8,1,7,10,23]` → 5 (`−2..7`). | i | pref | first | best | | --- | --- | --- | --- | | 0 | 15 | 15→0 | 0 | | 1 | 13 | 13→1 | 0 | | 2 | 15 | seen 0 | 2 | TC: O(n). SC: O(n). **If you get stuck:** brute; then “same prefix means the middle sums to 0.” --- ### Variation of Find All Anagrams — mapped R3 HM — AUTA Y — [LC 8362604](https://leetcode.com/discuss/post/8362604/amazon-sde-1-interview-experience-auta-a-5wmt/) **What they actually asked:** Variation of Find All Anagrams. Same HM as Combine Garlands. **Variation — do not stamp exact LC 438 as asked.** **Clarify out loud** - Sliding window of p’s length, all start indices of anagrams of p in s? Extra constraint? **Trick / pattern in one sentence:** Window count of 26 letters; match when counts equal (or `need==0` counter). **Why this data structure** - brute: sort every window - optimal: sliding count - refuse: regex **Brute** ```java List brute(String s, String p) { char[] need = p.toCharArray(); Arrays.sort(need); String key = new String(need); List ans = new ArrayList<>(); for (int i = 0; i + p.length() <= s.length(); i++) { char[] w = s.substring(i, i + p.length()).toCharArray(); Arrays.sort(w); if (key.equals(new String(w))) ans.add(i); } return ans; } ``` TC: O((n−m) m log m). SC: O(m). **Optimal** ```java List findAnagrams(String s, String p) { int[] need = new int[26], win = new int[26]; for (int i = 0; i < p.length(); i++) need[p.charAt(i) - 'a']++; List ans = new ArrayList<>(); int m = p.length(); for (int i = 0; i < s.length(); i++) { win[s.charAt(i) - 'a']++; if (i >= m) win[s.charAt(i - m) - 'a']--; if (i >= m - 1 && Arrays.equals(need, win)) ans.add(i - m + 1); } return ans; } ``` **Dry run** s=`cbaebabacd` p=`abc` → `[0,6]`. TC: O(n). SC: O(1). **If you get stuck:** sort windows; then 26-count. --- ### Longest Valid Parentheses — mapped R1 — UTA N — [LC 6606011](https://leetcode.com/discuss/post/6606011/amazon-sde-1-interview-experience-27-mar-ermb/) **What they actually asked:** Print **largest** valid parentheses. Prior note: example `()(())))) → ()(())`. Day 1 with Median of Two Sorted Arrays. **Clarify out loud** - Longest **length**, or the **substring** itself (they said print)? - Only `(` `)`? **Trick / pattern in one sentence:** Stack of indices (base −1); or DP `dp[i]` length ending at i. **Why this data structure** - brute: all substrings, check valid - optimal: stack of last unmatched, or two-pass left-right counts - refuse: regex **Brute** ```java boolean valid(String s, int l, int r) { int b = 0; for (int i = l; i <= r; i++) { if (s.charAt(i) == '(') b++; else b--; if (b < 0) return false; } return b == 0; } ``` TC: O(n³). Fails. **Optimal** — return substring (print): ```java String longestValid(String s) { int n = s.length(), bestL = 0, bestI = 0; ArrayDeque st = new ArrayDeque<>(); st.push(-1); for (int i = 0; i < n; i++) { if (s.charAt(i) == '(') st.push(i); else { st.pop(); if (st.isEmpty()) st.push(i); else { int len = i - st.peek(); if (len > bestL) { bestL = len; bestI = st.peek() + 1; } } } } return s.substring(bestI, bestI + bestL); } ``` **Dry run** `()(()))))` → `()(())` length 6. | i | stack | best | | --- | --- | --- | | 0 `(` | -1,0 | | | 1 `)` | -1 | 2 | | … | | 6 at `()(())` | TC: O(n). SC: O(n). **If you get stuck:** DP `if s[i]==')' and match`. --- ### Count good-review words + sort reviews — mapped R1 — UTA N — [LC 6570344](https://leetcode.com/discuss/post/6570344/amazon-sde-1-loop-interview-by-anonymous-i0v6/) **What they actually asked:** count good-review words; sort reviews. Follow-ups: HashMap/HashSet internals; why PQ (bible §5.F). **Clarify out loud** - Good word = in a dictionary set? Count per review, then sort reviews by that count (then lex)? - Case fold? Punctuation? **Trick / pattern in one sentence:** `HashSet` dictionary + tokenize; `Arrays.sort` with comparator (or heap if top-k reviews). **Why this data structure** - brute: for each word, scan dictionary list - optimal: HashSet O(1) lookup; sort O(r log r) - they asked why PQ: use heap if they want **top k** reviews not a full sort **Brute** — dictionary as list, `contains` O(d). **Optimal** ```java class Review { String text; int good; } List sortReviews(String[] reviews, Set goodWords) { Review[] a = new Review[reviews.length]; for (int i = 0; i < reviews.length; i++) { int c = 0; for (String w : reviews[i].toLowerCase().split("\\W+")) if (!w.isEmpty() && goodWords.contains(w)) c++; a[i] = new Review(); a[i].text = reviews[i]; a[i].good = c; } Arrays.sort(a, (x, y) -> y.good != x.good ? y.good - x.good : x.text.compareTo(y.text)); List out = new ArrayList<>(); for (Review r : a) out.add(r.text); return out; } ``` **Dry run** dict `{good,great}`, reviews `"good product"`, `"ok"`, `"great great"` → counts 1,0,2. TC: O(total chars + r log r). SC: O(r). **If you get stuck:** count then `sort`. For “why PQ”: k ≪ r. --- ### GetRandom O(1) (insert/delete/search) — mapped R1 + R2 reprint — UTA N — [LC 6573582](https://leetcode.com/discuss/post/6573582/amazon-sde-1-bangalore-offer-by-anonymou-92zg/) **What they actually asked:** insert/search/delete/getRandom O(1) **+ duplicates** (6573582 R1). Reprint: [Reddit 1lqy9uq](https://old.reddit.com/r/leetcode/comments/1lqy9uq/amazon_sde1_interview_experience/) R2 GetRandom Insert/Delete/Search O(1). **One card.** **Clarify out loud** - Duplicates allowed? (6573582 yes) - getRandom uniform over values or over distinct? **Trick / pattern in one sentence:** `ArrayList` for random index; `HashMap` value → index (or value → `Set` of indices if dups). **Why this data structure** - brute: HashSet + convert to list for random O(n) - optimal: list + map; delete = swap with last - refuse: only HashMap — cannot O(1) uniform random **Brute** — `ArrayList.contains` delete O(n). **Optimal (distinct first, then dups)** ```java class RandomizedSet { List a = new ArrayList<>(); Map idx = new HashMap<>(); Random rnd = new Random(); boolean insert(int v) { if (idx.containsKey(v)) return false; idx.put(v, a.size()); a.add(v); return true; } boolean remove(int v) { if (!idx.containsKey(v)) return false; int i = idx.get(v), last = a.size() - 1; int x = a.get(last); a.set(i, x); idx.put(x, i); a.remove(last); idx.remove(v); return true; } int getRandom() { return a.get(rnd.nextInt(a.size())); } } class RandomizedCollection { // duplicates List a = new ArrayList<>(); Map> pos = new HashMap<>(); Random rnd = new Random(); boolean insert(int v) { pos.computeIfAbsent(v, z -> new HashSet<>()).add(a.size()); a.add(v); return pos.get(v).size() == 1; } boolean remove(int v) { if (!pos.containsKey(v) || pos.get(v).isEmpty()) return false; int i = pos.get(v).iterator().next(); pos.get(v).remove(i); int last = a.size() - 1, x = a.get(last); a.set(i, x); pos.get(x).add(i); pos.get(x).remove(last); a.remove(last); if (pos.get(v).isEmpty()) pos.remove(v); return true; } int getRandom() { return a.get(rnd.nextInt(a.size())); } } ``` **Dry run** insert 1,1,2; remove 1; getRandom over remaining [1,2] or [1,1,2] depending on one remove. TC: O(1) expected. SC: O(n). **If you get stuck:** “array for random, map for index, swap-pop delete.” --- ### Encoded string `1226#24#(2)` letter freq — mapped R1 (OA-as-R1) — AUTA Y — [LC 6800853](https://leetcode.com/discuss/post/6800853/amazon-interview-experience-sde1-by-anon-vdbd/) **What they actually asked:** encoded string `1226#24#(2)` → freq of letters. Grid paths / subtract-digit are A-1. **Grammar was not fully specified in the IE — confirm before coding.** **Clarify out loud** - `1`–`9` → a–i; `10#`–`26#` → j–z? - `(k)` = frequency of the **previous token**? - Output map of letter → count? **Trick / pattern in one sentence:** This is a **parse**, then HashMap; do not start with HashMap. **Why this data structure** - brute: regex guesses - optimal: index `i`, parse number, optional `#`, optional `(freq)` - refuse: inventing an LC id **Brute** — hand-parse the example only. Fails other encodings. **Brute** ```java // Walk the given example by hand; no general brute without a grammar. Map freqExampleOnly() { Map m = new HashMap<>(); m.put('a', 1); m.put('b', 1); m.put('z', 1); m.put('x', 2); // 1226#24#(2) return m; } ``` **Optimal** — grammar assumed from the example (state it): `d` = a–i; `dd#` = j–z; `(k)` multiplies the token just parsed. ```java Map freqEncoded(String s) { Map map = new HashMap<>(); int i = 0, n = s.length(); while (i < n) { int code, j; if (i + 2 < n && Character.isDigit(s.charAt(i)) && Character.isDigit(s.charAt(i + 1)) && s.charAt(i + 2) == '#') { code = Integer.parseInt(s.substring(i, i + 2)); j = i + 3; } else { code = s.charAt(i) - '0'; j = i + 1; } int times = 1; if (j < n && s.charAt(j) == '(') { int k = j + 1; while (k < n && s.charAt(k) != ')') k++; times = Integer.parseInt(s.substring(j + 1, k)); j = k + 1; } map.merge((char) ('a' + code - 1), times, Integer::sum); i = j; } return map; } ``` **Dry run** `1226#24#(2)`: `1`→a, `2`→b, `26#`→z, `24#(2)`→x×2. | token | letter | count | | --- | --- | --- | | 1 | a | 1 | | 2 | b | 1 | | 26# | z | 1 | | 24#(2) | x | 2 | TC: O(n). SC: O(1) alphabet. **If you get stuck:** walk the example token by token on the whiteboard first. --- ### k-th largest from index `[k,n]` — mapped R1 (OA-as-R1) — AUTA Y — [LC 6800853](https://leetcode.com/discuss/post/6800853/amazon-interview-experience-sde1-by-anon-vdbd/) **What they actually asked:** k-th largest from index `[k,n]` sample `[4,2,1,3]` k=2 → `[2,2,3]`. **Clarify out loud** - For each right endpoint i in `[k..n]` (1-based), k-th largest in prefix `a[0..i-1]`? **Trick / pattern in one sentence:** Stream prefixes with a size-k min-heap; after i≥k, heap top is k-th largest of the prefix. **Why this data structure** - brute: sort prefix each i - optimal: min-heap size k - refuse: full sort of the array once (wrong prefixes) **Brute** ```java int[] kthPrefixesBrute(int[] a, int k) { int n = a.length; int[] ans = new int[n - k + 1]; for (int i = k; i <= n; i++) { int[] p = Arrays.copyOf(a, i); Arrays.sort(p); ans[i - k] = p[i - k]; // k-th largest = index i-k } return ans; } ``` TC: O(n² log n). Sample: prefixes [4,2] → 2nd largest 2; [4,2,1]→2; [4,2,1,3]→3. Matches. **Optimal** ```java int[] kthFromKtoN(int[] a, int k) { PriorityQueue min = new PriorityQueue<>(); int[] ans = new int[a.length - k + 1]; int p = 0; for (int i = 0; i < a.length; i++) { min.offer(a[i]); if (min.size() > k) min.poll(); if (i >= k - 1) ans[p++] = min.peek(); } return ans; } ``` **Dry run** `[4,2,1,3]` k=2 | i | heap | emit | | --- | --- | --- | | 0 | [4] | | | 1 | [2,4] | 2 | | 2 | [2,4] (1 dropped) | 2 | | 3 | [3,4] (2 dropped) | 3 | TC: O(n log k). SC: O(k). **If you get stuck:** sort prefixes; then heap. --- ### Sum of a very long string — mapped R1 — AUTA Y — [Nisarg](https://www.linkedin.com/posts/nisarg-patel-80361a184_amazon-auta-interviewexperience-activity-7361081215673585664-ZGfa) **What they actually asked:** Sum of a very long string. AUTA same-day 31 Jul 2025. Same R1 as k-page visit (verbal). **Clarify out loud** - Two numeric strings that do not fit in `long`? Or sum of numbers split by commas? Or digit-sum? - Leading zeros? Negative? **Trick / pattern in one sentence:** If it is big-integer add, add from the right with carry; store digits in `StringBuilder`. **Why this data structure** - brute: `new BigInteger` — OK if they allow; say you can write it - optimal: two pointers from the end - refuse: parse `Long.parseLong` — they said *very long* **Brute** ```java String sumBrute(String a, String b) { return new java.math.BigInteger(a).add(new java.math.BigInteger(b)).toString(); } ``` **Optimal** ```java String addStrings(String a, String b) { StringBuilder sb = new StringBuilder(); int i = a.length() - 1, j = b.length() - 1, carry = 0; while (i >= 0 || j >= 0 || carry > 0) { int x = i >= 0 ? a.charAt(i--) - '0' : 0; int y = j >= 0 ? b.charAt(j--) - '0' : 0; int s = x + y + carry; sb.append(s % 10); carry = s / 10; } return sb.reverse().toString(); } ``` **Dry run** `999` + `1` → `1000`. | i,j | x+y+c | write | | --- | --- | --- | | 2,0 | 10 | 0 carry 1 | | 1 | 10 | 0 carry 1 | | 0 | 10 | 0 carry 1 | | done | 1 | 1 | TC: O(max(L1,L2)). SC: O(L). **If you get stuck:** add on paper from the right. --- ### k-page visit sequence — mapped R1 — AUTA Y — [Nisarg](https://www.linkedin.com/posts/nisarg-patel-80361a184_amazon-auta-interviewexperience-activity-7361081215673585664-ZGfa) **What they actually asked:** multiple users visiting k pages in sequence (SW+hashmap; **verbal**). Related reprint: LC 6573582 BR “most frequent 3-page sequence.” **Clarify out loud** - Per user a list of pages; count k-grams globally? Most frequent k-sequence? - Consecutive visits only? **Trick / pattern in one sentence:** Sliding window of k page-ids; HashMap sequence → count; track max. **Why this data structure** - brute: all windows, recount - optimal: one pass HashMap - refuse: trie unless alphabet huge and they ask prefix **Brute** — for each user, for each i, join pages i..i+k-1, count with nested loops. **Optimal** ```java String mostFrequentK(List> users, int k) { Map freq = new HashMap<>(); int best = 0; String ans = ""; for (List seq : users) { for (int i = 0; i + k <= seq.size(); i++) { String key = String.join(">", seq.subList(i, i + k)); int c = freq.merge(key, 1, Integer::sum); if (c > best) { best = c; ans = key; } } } return ans; } ``` **Dry run** k=2, user `[A,B,A,B]`: AB, BA, AB → AB wins with 2. TC: O(total visits · k) if concatenating. SC: O(windows). **If you get stuck:** “k-gram counts, HashMap.” --- ### Remove K Digits — mapped R2 — UTA N — [LC 6630775](https://leetcode.com/discuss/post/6630775/amazon-sde1-round-2-by-harry_potter_10-zubi/) **What they actually asked:** Remove K Digits (LC linked). Same R2 as Split Array Largest Sum. **Clarify out loud** - Remove exactly k digits to form the **smallest** possible number? Keep order? - Leading zeros? **Trick / pattern in one sentence:** Monotonic increasing stack; pop last digit while it is bigger than the current and k>0. **Why this data structure** - brute: all subsets of deletions C(n,k) - optimal: stack greedy - refuse: sort digits (order must stay) **Brute** — recurse keep/drop. O(2^n). **Optimal** ```java String removeKdigits(String num, int k) { StringBuilder st = new StringBuilder(); for (int i = 0; i < num.length(); i++) { char c = num.charAt(i); while (k > 0 && st.length() > 0 && st.charAt(st.length() - 1) > c) { st.deleteCharAt(st.length() - 1); k--; } st.append(c); } while (k-- > 0 && st.length() > 0) st.deleteCharAt(st.length() - 1); int i = 0; while (i < st.length() && st.charAt(i) == '0') i++; String ans = st.substring(i); return ans.isEmpty() ? "0" : ans; } ``` **Dry run** `1432219`, k=3 → `1219`. | c | stack | k | | --- | --- | --- | | 1 | 1 | 3 | | 4 | 14 | 3 | | 3 | 13 | 2 | | 2 | 12 | 1 | | 2 | 12 | 1 | | 1 | 121 | 0 | | 9 | 1219 | 0 | TC: O(n). SC: O(n). **If you get stuck:** “strip peaks from the left.” --- ### Word Ladder family CAT→MEN — mapped R4/BR-adj — UTA N — [sde-1-17](https://www.geeksforgeeks.org/interview-experiences/amazon-interview-experience-for-sde-1-17/) **What they actually asked:** Word Ladder family **CAT→MEN**. Short — full Word Ladder is A-1 (7035289). **Clarify:** word list, differ by 1 letter, shortest transform length? **Trick:** BFS, each word a node; neighbors = 26·L mutations in a `HashSet` dictionary. ```java int ladderLength(String begin, String end, List wordList) { Set dict = new HashSet<>(wordList); if (!dict.contains(end)) return 0; ArrayDeque q = new ArrayDeque<>(); q.offer(begin); int dist = 1; while (!q.isEmpty()) { for (int sz = q.size(); sz > 0; sz--) { String u = q.poll(); if (u.equals(end)) return dist; char[] c = u.toCharArray(); for (int i = 0; i < c.length; i++) { char orig = c[i]; for (char ch = 'A'; ch <= 'Z'; ch++) { // CAT/MEN were uppercase in the IE c[i] = ch; String v = new String(c); if (dict.remove(v)) q.offer(v); } c[i] = orig; } } dist++; } return 0; } ``` **Dry run** CAT → COT → COG? MEN: CAT-BAT-BET-MEN style. TC: O(n · L · 26). SC: O(n). --- ### Next Greater Element — mapped R3 HM — UTA N — [LC 7724048](https://leetcode.com/discuss/post/7724048/amazon-sde-1-interview-experience-by-ano-t6fz/) **What they actually asked:** Next Greater Element (R3 HM with GenAI). Same IE Aggressive Cows R2. **Clarify out loud** - Next greater to the **right** for each index? Circular? nums1 subset of nums2 (LC 496)? **Trick / pattern in one sentence:** Scan right-to-left; decreasing stack of candidates. **Why this data structure** - brute: nested j>i - optimal: monotonic stack - refuse: sort — loses positions **Brute** ```java int[] ngeBrute(int[] a) { int n = a.length; int[] ans = new int[n]; Arrays.fill(ans, -1); for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (a[j] > a[i]) { ans[i] = a[j]; break; } return ans; } ``` TC: O(n²). SC: O(1). **Optimal** ```java int[] nextGreater(int[] a) { int n = a.length; int[] ans = new int[n]; ArrayDeque st = new ArrayDeque<>(); for (int i = n - 1; i >= 0; i--) { while (!st.isEmpty() && st.peek() <= a[i]) st.pop(); ans[i] = st.isEmpty() ? -1 : st.peek(); st.push(a[i]); } return ans; } ``` **Dry run** `[2,1,2,4,3]` → `[4,2,4,-1,-1]`. TC: O(n). SC: O(n). **If you get stuck:** Daily Temperatures stack, but store values not deltas. --- ### Next palindromic number — mapped R2 — UTA N — [LC 7280347](https://leetcode.com/discuss/post/7280347/amazon-india-sde-1-interview-experience-2ogbw/) **What they actually asked:** Next Palindromic Number (R2 with Clone Graph). **Clarify out loud** - Next strictly greater integer that is palindrome? Input as string (big)? - Leading zeros? **Trick / pattern in one sentence:** Mirror left half onto right; if that is ≤ n, increment the left half (and middle) and remirror. **Why this data structure** - brute: n+1, n+2, … check palindrome - optimal: digit array mirror - refuse: treating as `int` if they pass 20-digit strings **Brute** ```java boolean pal(String s) { int i = 0, j = s.length() - 1; while (i < j) if (s.charAt(i++) != s.charAt(j--)) return false; return true; } String brute(String n) { java.math.BigInteger x = new java.math.BigInteger(n).add(java.math.BigInteger.ONE); while (!pal(x.toString())) x = x.add(java.math.BigInteger.ONE); return x.toString(); } ``` TC: up to O(length · gap). Bad near 999→1001 but OK small. **Optimal** ```java String nextPalindrome(String num) { int n = num.length(); char[] a = num.toCharArray(); char[] b = a.clone(); for (int i = 0; i < n / 2; i++) b[n - 1 - i] = b[i]; if (new String(b).compareTo(num) > 0) return new String(b); int i = (n - 1) / 2; while (i >= 0 && b[i] == '9') { b[i] = '0'; i--; } if (i < 0) { char[] c = new char[n + 1]; Arrays.fill(c, '0'); c[0] = c[n] = '1'; return new String(c); } b[i]++; for (int L = 0; L < n / 2; L++) b[n - 1 - L] = b[L]; return new String(b); } ``` **Dry run** `123` → mirror `121` ≤ 123 → increment mid → `131`. TC: O(L). SC: O(L). **If you get stuck:** brute +1; then “increment left half.” --- ### similar to Asteroid Collision — mapped R1 AUTA + Parimal R2 — UTA mixed — [LC 6806195](https://leetcode.com/discuss/post/6806195/amazon-auta-interview-experience-sde-1-2-f90u/) **What they actually asked:** similar to Asteroid Collision (LC linked similar) AUTA R1. Reprint: [Parimal](https://www.linkedin.com/posts/parimal-deshmukh-3388aa220_amazon-sde-interviewexperience-activity-7450042399520641024-EwzB) R2 named LeetCode Asteroid Collision. **One card. Similar-not-exact on 6806195.** **Clarify out loud** - Positive right, negative left? Same abs explode both; smaller abs dies? - Same direction never collide? **Trick / pattern in one sentence:** Stack of survivors; while top going right and new going left, collide. **Why this data structure** - brute: rescan list of collisions - optimal: stack - refuse: sort by position without a stack of survivors **Brute** — simulate rounds until stable O(n²). **Optimal** ```java int[] asteroidCollision(int[] a) { ArrayDeque st = new ArrayDeque<>(); for (int x : a) { boolean alive = true; while (alive && !st.isEmpty() && st.peek() > 0 && x < 0) { int top = st.peek(); if (top < -x) st.pop(); else if (top == -x) { st.pop(); alive = false; } else alive = false; } if (alive) st.push(x); } int[] ans = new int[st.size()]; for (int i = ans.length - 1; i >= 0; i--) ans[i] = st.pop(); return ans; } ``` **Dry run** `[5,10,-5]` → `[5,10]`. `[8,-8]` → `[]`. `[10,2,-5]` → `[10]`. TC: O(n). SC: O(n). **If you get stuck:** “only + meets − can collide.” --- ### Next permutation / next greater same digits (Prabhash) — mapped R1 — UTA N — [Prabhash](https://www.linkedin.com/posts/prabhash-jena_amazoninterview-sde1-interviewexperience-activity-7354481801756622848-C4v6) **What they actually asked:** Next permutation / next greater same digits. Dry run; TC/SC. **Not** the A-1 AUTA R2 “similar to Next Permutation (approach only)” on 6806195 — that pack is A-1. This is Prabhash’s **exact** R1 second question. **Clarify:** next permutation of the digit array, or next integer with same digits? **Trick:** find rightmost ascent `a[i] < a[i+1]`, swap with rightmost successor, reverse suffix. Cross-ref A-1 for the AUTA “approach only” version. ```java void nextPermutation(int[] a) { int n = a.length, i = n - 2; while (i >= 0 && a[i] >= a[i + 1]) i--; if (i >= 0) { int j = n - 1; while (a[j] <= a[i]) j--; int t = a[i]; a[i] = a[j]; a[j] = t; } for (int l = i + 1, r = n - 1; l < r; l++, r--) { int t = a[l]; a[l] = a[r]; a[r] = t; } } ``` **Dry run** `[1,3,2]` → `[2,1,3]`. TC: O(n). SC: O(1). **If you get stuck:** “pivot, swap successor, reverse tail.” --- ### Linked list / array ### Merge K Sorted Lists — Bhavya R1 reprint note only — UTA N — [Bhavya](https://www.linkedin.com/posts/bhavya-77816218a_amazon-interviewexperience-sde1-activity-7473680829714546688-jeL9) **A-1 owns the full Merge k sorted linked lists card** (AUTA 7563011 R2). Reprint: Bhavya 13 May 2026 **R1** also asked Merge K Sorted Lists. Same Java (heap of k heads, O(N log k)). Do not duplicate the A-1 implementation here. --- ### Max sum switching between two sorted linked lists — mapped R1 — UTA N — [LC 6369243](https://leetcode.com/discuss/post/6369243/amazon-sde-1-interview-experience-accept-kize/) **What they actually asked:** Max sum switching between two sorted linked lists. **Do not stamp LC 962** (Width Ramp) or LC 210. Same IE R2 = delivery stations + topo. **Clarify out loud** - Lists sorted? Switch only at **common node values**? - Result = max path sum (can start on either list)? - Build the list or return the sum? **Trick / pattern in one sentence:** Walk both lists in sorted order; accumulate a segment sum on each until a common value; add `max(sum1, sum2)` including the common node once; repeat. **Why this data structure** - brute: DFS switch at every equal node — exponential if many commons - optimal: two pointers like merge; GFG “maximum sum linked list from two sorted lists with common nodes” - refuse: converting to arrays then LC 962-style ramps **Brute** — recurse: at a node, either continue or jump if values match. Exponential. **Optimal** ```java int maxSumSwitch(ListNode a, ListNode b) { ListNode p = a, q = b; int s1 = 0, s2 = 0, ans = 0; while (p != null && q != null) { if (p.val < q.val) { s1 += p.val; p = p.next; } else if (q.val < p.val) { s2 += q.val; q = q.next; } else { ans += Math.max(s1, s2) + p.val; s1 = s2 = 0; p = p.next; q = q.next; } } while (p != null) { s1 += p.val; p = p.next; } while (q != null) { s2 += q.val; q = q.next; } ans += Math.max(s1, s2); return ans; } ``` **Dry run** ``` 1 → 3 → 30 → 90 → 110 → 120 0 → 3 → 12 → 32 → 90 → 100 → 120 → 130 ``` Commons 3, 90, 120. Segments: before 3: max(1,0)+3; 3→90: max(30,12+32)+90; 90→120: max(110,100)+120; after: max(0,130). Classic GFG answer **342**. | common | s1 | s2 | add | | --- | --- | --- | --- | | 3 | 1 | 0 | 1+3 | | 90 | 30 | 44 | 44+90 | | 120 | 110 | 100 | 110+120 | | tail | 0 | 130 | 130 | TC: O(n+m). SC: O(1). **If you get stuck:** merge-like two pointers; at equals take max segment. --- ### Remove consecutive LL nodes sum 0 — mapped R2 — UTA N — [LC 6475219](https://leetcode.com/discuss/post/6475219/amazon-sde-1-interview-experience-bangal-4aa6/) **What they actually asked:** Remove consecutive LL nodes sum 0. Same R2 as single element in sorted array. **Clarify out loud** - Delete every contiguous sublist whose sum is 0 (possibly nested / multiple)? - Can the whole list vanish? **Trick / pattern in one sentence:** Dummy + prefix sums; HashMap prefix → node; if prefix repeats, the nodes between sum to 0 — skip them and clean map. **Why this data structure** - brute: for each start, scan until sum 0, delete, restart - optimal: prefix map on dummy - refuse: stack of values without prefixes if negatives exist (still OK with stack of (node, pref) but map is cleaner) **Brute** ```java ListNode removeZeroBrute(ListNode head) { Dummy: while (true) { ListNode d = new ListNode(0, head); boolean cut = false; for (ListNode s = d; s.next != null; s = s.next) { int sum = 0; for (ListNode e = s.next; e != null; e = e.next) { sum += e.val; if (sum == 0) { s.next = e.next; cut = true; break; } } if (cut) { head = d.next; break; } } if (!cut) return head; } } ``` TC: restart can be O(n²) or worse. SC: O(1). **Optimal** ```java ListNode removeZeroSumSublists(ListNode head) { ListNode dummy = new ListNode(0, head); Map map = new HashMap<>(); int pref = 0; for (ListNode n = dummy; n != null; n = n.next) { pref += n.val; map.put(pref, n); // last occurrence } pref = 0; for (ListNode n = dummy; n != null; n = n.next) { pref += n.val; n.next = map.get(pref).next; } return dummy.next; } ``` **Dry run** `1,2,-3,3,1`: prefixes 0,1,3,0,3,4. First 0 maps to dummy then later to node after −3… two-pass last-index: `3,1`. TC: O(n). SC: O(n). **If you get stuck:** brute delete-and-restart; then prefix map. --- ### Min platforms — mapped R1 — UTA N — [Prabhash](https://www.linkedin.com/posts/prabhash-jena_amazoninterview-sde1-interviewexperience-activity-7354481801756622848-C4v6) **What they actually asked:** min platforms. Same R1 as next permutation same digits. Dry run; TC/SC. **Clarify out loud** - Arrival[] / departure[] of trains; how many platforms so no two overlap? - Inclusive endpoints (depart 10:00, arrive 10:00 → extra platform)? **Trick / pattern in one sentence:** Sort arrivals and departures; two pointers / sweep; track current trains. **Why this data structure** - brute: for each train count overlaps O(n²) - optimal: sort + sweep - refuse: heap of departures also works (same as “min meeting rooms”) **Brute** ```java int platformsBrute(int[] arr, int[] dep) { int n = arr.length, best = 0; for (int i = 0; i < n; i++) { int cur = 0; for (int j = 0; j < n; j++) if (arr[j] <= arr[i] && dep[j] >= arr[i]) cur++; best = Math.max(best, cur); } return best; } ``` TC: O(n²). SC: O(1). **Optimal** ```java int minPlatforms(int[] arr, int[] dep) { Arrays.sort(arr); Arrays.sort(dep); int i = 0, j = 0, cur = 0, best = 0; while (i < arr.length) { if (arr[i] <= dep[j]) { cur++; best = Math.max(best, cur); i++; } else { cur--; j++; } } return best; } ``` **Dry run** arr `900,940,950,1100` dep `910,1200,1120,1130` → 3. | event | cur | | --- | --- | | 900 arr | 1 | | 910 dep | 0 | | 940 arr | 1 | | 950 arr | 2 | | … | 3 | TC: O(n log n). SC: O(1) besides sort. **If you get stuck:** “meeting rooms / line sweep.” Reprint: LC 6573582 R2 GPU intervals “4 GPU=1 CPU min CPUs” is the same sweep. --- ### Merge Intervals — mapped R1 — UTA N — [GFG fresher](https://www.geeksforgeeks.org/interview-experiences/amazon-interview-experience-for-sde1-fresher-off-campus/) **What they actually asked:** Merge Intervals (with Burning Tree). **Clarify:** `[start,end]` inclusive? Touching merge (`[1,2][2,3]`)? **Trick:** Sort by start; if `cur.start <= last.end` merge ends. **Why DS:** brute pairwise until stable O(n²); optimal sort. **Brute** — while merged something, scan pairs. **Optimal** ```java int[][] merge(int[][] iv) { Arrays.sort(iv, (a, b) -> a[0] - b[0]); List out = new ArrayList<>(); int[] cur = iv[0]; for (int i = 1; i < iv.length; i++) { if (iv[i][0] <= cur[1]) cur[1] = Math.max(cur[1], iv[i][1]); else { out.add(cur); cur = iv[i]; } } out.add(cur); return out.toArray(new int[0][]); } ``` **Dry run** `[1,3][2,6][8,10]` → `[1,6][8,10]`. TC: O(n log n). SC: O(n). **If you get stuck:** sort then linear merge. --- ### Circular Kadane — mapped R1 — UTA N — [LC 8014509](https://leetcode.com/discuss/post/8014509/amazon-sde-1-interview-experience-by-pra-azvd/) **What they actually asked:** circular Kadane (with Search in Rotated Sorted Array). **Clarify out loud** - Max subarray sum, array wraps? - All negative → max element (cannot wrap the whole array as empty)? **Trick / pattern in one sentence:** `max(standard Kadane, total − min-subarray)`; if all negative, return max element. **Why this data structure** - brute: 2n window / duplicate array - optimal: one min Kadane + one max Kadane - refuse: heap **Brute** — concat `a+a`, Kadane with length ≤ n. TC: O(n²) if you cap length naively O(n) with deque. **Optimal** ```java int maxSubarraySumCircular(int[] a) { int total = 0, maxEnd = 0, minEnd = 0; int maxS = Integer.MIN_VALUE / 4, minS = Integer.MAX_VALUE / 4; for (int x : a) { total += x; maxEnd = Math.max(x, maxEnd + x); maxS = Math.max(maxS, maxEnd); minEnd = Math.min(x, minEnd + x); minS = Math.min(minS, minEnd); } if (maxS < 0) return maxS; // all negative return Math.max(maxS, total - minS); } ``` **Dry run** `[5,-3,5]` → wrap 5+5=10 vs linear 5. TC: O(n). SC: O(1). **If you get stuck:** linear Kadane first, then “invert to min subarray.” --- ### `|a[i]−a[j]|=k` max subarray — mapped R2 — UTA N — [LC 8014509](https://leetcode.com/discuss/post/8014509/amazon-sde-1-interview-experience-by-pra-azvd/) **What they actually asked:** max subarray i..j with `|a[i]−a[j]|=k` (with Islands). **No LC id.** Confirm: maximize **sum** or **length** of contiguous `a[i..j]` whose **endpoints** differ by k. **Clarify out loud** - i,j are endpoints of the subarray? - Max sum vs max length? - k given? **Trick / pattern in one sentence:** For each right index j, look up previous indices of `a[j]+k` and `a[j]−k`; take best sum/length. **Why this data structure** - brute: all i≤j check endpoints - optimal: HashMap value → list of prefix sums / min prefix before this value (for max sum) or leftmost index (for max length) - refuse: two pointers assuming sorted **Brute** ```java int maxLenBrute(int[] a, int k) { int best = 0; for (int i = 0; i < a.length; i++) for (int j = i; j < a.length; j++) if (Math.abs(a[i] - a[j]) == k) best = Math.max(best, j - i + 1); return best; } ``` TC: O(n²). SC: O(1). **Optimal (max length)** — keep first index of each value: ```java int maxLen(int[] a, int k) { Map first = new HashMap<>(); int best = 0; for (int j = 0; j < a.length; j++) { first.putIfAbsent(a[j], j); for (int t : new int[]{a[j] + k, a[j] - k}) { if (first.containsKey(t)) best = Math.max(best, j - first.get(t) + 1); } } return best; } ``` Max **sum** variant: store min prefix before each value so `pref[j+1]−minPref[a[j]±k]` is candidate. **Dry run** a=`[1,2,3,1]`, k=2: endpoints 1 and 3 → length 3 (`1,2,3`). TC: O(n). SC: O(n). **If you get stuck:** brute i,j; then “map of first index of value.” --- ### In-place frequency 1..N — mapped R2 — UTA N — [Prabhash](https://www.linkedin.com/posts/prabhash-jena_amazoninterview-sde1-interviewexperience-activity-7354481801756622848-C4v6) **What they actually asked:** in-place freq 1..N. Same R2 as Kadane water-level. **Clarify out loud** - Array of size n, values in 1..n; count occurrences **in-place**? - Output overwrite a[i] = freq of (i+1)? **Trick / pattern in one sentence:** Add `n` at index `(a[i]-1) % n`; then `a[i] / n` is the count. **Why this data structure** - brute: extra HashMap / count array - optimal: modulo encoding - refuse: sorting if they require original positions / O(1) extra **Brute** ```java int[] freqExtra(int[] a) { int n = a.length; int[] c = new int[n]; for (int x : a) c[x - 1]++; return c; } ``` TC: O(n). SC: O(n) extra — they said in-place. **Optimal** ```java void inplaceFreq(int[] a) { int n = a.length; for (int i = 0; i < n; i++) a[i]--; // 0..n-1 for (int i = 0; i < n; i++) a[a[i] % n] += n; for (int i = 0; i < n; i++) a[i] /= n; // freq of value i+1 } ``` **Dry run** `[2,3,3,2,5]` n=5 → freq of 1..5: `0,2,2,0,1`. | after +n | a[i]/n | | --- | --- | | encoded | 0 2 2 0 1 | TC: O(n). SC: O(1). **If you get stuck:** extra array first, then “store two numbers in one slot via +n.” --- ### Kadane water-level-change — mapped R2 — UTA N — [Prabhash](https://www.linkedin.com/posts/prabhash-jena_amazoninterview-sde1-interviewexperience-activity-7354481801756622848-C4v6) **What they actually asked:** Kadane variant max water from water-level-change array. **Clarify:** array of deltas (can be negative); max water = max subarray sum of deltas? Or trap-rain on heights? Candidate said **Kadane variant** → max subarray sum. **Trick:** standard Kadane on the change array. **Why DS:** brute all subarrays; optimal Kadane. Not a heap. **Brute** O(n²) running sums. **Optimal** ```java int maxWater(int[] delta) { int best = delta[0], cur = delta[0]; for (int i = 1; i < delta.length; i++) { cur = Math.max(delta[i], cur + delta[i]); best = Math.max(best, cur); } return best; } ``` **Dry run** `[1,-2,3,1,-1]` → `3+1=4`. TC: O(n). SC: O(1). **If you get stuck:** “max subarray sum.” If they meant trapping rain, use the Rainwater card. --- ### Median of Two Sorted Arrays — mapped R1 — UTA N — [LC 6606011](https://leetcode.com/discuss/post/6606011/amazon-sde-1-interview-experience-27-mar-ermb/) **What they actually asked:** Median of Two Sorted Arrays. Same R1 as longest valid parentheses. (8029194 HM had “LC Hard similar to Median of Two Sorted Arrays” — same pattern, unnamed exact.) **Clarify out loud** - Even length → average of two middles? - Empty one array? - O(log (m+n)) required? **Trick / pattern in one sentence:** BS the partition of the smaller array so `leftMax ≤ rightMin` on both sides. **Why this data structure** - brute: merge O(m+n) - optimal: BS on smaller - refuse: sorting concatenated **Brute** ```java double brute(int[] a, int[] b) { int[] c = new int[a.length + b.length]; int i = 0, j = 0, k = 0; while (i < a.length && j < b.length) c[k++] = a[i] < b[j] ? a[i++] : b[j++]; while (i < a.length) c[k++] = a[i++]; while (j < b.length) c[k++] = b[j++]; int n = c.length; return (n % 2 == 1) ? c[n/2] : (c[n/2-1] + c[n/2]) / 2.0; } ``` TC: O(m+n). SC: O(m+n). **Optimal** ```java double findMedianSortedArrays(int[] a, int[] b) { if (a.length > b.length) return findMedianSortedArrays(b, a); int m = a.length, n = b.length, lo = 0, hi = m, half = (m + n + 1) / 2; while (lo <= hi) { int i = (lo + hi) / 2, j = half - i; int aL = i == 0 ? Integer.MIN_VALUE : a[i - 1]; int aR = i == m ? Integer.MAX_VALUE : a[i]; int bL = j == 0 ? Integer.MIN_VALUE : b[j - 1]; int bR = j == n ? Integer.MAX_VALUE : b[j]; if (aL <= bR && bL <= aR) { if (((m + n) & 1) == 1) return Math.max(aL, bL); return (Math.max(aL, bL) + Math.min(aR, bR)) / 2.0; } else if (aL > bR) hi = i - 1; else lo = i + 1; } throw new IllegalArgumentException(); } ``` **Dry run** a=`[1,3]` b=`[2]` → 2. a=`[1,2]` b=`[3,4]` → 2.5. | i | j | aL aR | bL bR | | --- | --- | --- | --- | | 1 | 1 | 1,3 vs 2,4 | adjust until cut OK | TC: O(log min(m,n)). SC: O(1). **If you get stuck:** merge brute; then “partition smaller.” --- ### Minimum Knight Moves — mapped R2 — UTA N — [LC 6629948](https://leetcode.com/discuss/post/6629948/amazon-sde-1-20232024-graduate-round-2-b-v6wy/) **What they actually asked:** Minimum Knight Moves (LC linked). Same R2 as Validate Sum Tree. **Clarify out loud** - Infinite chessboard? Start (0,0) to (x,y)? - 8 knight deltas? Min steps? **Trick / pattern in one sentence:** BFS; use symmetry `x=abs(x), y=abs(y)` and `x≥y` to cut the quadrant. **Why this data structure** - brute: BFS without symmetry — still OK for small targets - optimal: BFS + visited in first quadrant - refuse: Dijkstra — unweighted **Brute** — BFS whole plane, visited set of `x,y` strings. Memory heavy. **Optimal** ```java int minKnightMoves(int x, int y) { x = Math.abs(x); y = Math.abs(y); int[][] d = {{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}}; ArrayDeque q = new ArrayDeque<>(); Set vis = new HashSet<>(); q.offer(new int[]{0, 0, 0}); vis.add("0,0"); while (!q.isEmpty()) { int[] c = q.poll(); if (c[0] == x && c[1] == y) return c[2]; for (int[] dd : d) { int nx = c[0] + dd[0], ny = c[1] + dd[1]; if (nx < -2 || ny < -2 || nx > x + 2 || ny > y + 2) continue; String k = nx + "," + ny; if (vis.add(k)) q.offer(new int[]{nx, ny, c[2] + 1}); } } return -1; } ``` **Dry run** (2,1) → 1. (5,5) → 4. TC: O(area visited). SC: same. **If you get stuck:** “knight = 8-dir BFS.” --- ### Validate Sudoku (not Solver) — mapped R3 — UTA N — [sde-1-17](https://www.geeksforgeeks.org/interview-experiences/amazon-interview-experience-for-sde-1-17/) **What they actually asked:** Validate sudoku (**not** Solver). Solver is older GFG remainder below. **Clarify:** 9×9, `'.'` empty; check rows, cols, 3×3 boxes? **Trick:** 9 sets (or bitmasks) per row/col/box; skip `'.'`. **Why DS:** brute rescan; optimal one pass 27 sets. Not backtracking. **Brute** — for each cell rescan its row/col/box O(81·9). **Optimal** ```java boolean isValidSudoku(char[][] b) { int[] row = new int[9], col = new int[9], box = new int[9]; for (int i = 0; i < 9; i++) for (int j = 0; j < 9; j++) { if (b[i][j] == '.') continue; int bit = 1 << (b[i][j] - '1'); int k = (i / 3) * 3 + j / 3; if ((row[i] & bit) != 0 || (col[j] & bit) != 0 || (box[k] & bit) != 0) return false; row[i] |= bit; col[j] |= bit; box[k] |= bit; } return true; } ``` **Dry run** duplicate `5` in row 0 → false. TC: O(81). SC: O(1). **If you get stuck:** three nested uniqueness checks. --- ### Min Arrows to Burst Balloons — mapped R1 — UTA N — [Deepak](https://www.linkedin.com/posts/deepak-gautam-a77b93222_amazon-sde-interviewexperience-activity-7485166684211671040-d-gv) **What they actually asked:** Number of Islands; **Min Arrows to Burst Balloons** (snippet). Jul 2026, closest calendar to 18 Aug, **not** named UTA. Islands is the graph card; this is interval greedy. **Clarify:** points `[start,end]` on a line; arrow at x bursts all covering x; min arrows? **Trick:** Sort by **end**; shoot at end; skip balloons already covering that x. ```java int findMinArrowShots(int[][] p) { Arrays.sort(p, (a, b) -> Integer.compare(a[1], b[1])); int arrows = 1, cut = p[0][1]; for (int i = 1; i < p.length; i++) { if (p[i][0] > cut) { arrows++; cut = p[i][1]; } } return arrows; } ``` **Dry run** `[[10,16],[2,8],[1,6],[7,12]]` → 2. Brute: try all x. TC: O(n log n). SC: O(1). Use `Integer.compare` (overflow). **Stuck:** “sort by end, greedy shot.” --- ### Unnamed FTE from bible §5.B (pattern only — no fake LC) Compact. Titles stay **UNNAMED**. **Map+String Amazon Shipping simulation** — mapped R1 — AUTA mail — [IE.in 2024-grad](https://interviewexperiences.in/experience/amazon/amazon-sde-1-interview-experience-2024-grad-17-yoe-tier-3-college-selected). Pattern: parse shipment ids / routes into `HashMap`, simulate state transitions, deep follow-ups on edge cases (missing key, duplicate scan). Not a named LC. Clarify entities (package, hub, status) before coding. **Logic-heavy non-standard** — mapped R1 — UTA — [Naina](https://medium.com/@nainavangani09/my-amazon-sde-1-interview-experience-2025-selected-dea6b5e9e3e9). Pattern: they gave I/O and expected a dry run; one hint. Do not guess a slug. Write brute from the example table they draw, then name the DS. **Heap+HashMap array (LC Medium)** — mapped R1 — hashtag only — Rudraksh. Pattern: frequency or running top-k on an array (same skeleton as Top K Frequent). Hashtag is not an id. **matrix + heaps** — mapped R1 — [LC 7280347](https://leetcode.com/discuss/post/7280347/amazon-india-sde-1-interview-experience-2ogbw/). Pattern: kth smallest in sorted matrix / merge k sorted rows (min-heap of row heads). Same IE named Diameter + later Clone Graph; this one stayed unnamed. **Trees+DP** — mapped R2 — [LC 7981646](https://leetcode.com/discuss/post/7981646/). Pattern: tree knapsack / House Robber on tree / diameter-with-values. They told candidate to prep LLD; still unnamed. **Binary Search solved using PQ** — mapped R3 — LC 7981646. Pattern: a problem that *can* be BS-on-answer but they accepted a heap simulation (e.g. kth pair distance / meeting rooms). Do not invent which. **AUTA greedy / tree / leftover puzzle** — mapped R1 — [Reddit 1ueybmg](https://old.reddit.com/r/LeetcodeDesi/comments/1ueybmg/amazon_sde1_auta_india_interview_experience_offer/). Three unnamed questions same day as logger LLD. Pattern only: one greedy, one BT, one puzzle. No titles. **Arijit LL variation + 1D DP** — mapped R1 — AUTA — [Arijit](https://www.linkedin.com/posts/arijit-char_my-amazon-sde-1-auta-interview-experience-activity-7366548692872433664-Fw-c). Pattern: linked-list local reverse/swap family + linear DP (kadane/robber/climb). R2 was unnamed SD (OOD fragment). **Kamlesh story string/stack/graph** — mapped R1 (OA-as-R1) — [Kamlesh](https://www.linkedin.com/posts/kamlesh012_amazon-interviewexperience-sde1-activity-7435882238334078976-_HqI). Pattern: narrative wrapping a string parse, a monotonic stack, or a graph walk. R2 was Stack Overflow LLD. **Job 3100855 Two Pointer / Heap / BS** — [Reddit 1s9z862](https://old.reddit.com/r/csMajors/comments/1s9z862/amazon_sde1_interview_experience_india_2026_oa_3/). **Different Job ID, not 10454435.** One line: do not treat as this loop’s question list. Other §5.B unnamed already skipped as A-1 (A2/A5/A13) or covered as pattern jumps / stone-collision / encoded above. --- ### Older GFG remainder 2021–23 (compact) Not UTA-default. Trick + short Java + TC/SC. URLs: GFG `sde-1-16/23/24/25/27/29`, `off-campus-8/10/12/13`, `on-campus-6`. Reprint: `sde-1off-campus-2023` ≡ `sde-1-34`. **First unique-nationality spectator** — sde-1-23 R1. Trick: stream of (id, nationality); first person whose nationality appears once. Java: `LinkedHashMap` then first count==1, or queue+map like first unique char. TC: O(n). SC: O(u). **Parent-child 1-parent nodes** — sde-1-24 R2. Trick: pairs `(parent, child)`; print nodes with exactly one parent and nodes with no parent (roots). Java: `Map indeg`; scan keys. TC: O(n). SC: O(n). **Validate BST variant** — sde-1-25 R1. Trick: min/max recurse (not only left= hi) return false; return isBST(n.left, lo, n.val) && isBST(n.right, n.val, hi); } ``` TC: O(n). SC: O(h). **Max-bends path** — sde-1-25 R2. Trick: longest path in binary tree counting direction changes (left/right). DFS return `{len going left, len going right}`; bend when you attach opposite child. TC: O(n). **Next greater frequency** — sde-1-25 R2. Trick: next element to the right with **strictly higher freq**, not higher value. Freq map first, then monotonic stack on freq[a[i]]. TC: O(n). SC: O(n). **minStack one stack** — sde-1-27 R1. Trick: store `2*x - min` when pushing a new min (or pair). ```java class MinStack { ArrayDeque st = new ArrayDeque<>(); long min; void push(int x) { if (st.isEmpty()) { st.push((long) x); min = x; } else if (x >= min) st.push((long) x); else { st.push(2L * x - min); min = x; } } void pop() { long t = st.pop(); if (t < min) min = 2 * min - t; } int top() { long t = st.peek(); return (int) (t < min ? min : t); } int getMin() { return (int) min; } } ``` TC: O(1). SC: O(n). **Longest palindrome from chars** — sde-1-27 R2. Trick: count letters; answer = all even counts + at most one odd. TC: O(n). SC: O(1). **Min-length substring covering pattern** — sde-1-27 BR. Trick: minimum window substring; `need` map + `missing` counter. TC: O(n). SC: O(Σ). **Reverse stack via another stack** — sde-1-29 R1. Trick: `st2` holds reverse; or recursion + one stack insert-at-bottom. TC: O(n). SC: O(n). **Max water between two buildings** — sde-1-29 R2. Trick: two pointers on heights; area = `min(h[l],h[r])*(r-l)` max (container with most water). TC: O(n). SC: O(1). **North-south bridges LIS** — sde-1-16 R2. Trick: sort by north, LIS on south (patience sort tails). TC: O(n log n). SC: O(n). **LED RGB OOPS** — sde-1-16 R1. Point to **OOD fragment** (SOLID / state of LED). Not a DSA card. **Celebrity** — off-campus-10. Trick: two pointers eliminate; verify candidate row 0s / col 1s (`knows(i,j)` API). TC: O(n). SC: O(1). **Rat in a maze** — off-campus-13 R2. Trick: DFS/backtrack 4-dir, mark visited, collect paths `DLRU`. TC: exponential paths. SC: O(n²) vis. **Squares-sort** — off-campus-13 R1. Trick: sorted squares of sorted array: two pointers from ends, fill output from back. TC: O(n). SC: O(n). **Delete leaf value X** — off-campus-13 R1. Trick: post-order; if leaf and val==X return null. TC: O(n). SC: O(h). **Reduce array at most twice** — on-campus-6 R1. Trick: (underspecified year-out) usually: replace two numbers by their difference/sum at most twice to reach target — clarify; greedy sort or PQ. Pattern: limited reduction ops. **Closest pair-sum** — on-campus-6 R2. Trick: two pointers on sorted array toward target T. TC: O(n) after sort. **Balanced parentheses combinations** — on-campus-6 BR. Trick: backtrack `open`. TC: O(n log w). SC: O(n). **Sudoku Solver** — backtrack empty cell, try 1–9, `isValid`. Distinct from **Validate** card above. TC: exponential. SC: O(81). **Paint House** — DP `dp[i][c] = cost[i][c] + min of other colors prev`. TC: O(n). SC: O(1) rolling. **Knight steps** — BFS like Minimum Knight Moves; bounded board. TC: O(n²). **Evaluate division** — graph of ratios; DFS product (family of Currency Converter; still no LC stamp on Shiwangi). TC: O(E) per query. SC: O(E). **Stepping numbers** — BFS from 1–9; append lastDigit±1. TC: numbers generated. SC: queue. **Word search 8-dir** — DFS from each cell, 8 deltas, mark visited. TC: O(mn · 8^L). SC: O(L). **Pairs sum % 60** — count `freq[t%60]`; ans += freq[0] C2 + freq[30] C2 + freq[i]*freq[60-i]. TC: O(n). SC: O(1). --- ## 3. OOD / LLD cards (bible §5.C FTE only) Notes for Adarsh. Java is canonical. These are answers to designs **other** SDE I / UTA / AUTA candidates reported in first-hand IEs. Your 18 Aug loop may differ. Unnamed stays unnamed. There is still **no** public IE that names Job **10454435** for a live-round design — do not treat CampusToCareer “Tech 2 = APIs / databases / caching layers” as an asked prompt (Class C invention). Login Tracker is **not** in this fragment (mentor-only, unverified). Rate Limiter independent SDE I live-round count = **1**, and that one is OA+3 Second Technical SD, **not** UTA two-DSA. Live-Code rhythm: entities + 1–2 methods compiling in the editor beats a novel of empty classes. Say TC/SC out loud. Canada cart/checkout, intern eviction DS, 5-round board-game LLD: see NMF / INTERN appendix (not this FTE table). --- ### Amazon Locker / Locker Management (warehouse packages) — our R1 Prince + our R2 Uday — not UTA/AUTA — shared card - Prince R1: https://medium.com/@princepandey20022002/amazon-sde-1-interview-experience-off-campus-57825c172e2f (Job 3057703, OA+2+BR) - Uday Singh R2: https://www.linkedin.com/posts/uday-singh-b97283216_amazon-sde1-interviewexperience-activity-7359475568892956672-433l (OA+3; expected DSA, got SD; UX + scalability) **What they actually asked** - Prince: Design a **Locker Management System for Warehouse Packages** (R1, after an LC-424-like DSA). - Uday: **Amazon Locker System** as the second live (R2). Candidate expected DSA, got system design. Follow-ups: **UX + scalability**. Same family. Two independent IEs, two slots. Not two different products. **Clarify** - Pickup vs drop-off vs both? Customer-facing Amazon Hub Locker vs warehouse cubby? - Locker sizes (S/M/L) vs package dimensions? One package per locker or split? - Assign locker at drop, or customer chooses? - Code / QR expiry? Failed pickup after N days → return-to-FC? - Single site vs multi-site (Uday scale)? Concurrent assign on the same cubby? - Persistence: in-memory for Live Code, then “Map + DB later”? **Classes** ```java enum LockerSize { SMALL, MEDIUM, LARGE } final class Package { final String packageId; final LockerSize minSize; Package(String packageId, LockerSize minSize) { this.packageId = packageId; this.minSize = minSize; } } final class Locker { final String lockerId; final LockerSize size; private String occupyingPackageId; // null = free private String accessCode; Locker(String lockerId, LockerSize size) { this.lockerId = lockerId; this.size = size; } boolean isFree() { return occupyingPackageId == null; } synchronized String occupy(Package pkg, String code) { if (!isFree()) throw new IllegalStateException("occupied"); occupyingPackageId = pkg.packageId; accessCode = code; return code; } synchronized String release(String code) { if (accessCode == null || !accessCode.equals(code)) { throw new IllegalArgumentException("bad code"); } String id = occupyingPackageId; occupyingPackageId = null; accessCode = null; return id; } } interface LockerAssignmentStrategy { Locker pick(List free, LockerSize minSize); } final class SmallestFitStrategy implements LockerAssignmentStrategy { public Locker pick(List free, LockerSize minSize) { Locker best = null; for (Locker l : free) { if (l.size.ordinal() < minSize.ordinal()) continue; if (best == null || l.size.ordinal() < best.size.ordinal()) best = l; } return best; } } final class LockerSite { private final Map byId = new HashMap<>(); private final Map> freeBySize = new EnumMap<>(LockerSize.class); private final Map packageToLocker = new HashMap<>(); private final LockerAssignmentStrategy strategy; LockerSite(LockerAssignmentStrategy strategy) { this.strategy = strategy; for (LockerSize s : LockerSize.values()) freeBySize.put(s, new ArrayDeque<>()); } void addLocker(Locker locker) { byId.put(locker.lockerId, locker); freeBySize.get(locker.size).add(locker); } synchronized String dropOff(Package pkg) { List candidates = new ArrayList<>(); for (LockerSize s : LockerSize.values()) { if (s.ordinal() >= pkg.minSize.ordinal()) candidates.addAll(freeBySize.get(s)); } Locker chosen = strategy.pick(candidates, pkg.minSize); if (chosen == null) throw new IllegalStateException("no locker"); freeBySize.get(chosen.size).remove(chosen); String code = UUID.randomUUID().toString().substring(0, 6); chosen.occupy(pkg, code); packageToLocker.put(pkg.packageId, chosen.lockerId); return code; } synchronized String pickUp(String lockerId, String code) { Locker locker = byId.get(lockerId); String pkgId = locker.release(code); packageToLocker.remove(pkgId); freeBySize.get(locker.size).add(locker); return pkgId; } } ``` **SOLID** - **S:** `Locker` owns occupy/release; `LockerSite` owns indexes; strategy owns “which cubby”. - **O:** new size or “closest-to-entrance” strategy without editing `LockerSite`. - **L:** any `LockerAssignmentStrategy` is substitutable. - **I:** no fat `AmazonGodService` with payments + routing + lockers. - **D:** site depends on the strategy interface, not `SmallestFitStrategy`. **Core algorithm / DS** - `HashMap` packageId → lockerId, lockerId → Locker. - Per-size free lists (`EnumMap` + `Deque`) so assign is O(1) if you always take the head of the smallest-fit deque (Prince Live Code). Strategy scan is fine for a small site. - Access code: random string; optional expiry timestamp on `Locker`. **Follow-ups** - **Scale (Uday):** site-sharded (lockerId prefix = site). Inventory in Dynamo/SQL; assignment via conditional write (`occupied=false` → `true`) so two couriers cannot win the same cubby. Cache free-counts per size, not the source of truth. - **Thread-safety:** `synchronized` on site for in-memory; production = DB unique constraint / Redis `SET NX` on locker key. - **Failure:** courier crash after occupy → TTL + compensation job returns package to FC. - **UX (Uday):** SMS/email with locker map + code; oversized package → “see associate”; expired code → regenerate after ID check. - Do **not** jump to “add a caching layer” as if Job 10454435 asked it. **If stuck:** draw Site → Bank → Locker → Package. Implement `dropOff` happy path (find free SMALL, set occupied, return code). Then `pickUp`. --- ### Spotify playlist insert/delete/search O(1) — our R2 — not UTA/AUTA — Prince (same loop as Locker R1) https://medium.com/@princepandey20022002/amazon-sde-1-interview-experience-off-campus-57825c172e2f **What they actually asked** Design a **Spotify Playlist**: **insert / delete / search by name in O(1)**. (Same Prince R2 as matrix max-path DSA.) **Clarify** - Unique song names in one playlist, or duplicates allowed? - Does insert position matter (end vs at index)? Index insert cannot be O(1) in an array. - Search = exact name, or prefix? - Single playlist or library of playlists? - Thread-safe play/pause vs mutate? **Classes** ```java final class SongNode { final String name; SongNode prev, next; SongNode(String name) { this.name = name; } } final class Playlist { private final Map byName = new HashMap<>(); private final SongNode head = new SongNode(""); // dummy private final SongNode tail = new SongNode(""); Playlist() { head.next = tail; tail.prev = head; } /** insert at end — O(1) average */ public boolean insert(String name) { if (byName.containsKey(name)) return false; SongNode node = new SongNode(name); SongNode last = tail.prev; last.next = node; node.prev = last; node.next = tail; tail.prev = node; byName.put(name, node); return true; } /** delete by name — O(1) average */ public boolean delete(String name) { SongNode node = byName.remove(name); if (node == null) return false; node.prev.next = node.next; node.next.prev = node.prev; node.prev = node.next = null; return true; } /** search by exact name — O(1) average */ public boolean search(String name) { return byName.containsKey(name); } } ``` **SOLID** - **S:** `Playlist` is the DS; do not mix streaming/bitrate here. - **O:** a `PlayOrder` strategy (shuffle vs sequential) can wrap the DLL later. - **L:** n/a unless you extract `MutablePlaylist`. - **I:** three methods only — matches the ask. - **D:** callers depend on `Playlist`, not HashMap. **Core algorithm / DS** - **Brute:** `ArrayList` — search/delete O(n). - **Optimal:** `HashMap` + doubly linked list for order. Same pattern as LRU. Average O(1) insert/delete/search. - Refuse a balanced BST unless they ask ordered-by-name iteration (that is O(log n), not O(1)). **Follow-ups** - Duplicates: key = `name + "#" + uniqueId`, secondary index `name → Set`. - Move to next/prev song: walk DLL. - Thread-safety: `synchronized` or ConcurrentHashMap + careful DLL (DLL concurrent splice is hard — one lock on playlist). - Scale: one playlist is in-memory; Spotify-scale is not this question. **If stuck:** say HashMap for O(1) name lookup, then add DLL only if they care about play order. Implement `search` first. Related (not this card): music Song/Artist/Album family below; GetRandom O(1) is a different IE (HashMap + ArrayList). --- ### Parking Lot — our R2 — not UTA/AUTA — GFG fresher https://www.geeksforgeeks.org/interview-experiences/amazon-interview-experience-for-sde1-fresher-off-campus/ Reprints / same family: year-out GFG Set 186/322. DevBrainiac Parking Lot is **their R3, experienced 4-round = NMF**, not a second UTA ask. **What they actually asked** **Parking Lot OOD** as R2 (after Burning Tree + Merge Intervals). Behavioral 2–3 UNNAMED. **Clarify** - Vehicle types (bike / car / bus) vs spot types? Can a car take a bus spot? - Multi-floor? Entry multiple gates? - Hourly vs flat fee? Ticket on entry, pay on exit? - EV / reserved (only if they add it — DevBrainiac NMF had EV/reserved/pricing)? - Single machine, in-memory? **Classes** ```java enum SpotType { MOTORCYCLE, COMPACT, LARGE } enum VehicleType { MOTORCYCLE, CAR, BUS } final class Vehicle { final String plate; final VehicleType type; Vehicle(String plate, VehicleType type) { this.plate = plate; this.type = type; } } final class ParkingSpot { final String spotId; final SpotType type; private Vehicle occupant; ParkingSpot(String spotId, SpotType type) { this.spotId = spotId; this.type = type; } boolean isFree() { return occupant == null; } boolean canFit(Vehicle v) { if (v.type == VehicleType.MOTORCYCLE) return true; if (v.type == VehicleType.CAR) return type != SpotType.MOTORCYCLE; return type == SpotType.LARGE; } void park(Vehicle v) { occupant = v; } Vehicle leave() { Vehicle v = occupant; occupant = null; return v; } } final class Ticket { final String ticketId; final String spotId; final String plate; final long inEpochMs; Ticket(String ticketId, String spotId, String plate, long inEpochMs) { this.ticketId = ticketId; this.spotId = spotId; this.plate = plate; this.inEpochMs = inEpochMs; } } interface PricingPolicy { int cents(Ticket t, long outEpochMs); } final class HourlyPricing implements PricingPolicy { private final int centsPerHour; HourlyPricing(int centsPerHour) { this.centsPerHour = centsPerHour; } public int cents(Ticket t, long outEpochMs) { long hours = Math.max(1, (outEpochMs - t.inEpochMs + 3_599_999) / 3_600_000); return (int) hours * centsPerHour; } } final class ParkingLot { private final Map spots = new HashMap<>(); private final Map> free = new EnumMap<>(SpotType.class); private final Map openTickets = new HashMap<>(); private final PricingPolicy pricing; ParkingLot(PricingPolicy pricing) { this.pricing = pricing; for (SpotType t : SpotType.values()) free.put(t, new ArrayDeque<>()); } void addSpot(ParkingSpot s) { spots.put(s.spotId, s); free.get(s.type).add(s); } synchronized Ticket enter(Vehicle v) { ParkingSpot spot = findSpot(v); if (spot == null) return null; free.get(spot.type).remove(spot); spot.park(v); Ticket t = new Ticket(UUID.randomUUID().toString(), spot.spotId, v.plate, System.currentTimeMillis()); openTickets.put(t.ticketId, t); return t; } synchronized int exit(String ticketId) { Ticket t = openTickets.remove(ticketId); if (t == null) throw new IllegalArgumentException("unknown ticket"); ParkingSpot spot = spots.get(t.spotId); spot.leave(); free.get(spot.type).add(spot); return pricing.cents(t, System.currentTimeMillis()); } private ParkingSpot findSpot(Vehicle v) { for (SpotType t : SpotType.values()) { for (ParkingSpot s : free.get(t)) { if (s.canFit(v)) return s; } } return null; } } ``` **SOLID** - **S:** spot occupancy vs pricing vs lot indexes are separate. - **O:** new `PricingPolicy` (EV premium) without editing `enter`/`exit`. - **L:** any pricing impl. - **I:** `PricingPolicy` is one method. - **D:** lot depends on `PricingPolicy`. **Core algorithm / DS** - Free lists per `SpotType`. Assign = first fit. - `openTickets` HashMap for O(1) exit. **Follow-ups** - Multi-floor: `Floor` has its own free maps; `ParkingLot` picks nearest floor with a fit. - Thread-safety: one lock per lot, or lock per floor. - Full lot: `enter` returns null / wait queue. **Taanya — similar-to, not a second independent Parking Lot** https://www.linkedin.com/posts/taanya-tarun-91b623144_i-recently-went-through-the-interview-process-activity-7455268279041871872-i9j2 Their R2: **intervals; stream-based with follow-ups; LLD similar to parking lot**. Treat as the same entity sketch (spot/ticket/vehicle) plus a **stream of interval events** (car arrives at t, leaves at t). If they push intervals: sweep-line / min-platforms on `[in, out)` to answer “how many spots do we need?” or “is the lot full at time t?”. Do **not** count this as a second unique Parking Lot ask. **If stuck:** Vehicle, Spot, Ticket, `enter`/`exit`. Price last. --- ### Elevator Controller + DoS — our R2 — not UTA/AUTA — GFG 2025 SDE https://www.geeksforgeeks.org/interview-experiences/amazon-sde-2025-interview/ **What they actually asked** Tech 2: **Elevator Controller LLD**; **DoS / cyber follow-up**; project walkthrough. (OA+2; Tech 1 was spiral/zigzag tree.) **Clarify** - One shaft or N elevators? Floors 0..F? - External hall call (up/down) vs internal cabin buttons? - SCAN / LOOK vs nearest-car? - Capacity / weight? - Single-threaded event loop vs one thread per car? - DoS = flood of hall-call API requests? **Classes** ```java enum Direction { UP, DOWN, IDLE } final class Request { final int floor; final Direction hallDir; // IDLE means cabin destination Request(int floor, Direction hallDir) { this.floor = floor; this.hallDir = hallDir; } } interface DispatchPolicy { int pickCar(List cars, Request r); } final class NearestCarPolicy implements DispatchPolicy { public int pickCar(List cars, Request r) { int best = 0; int bestDist = Integer.MAX_VALUE; for (int i = 0; i < cars.size(); i++) { int d = Math.abs(cars.get(i).currentFloor - r.floor); if (d < bestDist) { bestDist = d; best = i; } } return best; } } final class ElevatorCar { final int id; int currentFloor = 0; Direction dir = Direction.IDLE; final TreeSet ups = new TreeSet<>(); final TreeSet downs = new TreeSet<>(Comparator.reverseOrder()); ElevatorCar(int id) { this.id = id; } void addStop(int floor, Direction hallDir) { if (floor >= currentFloor) ups.add(floor); else downs.add(floor); if (dir == Direction.IDLE) { dir = floor >= currentFloor ? Direction.UP : Direction.DOWN; } } void step() { if (dir == Direction.UP && !ups.isEmpty()) { currentFloor = ups.pollFirst(); if (ups.isEmpty()) dir = downs.isEmpty() ? Direction.IDLE : Direction.DOWN; } else if (dir == Direction.DOWN && !downs.isEmpty()) { currentFloor = downs.pollFirst(); if (downs.isEmpty()) dir = ups.isEmpty() ? Direction.IDLE : Direction.UP; } } } final class ElevatorController { private final List cars; private final DispatchPolicy policy; private final AtomicInteger hailCount = new AtomicInteger(); private static final int HAIL_PER_SEC_CAP = 50; private volatile long windowStartMs = System.currentTimeMillis(); private int windowCount = 0; ElevatorController(int nCars, DispatchPolicy policy) { this.policy = policy; cars = new ArrayList<>(); for (int i = 0; i < nCars; i++) cars.add(new ElevatorCar(i)); } public synchronized boolean hallCall(int floor, Direction dir) { if (isDoS()) return false; // or 429 int idx = policy.pickCar(cars, new Request(floor, dir)); cars.get(idx).addStop(floor, dir); return true; } public synchronized void cabinSelect(int carId, int floor) { cars.get(carId).addStop(floor, Direction.IDLE); } /** SCAN step for demo */ public synchronized void tick() { for (ElevatorCar c : cars) c.step(); } private boolean isDoS() { long now = System.currentTimeMillis(); if (now - windowStartMs >= 1000) { windowStartMs = now; windowCount = 0; } windowCount++; hailCount.incrementAndGet(); return windowCount > HAIL_PER_SEC_CAP; } } ``` **SOLID** - **S:** car owns stops; controller owns dispatch + rate cap; policy owns “which car”. - **O:** replace `NearestCarPolicy` with SCAN-aware idle-first. - **L:** policy substitutable. - **I:** dispatch vs DoS limiter could be two interfaces. - **D:** controller depends on `DispatchPolicy`. **Core algorithm / DS** - Per car: two `TreeSet`s of pending floors (SCAN). - Dispatch: nearest car (Live Code). Production: elevator scheduling is a known hard problem — say so. **Follow-ups** - **DoS (they asked):** unauthenticated hall-call endpoint can be flooded → cars thrash. Mitigations: per-IP / per-kiosk **rate limit** (fixed window is enough to say); auth on cabin panel; ignore duplicate calls to the same floor; circuit-break a kiosk; do not accept calls faster than the car can physically move. This is **not** the Rate Limiter SD card below (that count stays 1); here it is a **security follow-up on elevator**. - **Failure:** car stuck — remove from dispatch list; dump its stops to others. - **Scale:** one controller process per building; not a distributed Kafka novel. **If stuck:** one car, `TreeSet` of floors, `hallCall` + `tick`. Then N cars + nearest. Then one sentence on DoS rate cap. --- ### Searchable Collection add/search — our R2 — not UTA/AUTA — Aditya https://www.linkedin.com/posts/adityadevansh_amazon-sde1-interviewexperience-activity-7479410027959865346-jiR8 **What they actually asked** **Searchable Collection LLD add/search**; LP Ownership; adapting to new tech. (2 onsite + BR.) **Clarify** - Exact match vs prefix vs contains? Typed payload or `String` only? - Unique ids? Duplicate values? - Expected n? In-memory? - Search return first hit, all hits, or top-K? **Classes** ```java interface SearchableCollection { void add(String key, T value); List search(String query); } /** Exact key. */ final class HashSearchableCollection implements SearchableCollection { private final Map> map = new HashMap<>(); public void add(String key, T value) { map.computeIfAbsent(key, k -> new ArrayList<>()).add(value); } public List search(String query) { List hit = map.get(query); return hit == null ? List.of() : List.copyOf(hit); } } final class TrieNode { final Map> kids = new HashMap<>(); final List values = new ArrayList<>(); } /** Prefix search. */ final class TrieSearchableCollection implements SearchableCollection { private final TrieNode root = new TrieNode<>(); public void add(String key, T value) { TrieNode cur = root; for (int i = 0; i < key.length(); i++) { cur = cur.kids.computeIfAbsent(key.charAt(i), c -> new TrieNode<>()); } cur.values.add(value); } public List search(String query) { TrieNode cur = root; for (int i = 0; i < query.length(); i++) { cur = cur.kids.get(query.charAt(i)); if (cur == null) return List.of(); } List out = new ArrayList<>(); dfs(cur, out); return out; } private void dfs(TrieNode n, List out) { out.addAll(n.values); for (TrieNode k : n.kids.values()) dfs(k, out); } } ``` **SOLID** - **S:** storage vs traversal. - **O:** new impl (inverted index) behind the same interface. - **L:** Hash vs Trie are substitutable if the caller agreed prefix vs exact in clarify. - **I:** two methods — matches the ask. - **D:** callers depend on `SearchableCollection`. **Core algorithm / DS** - Exact: HashMap. Prefix: Trie. Contains: scan or suffix array — say n is small unless they ask. **Follow-ups** - Case fold / Unicode: normalize on add and search. - Thread-safety: ConcurrentHashMap for exact; Trie needs a lock. - Top-K prefix: heap at each node or online (see SERP prefix card later — different IE). **If stuck:** interface with `add`/`search`, HashMap impl, then “if prefix, Trie”. --- ### Dog check-in / check-out tracking — our R2 — AUTA — Nisarg Patel https://www.linkedin.com/posts/nisarg-patel-80361a184_amazon-auta-interviewexperience-activity-7361081215673585664-ZGfa Loop: OA + 3 same-day Pacific 31 Jul 2025. R2 12:30: **LP + LLD dog check-in/out tracking**. Location India **not stated**. **What they actually asked** LLD to **track dog check-in and check-out** (daycare / kennel / Amazon campus pet? — candidate said tracking, not a named product). Do not invent Amazon Pets. **Clarify** - One active visit per dog, or history of visits? - Capacity of the facility? Breed / size limits? - Checkout must match the same guardian? - Concurrent check-in at a kiosk? - Query: who is in now? visits for a dog? overdue pickup? **Classes** ```java final class Dog { final String dogId; final String name; final String ownerId; Dog(String dogId, String name, String ownerId) { this.dogId = dogId; this.name = name; this.ownerId = ownerId; } } final class Visit { final String visitId; final String dogId; final long inEpochMs; Long outEpochMs; Visit(String visitId, String dogId, long inEpochMs) { this.visitId = visitId; this.dogId = dogId; this.inEpochMs = inEpochMs; } boolean isOpen() { return outEpochMs == null; } } interface KennelStore { void saveDog(Dog d); Dog getDog(String dogId); void saveVisit(Visit v); Visit openVisit(String dogId); List history(String dogId); } final class InMemoryKennelStore implements KennelStore { private final Map dogs = new HashMap<>(); private final Map openByDog = new HashMap<>(); private final Map> history = new HashMap<>(); public void saveDog(Dog d) { dogs.put(d.dogId, d); } public Dog getDog(String dogId) { return dogs.get(dogId); } public void saveVisit(Visit v) { if (v.isOpen()) openByDog.put(v.dogId, v); else openByDog.remove(v.dogId); history.computeIfAbsent(v.dogId, k -> new ArrayList<>()); List hs = history.get(v.dogId); if (hs.isEmpty() || hs.get(hs.size() - 1) != v) hs.add(v); } public Visit openVisit(String dogId) { return openByDog.get(dogId); } public List history(String dogId) { return history.getOrDefault(dogId, List.of()); } } final class KennelService { private final KennelStore store; private final int capacity; private int occupancy = 0; KennelService(KennelStore store, int capacity) { this.store = store; this.capacity = capacity; } public synchronized Visit checkIn(String dogId) { if (store.getDog(dogId) == null) throw new IllegalArgumentException("unknown dog"); if (store.openVisit(dogId) != null) throw new IllegalStateException("already in"); if (occupancy >= capacity) throw new IllegalStateException("full"); Visit v = new Visit(UUID.randomUUID().toString(), dogId, System.currentTimeMillis()); store.saveVisit(v); occupancy++; return v; } public synchronized Visit checkOut(String dogId, String ownerId) { Dog d = store.getDog(dogId); if (d == null || !d.ownerId.equals(ownerId)) throw new IllegalArgumentException("owner mismatch"); Visit v = store.openVisit(dogId); if (v == null) throw new IllegalStateException("not in"); v.outEpochMs = System.currentTimeMillis(); store.saveVisit(v); occupancy--; return v; } } ``` **SOLID** - **S:** `KennelService` rules vs `KennelStore` persistence. - **O:** swap in-memory for JDBC store. - **L:** any `KennelStore`. - **I:** store is the persistence surface; service is the use-case surface. - **D:** service depends on `KennelStore`. **Core algorithm / DS** - HashMap dogId → open Visit; occupancy counter. - History list per dog. **Follow-ups** - Overdue: scan open visits (or min-heap by `inEpochMs`). - Thread-safety: one lock on service for Live Code. - Failure: crash mid check-in → occupancy vs store; persist first then increment, or transactional. **If stuck:** `Dog`, `Visit`, `checkIn`/`checkOut` with “already in” and “full” guards. --- ### File library — recursive traversal, filter, inheritance — our R2 — not UTA/AUTA — Pratyush https://www.linkedin.com/posts/pratyush2331_amazoninterview-sde-backendengineering-activity-7465745486185074688-QIh2 **What they actually asked** **File library system OOD**: recursive traversal, filtering, abstractions, **inheritance**. Hyderabad onsite. **Clarify** - In-memory tree vs wrap `java.nio.file`? - Filters: name glob, min size, extension, modified-after? AND vs OR? - Return paths or `FileComponent` objects? - Symlinks / cycles? **Classes** ```java interface FileComponent { String name(); long size(); void accept(FileVisitor v); } interface FileVisitor { void visitFile(FileLeaf f); void visitDir(Directory d); } interface FileFilter { boolean matches(FileLeaf f); } final class FileLeaf implements FileComponent { private final String name; private final long sizeBytes; FileLeaf(String name, long sizeBytes) { this.name = name; this.sizeBytes = sizeBytes; } public String name() { return name; } public long size() { return sizeBytes; } public void accept(FileVisitor v) { v.visitFile(this); } } final class Directory implements FileComponent { private final String name; private final List children = new ArrayList<>(); Directory(String name) { this.name = name; } void add(FileComponent c) { children.add(c); } public String name() { return name; } public long size() { long s = 0; for (FileComponent c : children) s += c.size(); return s; } public void accept(FileVisitor v) { v.visitDir(this); for (FileComponent c : children) c.accept(v); } } final class NameSuffixFilter implements FileFilter { private final String suffix; NameSuffixFilter(String suffix) { this.suffix = suffix; } public boolean matches(FileLeaf f) { return f.name().endsWith(suffix); } } final class MinSizeFilter implements FileFilter { private final long min; MinSizeFilter(long min) { this.min = min; } public boolean matches(FileLeaf f) { return f.size() >= min; } } final class AndFilter implements FileFilter { private final FileFilter a, b; AndFilter(FileFilter a, FileFilter b) { this.a = a; this.b = b; } public boolean matches(FileLeaf f) { return a.matches(f) && b.matches(f); } } final class CollectingVisitor implements FileVisitor { private final FileFilter filter; final List hits = new ArrayList<>(); CollectingVisitor(FileFilter filter) { this.filter = filter; } public void visitFile(FileLeaf f) { if (filter.matches(f)) hits.add(f); } public void visitDir(Directory d) { /* skip */ } } final class FileLibrary { List search(Directory root, FileFilter filter) { CollectingVisitor v = new CollectingVisitor(filter); root.accept(v); return v.hits; } } ``` **SOLID** - **S:** leaf vs directory vs filter vs walk. - **O:** new filter without touching traversal. - **L:** `FileLeaf` / `Directory` both `FileComponent` (composite). - **I:** tiny `FileFilter` / `FileVisitor`. - **D:** library depends on abstractions. **Core algorithm / DS** - Composite tree + Visitor DFS. Filter chain (Decorator / composite AND). **Follow-ups** - Cycle: `IdentityHashMap` visited dirs. - Scale: don’t load the whole tree; `Files.walk` + predicate (see find-family card). - Inheritance vs composition: they asked inheritance — Composite is the honest use; prefer composition for filters. **If stuck:** `File` / `Directory` with `List`, recursive `search(Directory, filter)`. --- ### Unix find-like / Java library on Linux to search files by constraints — find family - Raghav R2: https://www.linkedin.com/posts/raghav-rawat-a24aa5200_preparing-referral-amazon-activity-7352700400325570560-4slI — **Design a Java library on Linux to search files by constraints** (high-level); OA+DSA+design+HM. - Vanshika R2 analogue (3rd live, second coding): https://medium.com/@vanshika.mehta/my-amazon-sde-1-interview-experience-6c121054f123 — **Unix `find`-like command to search a file**; 3–4 follow-ups each; two LP UNNAMED. Loop OA+3, Sep 2025. **Not UTA-default two-DSA.** - US 3×60 Unix Find (Levels.fyi oP6vow, size/name/type/date/empty): **NMF** — same family evidence, not a second India UTA ask. Keep this card as **FTE Vanshika + Raghav**. **What they actually asked** - Vanshika: design a Unix **`find`-like** command to search a file (constraints implied by follow-ups; US NMF names size/name/type/date/empty — do not claim Vanshika listed those unless they did). - Raghav: **Java library on Linux** to search files **by constraints**, high-level (not a 40-min SNS design). **Clarify** - Walk real FS (`java.nio.file`) vs in-memory tree (Pratyush)? - Predicates: name glob, `-type f/d`, min/max size, mtime, empty file? - Short-circuit AND/OR? `-print` vs return `List`? - Follow symlinks? Permission errors? - Single machine (yes for Live Code). **Classes** ```java interface PathPredicate { boolean test(Path p, BasicFileAttributes attrs) throws IOException; } final class NameGlob implements PathPredicate { private final PathMatcher matcher; NameGlob(String glob) { matcher = FileSystems.getDefault().getPathMatcher("glob:" + glob); } public boolean test(Path p, BasicFileAttributes attrs) { return matcher.matches(p.getFileName()); } } final class TypeFile implements PathPredicate { public boolean test(Path p, BasicFileAttributes attrs) { return attrs.isRegularFile(); } } final class MinSize implements PathPredicate { private final long min; MinSize(long min) { this.min = min; } public boolean test(Path p, BasicFileAttributes attrs) { return attrs.isRegularFile() && attrs.size() >= min; } } final class AndPred implements PathPredicate { private final PathPredicate[] ps; AndPred(PathPredicate... ps) { this.ps = ps; } public boolean test(Path p, BasicFileAttributes attrs) throws IOException { for (PathPredicate pred : ps) if (!pred.test(p, attrs)) return false; return true; } } final class FileFinder { List find(Path root, PathPredicate pred) throws IOException { List out = new ArrayList<>(); Files.walkFileTree(root, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (pred.test(file, attrs)) out.add(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { return FileVisitResult.CONTINUE; } }); return out; } } // library façade (Raghav) final class LinuxFileSearch { private final FileFinder finder = new FileFinder(); public List search(Path root, PathPredicate constraints) throws IOException { return finder.find(root, constraints); } } ``` **SOLID** - **S:** walk vs predicate vs façade. - **O:** new constraint class. - **L:** any `PathPredicate`. - **I:** one `test` method (Specification). - **D:** finder depends on predicate, not glob internals. **Core algorithm / DS** - DFS/BFS walk (`Files.walkFileTree`). Predicates AND-composed. No Trie required unless they ask prefix on millions of names already indexed. **Follow-ups** - Empty file: `attrs.size()==0`. - Date: `attrs.lastModifiedTime()`. - Parallel walk: say “partition top-level dirs” — usually overkill. - Thread-safety: immutable predicates; don’t share the output list across threads without a concurrent collector. **If stuck:** `Predicate`, walk directory, AND name+size. Then wrap as `LinuxFileSearch`. Pratyush file-library is the **in-memory Composite** cousin; this card is the **POSIX find / nio** cousin. Same Specification pattern. --- ### Notification system–like — our R2 — not UTA/AUTA — Nitesh Khanna https://www.linkedin.com/posts/nitesh-khanna-75334b23b_amazon-sde1-interviewexperience-activity-7440683395870777344-oRfH **What they actually asked** Interview 2: LLD **similar to a notification system** + GenAI UNNAMED. Pattern prompt — **do not invent a full AWS SNS / SES / Pinpoint design**. **Clarify** - In-process Observer vs “email/SMS/push”? - Sync send vs queue? - Templates? Preferences (user opted out of SMS)? - Scale: one box Live Code vs “later, a queue”. - Failure: retry? at-least-once? **Classes** ```java enum ChannelType { EMAIL, SMS, IN_APP } final class Notification { final String userId; final String title; final String body; final ChannelType channel; Notification(String userId, String title, String body, ChannelType channel) { this.userId = userId; this.title = title; this.body = body; this.channel = channel; } } interface NotificationSender { ChannelType channel(); void send(Notification n); } final class EmailSender implements NotificationSender { public ChannelType channel() { return ChannelType.EMAIL; } public void send(Notification n) { /* SMTP stub */ } } final class SmsSender implements NotificationSender { public ChannelType channel() { return ChannelType.SMS; } public void send(Notification n) { /* SMS stub */ } } interface PreferenceStore { boolean allows(String userId, ChannelType ch); } final class NotificationService { private final Map senders; private final PreferenceStore prefs; NotificationService(List list, PreferenceStore prefs) { this.prefs = prefs; senders = new EnumMap<>(ChannelType.class); for (NotificationSender s : list) senders.put(s.channel(), s); } public void notify(Notification n) { if (!prefs.allows(n.userId, n.channel)) return; NotificationSender s = senders.get(n.channel); if (s == null) throw new IllegalStateException("no sender"); s.send(n); } } ``` **SOLID** - **S:** service routes; sender delivers. - **O:** new `PushSender` without editing `notify`. - **L:** any sender. - **I:** sender is `send` + `channel`. - **D:** service depends on `NotificationSender` / `PreferenceStore`. **Core algorithm / DS** - Strategy map `ChannelType → Sender`. Optional in-memory queue `BlockingQueue` + worker. **Follow-ups** - Scale talk (one minute, not SNS): enqueue to a broker, workers per channel, idempotency key. Stop. Do not draw AWS logos unless they ask cloud. - Failure: retry with backoff; dead-letter; **do not** dual-write “user table + SNS” unprompted. - DoS: rate-limit per user (elevator-style cap, not the Rate Limiter SD card). **If stuck:** `Notification` + `Sender` interface + Email/SMS impls + `notify()` that picks by channel. --- ### Music system Song/Artist/Album + playlist variants — family card - LC 6570344 R2: https://leetcode.com/discuss/post/6570344/amazon-sde-1-loop-interview-by-anonymous-i0v6/ — LLD **music system (Song, Artist, Album, …)**; follow-up **no iterative loop**; **average rating of unique songs**. - Jyoti Music Playlist: https://www.linkedin.com/posts/jyoti-singh-271b723b2_amazon-sde1-interviewexperience-activity-7436999420333821952-Xrye — body historically **404**; SERP: design a **Music Playlist system**; two test cases. **I could not verify** the full body. - LC 6873106 R2: https://leetcode.com/discuss/post/6873106/amazon-sde1-offer-interview-experience-b-idun/ — **flexible music playlist** (opened this pass as playlist LLD). Not a second Spotify-O(1) Prince ask. Prince Spotify O(1) is the **HashMap+DLL** card above. This card is the **domain model**. **What they actually asked** - 6570344: class design for a music system with Song / Artist / Album. Follow-up: avoid an iterative loop; average rating if each song is unique in an in-memory DB. - Jyoti: playlist system, two scenarios (SERP only). - 6873106: flexible playlist LLD. **Clarify** - Catalog vs one playlist vs both? - Ratings on song or album? Unique songs (6570344)? - Playlists contain song ids; can a song be in many playlists? - “Flexible” = add/remove/reorder / nested folders? **Classes** ```java final class Artist { final String artistId; final String name; Artist(String artistId, String name) { this.artistId = artistId; this.name = name; } } final class Album { final String albumId; final String title; final String artistId; Album(String albumId, String title, String artistId) { this.albumId = albumId; this.title = title; this.artistId = artistId; } } final class Song { final String songId; final String title; final String albumId; final String artistId; private double ratingSum; private int ratingCount; Song(String songId, String title, String albumId, String artistId) { this.songId = songId; this.title = title; this.albumId = albumId; this.artistId = artistId; } void addRating(int stars) { ratingSum += stars; ratingCount++; } double averageRating() { return ratingCount == 0 ? 0 : ratingSum / ratingCount; } } final class MusicCatalog { private final Map songs = new HashMap<>(); private final Map artists = new HashMap<>(); private final Map albums = new HashMap<>(); private double globalRatingSum; private int globalRatingCount; void addSong(Song s) { songs.put(s.songId, s); } void rate(String songId, int stars) { Song s = songs.get(songId); s.addRating(stars); globalRatingSum += stars; globalRatingCount++; } /** unique songs, running average — O(1), no loop (6570344 follow-up) */ double averageRatingAllUniqueSongs() { return globalRatingCount == 0 ? 0 : globalRatingSum / songs.size(); // If each song is unique and you need mean of per-song averages: // maintain sumOfAverages incrementally on each rate, still O(1). } } interface PlaylistOps { void add(String songId); void remove(String songId); List songs(); } final class OrderedPlaylist implements PlaylistOps { private final LinkedHashSet order = new LinkedHashSet<>(); public void add(String songId) { order.add(songId); } public void remove(String songId) { order.remove(songId); } public List songs() { return new ArrayList<>(order); } } ``` **SOLID** - **S:** Song ratings vs catalog indexes vs playlist membership. - **O:** `PlaylistOps` — shuffle / radio impl later (6873106 “flexible”). - **L:** playlist impls substitutable. - **I:** do not force `Album` to implement `PlaylistOps`. - **D:** playlist stores ids, not concrete `ArrayList` APIs. **Core algorithm / DS** - HashMaps by id. Playlist: `LinkedHashSet` for unique order O(1) add/remove. Running sums for average — **that** is the “no iterative loop” answer (maintain `ratingSum` / `count` on write). **Follow-ups** - Mean of per-song averages vs mean of all rating events — ask which. - Jyoti two test cases: if body stays 404, implement add/remove + “play next” on `LinkedHashSet` iterator; don’t invent a third product. **If stuck:** three classes + HashMap catalog + `averageRating` field. Playlist as `LinkedHashSet` of song ids. --- ### LRU Cache — our R2 Interview 2 — not UTA/AUTA — Bhavya — **NOT Login Tracker** https://www.linkedin.com/posts/bhavya-77816218a_amazon-interviewexperience-sde1-activity-7473680829714546688-jeL9 Hyderabad onsite. Interview 2: LP + **LRU Cache** + design principles / basic SD UNNAMED. HM Spring login is a **different card**. Login Tracker (`new_login` / `get_oldest_login`) is **unverified mentor-only** — do not treat it as this ask. **What they actually asked** **LRU Cache** (standard get/put capacity). Then unnamed design-principles talk. **Clarify** - Capacity in entries? `get` miss return -1? - Thread-safe? TTL? Generic K/V or `int`? - Evict least-recently-**used** (get counts as use). **Classes** ```java final class LRUNode { int key, value; LRUNode prev, next; LRUNode(int key, int value) { this.key = key; this.value = value; } } final class LRUCache { private final int capacity; private final Map map = new HashMap<>(); private final LRUNode head = new LRUNode(0, 0); private final LRUNode tail = new LRUNode(0, 0); public LRUCache(int capacity) { this.capacity = capacity; head.next = tail; tail.prev = head; } public int get(int key) { LRUNode n = map.get(key); if (n == null) return -1; moveToFront(n); return n.value; } public void put(int key, int value) { LRUNode n = map.get(key); if (n != null) { n.value = value; moveToFront(n); return; } LRUNode fresh = new LRUNode(key, value); map.put(key, fresh); addAfterHead(fresh); if (map.size() > capacity) { LRUNode lru = tail.prev; remove(lru); map.remove(lru.key); } } private void moveToFront(LRUNode n) { remove(n); addAfterHead(n); } private void addAfterHead(LRUNode n) { n.next = head.next; n.prev = head; head.next.prev = n; head.next = n; } private void remove(LRUNode n) { n.prev.next = n.next; n.next.prev = n.prev; } } ``` **SOLID** - **S:** node vs cache vs (later) `EvictionPolicy` — Bhavya did not ask LFU; see LFU card. - **O:** extracting policy is the Reddit 1idtlan follow-up, not this IE. - **L:** n/a for a concrete cache. - **I:** `get`/`put` only. - **D:** n/a. **Core algorithm / DS** - **Brute:** `LinkedHashMap` with `accessOrder=true` + `removeEldestEntry` — mention, then write HashMap+DLL because they want to see pointers. - **Optimal:** HashMap + dummy-headed DLL. `get`/`put` O(1). - Refuse `TreeMap` by timestamp (O(log n) and clock issues). Dry run `capacity=2`: `put(1,1) put(2,2) get(1) put(3,3)` → key 2 evicted; map `{1,3}`. **Follow-ups** - Thread-safety: `synchronized` on cache, or `ConcurrentHashMap` + striped locks (hard). `LinkedHashMap` + `Collections.synchronizedMap` is a sentence, not the code they want. - TTL: store `expireAt` on node; lazy delete on get. - Scale: Redis LRU is not this question unless they pivot to SD. **If stuck:** HashMap to node; on get, splice node to head; on overflow, drop `tail.prev`. --- ### Rate Limiter + distributed scale — Second Technical SD 13 Feb 2025 — **not UTA default** — IE.in 2025-grad https://interviewexperiences.in/experience/amazon/amazon-sde-1-2025-grad **Label:** asked as **Second Technical SD**, **not UTA two-DSA**. Loop = OA + 3 (First Tech 4 Feb graph+tree+OS; Second Tech **13 Feb 2025** Design a Rate Limiter + **scale across distributed systems** + few LP UNNAMED; Final LP 17 Jul). Independent **SDE I live-round count = 1**. SDE-2 Super Day / YouTube `d0yM6h0XRxk` / Hitesh L5 / prep lists / mentor file are **not** a second ask. **What they actually asked** **Design a Rate Limiter**; **scale across distributed systems**. (Not a DSA puzzle.) **Clarify** - Per user / IP / API key / route? Stacked limits? - Limit = N requests / W seconds? Burst allowed? - Reject = HTTP **429** + **Retry-After** vs queue vs silent drop? - Single process vs many app servers behind a LB? (they asked distributed) - Fail-**open** vs fail-**closed** if Redis dies? **Classes** (converted from `amazon-sde1-interview-prep.md` Python → Java) ```java interface RateLimiter { boolean allowRequest(String key); } final class TokenBucketRateLimiter implements RateLimiter { private final int capacity; private final double refillPerSec; private final Map buckets = new HashMap<>(); private final Object lock = new Object(); private static final class Bucket { double tokens; long lastNanos; Bucket(double tokens, long lastNanos) { this.tokens = tokens; this.lastNanos = lastNanos; } } TokenBucketRateLimiter(int capacity, double refillPerSec) { this.capacity = capacity; this.refillPerSec = refillPerSec; } public boolean allowRequest(String key) { synchronized (lock) { long now = System.nanoTime(); Bucket b = buckets.get(key); if (b == null) { b = new Bucket(capacity, now); buckets.put(key, b); } double delta = (now - b.lastNanos) / 1_000_000_000.0; b.tokens = Math.min(capacity, b.tokens + delta * refillPerSec); b.lastNanos = now; if (b.tokens >= 1.0) { b.tokens -= 1.0; return true; } return false; } } } final class SlidingWindowCounterRateLimiter implements RateLimiter { private final int maxRequests; private final double windowSec; private final Map windows = new HashMap<>(); private final Object lock = new Object(); private static final class Window { long currStartNanos; int currCount; int prevCount; } SlidingWindowCounterRateLimiter(int maxRequests, double windowSec) { this.maxRequests = maxRequests; this.windowSec = windowSec; } public boolean allowRequest(String key) { synchronized (lock) { long now = System.nanoTime(); long windowNanos = (long) (windowSec * 1_000_000_000L); Window w = windows.get(key); if (w == null || now - w.currStartNanos >= windowNanos) { int prev = 0; if (w != null && now - w.currStartNanos < 2 * windowNanos) prev = w.currCount; w = new Window(); w.currStartNanos = now; w.prevCount = prev; windows.put(key, w); } double elapsed = (now - w.currStartNanos) / 1_000_000_000.0; double weight = Math.max(0.0, (windowSec - elapsed) / windowSec); double estimated = w.prevCount * weight + w.currCount; if (estimated < maxRequests) { w.currCount++; return true; } return false; } } } /** Where it sits: gateway/middleware, not inside each use-case. */ final class RateLimitFilter { private final RateLimiter limiter; RateLimitFilter(RateLimiter limiter) { this.limiter = limiter; } /** return null if allowed; otherwise Retry-After seconds */ Integer preHandle(String key) { if (limiter.allowRequest(key)) return null; return 1; // Retry-After: 1 (or remaining-window) } } ``` Talk-track table (say out loud, don’t code all five): | Strategy | Memory | Accuracy | Burst | | --- | --- | --- | --- | | Fixed window | O(1)/key | low | ~2× at boundary | | Sliding window log | O(n)/key | exact | none | | Sliding window counter | O(1)/key | approx | small | | Token bucket | O(1)/key | n/a | up to capacity | | Leaky bucket | O(1)/key | n/a | smoothed | Cloudflare/Kong-style default: **sliding window counter**. Bursty APIs: **token bucket**. Write one fully (token bucket), sketch the other. **SOLID** - **S:** algorithm vs HTTP filter vs distributed store. - **O:** new limiter impl behind `RateLimiter`. - **L:** TokenBucket and SlidingWindowCounter both `allowRequest`. - **I:** one method on the strategy. - **D:** filter depends on `RateLimiter`, not Redis. **Core algorithm / DS** - Single box: `HashMap` + lock. - Distributed: **Redis + atomic Lua** so GET-refill-DECR-SET cannot race across app servers. Lua talk (do not need to compile Lua in Live Code): ``` -- TOKEN_BUCKET_LUA -- KEYS[1]=key ARGV=capacity, refill_rate, now -- HMGET tokens timestamp; refill; if tokens>=1 then decr, HMSET, EXPIRE, return 1 else 0 ``` Java call shape: `eval(lua, keys, capacity, refill, now)` → 1/0. **Follow-ups** - **Fail-open:** Redis down → allow (availability; risk overload). **Fail-closed:** Redis down → deny (protect origin; false 429s). Pick fail-closed for checkout/payments, fail-open for a marketing pixel. Say the trade-off; don’t waffle. - **429** + `Retry-After` (seconds until next token / window). Not a silent drop. - Multi-limit: compose `AND` of per-user and global limiters. - Clock: monotonic locally; Redis `TIME` inside Lua for multi-server. - Hot key: shard key or local token cache with periodic reconcile (mention, don’t design a novel). **If stuck:** interface `allowRequest(key)`, token bucket in a HashMap, then “for N servers, same math in Redis Lua”. Then 429 + fail-closed. --- ### Bookstore word-count OOD — our R3 — UTA — Shiwangi https://medium.com/@sshiwangi770/my-amazon-interview-experience-1ab2fd4f9e6f UTA named. R1 Currency Converter graph; R2 easy hashmap UNNAMED; **R3 bookstore word-count OOD**; R4 work deep-dive + SW UNNAMED. Comment: no LP each round. **What they actually asked** **Bookstore** — **count of a particular word in a specific book**; classes / objects / methods. (All_Rounds wording: count of a particular word in a specific book.) **Clarify** - One book or a catalog? Case-fold / punctuation? - Count at query time vs precomputed inverted index? - Same word in title vs body? - Concurrent updates (new edition)? **Classes** ```java final class Book { final String isbn; final String title; private final Map freq = new HashMap<>(); Book(String isbn, String title, String text) { this.isbn = isbn; this.title = title; index(text); } private void index(String text) { for (String raw : text.split("\\W+")) { if (raw.isEmpty()) continue; String w = raw.toLowerCase(Locale.ROOT); freq.put(w, freq.getOrDefault(w, 0) + 1); } } int count(String word) { return freq.getOrDefault(word.toLowerCase(Locale.ROOT), 0); } } final class Bookstore { private final Map byIsbn = new HashMap<>(); void add(Book b) { byIsbn.put(b.isbn, b); } int countInBook(String isbn, String word) { Book b = byIsbn.get(isbn); if (b == null) throw new IllegalArgumentException("unknown book"); return b.count(word); } } ``` **SOLID** - **S:** `Book` owns its index; `Bookstore` owns lookup. - **O:** tokenizer as `WordSplitter` if they ask stemming later. - **L:** n/a. - **I:** don’t dump inventory + payments on `Book`. - **D:** bookstore depends on `Book`, not a global static map. **Core algorithm / DS** - Per-book `HashMap`. Query O(1). Build O(tokens). - Inverted index `word → Map` if they ask “which books contain X”. **Follow-ups** - Phrase count: store token arrays, not only freq. - Scale: one HashMap per book in memory is enough for Live Code. **If stuck:** `Book` with `Map` filled in the constructor; `count(word)`. --- ### Stack Overflow–like Q&A — our R2 (their R3) — not UTA/AUTA — Kamlesh — OA-as-R1 https://www.linkedin.com/posts/kamlesh012_amazon-interviewexperience-sde1-activity-7435882238334078976-_HqI OA numbered R1; their R2 = story DSA → **our R1**; their R3 = **Design a Q&A platform similar to Stack Overflow — entities/models/DS** → **our R2**. **What they actually asked** Design a Q&A platform **similar to Stack Overflow** — **entities / models / DS**. Not a full HLD of SO. **Clarify** - Post question, answer, comment, vote, tag, accept? - Search: tag vs full-text? - Reputation? Auth? - In-memory for Live Code? **Classes** ```java final class User { final String userId; final String name; int reputation; User(String userId, String name) { this.userId = userId; this.name = name; } } final class Tag { final String slug; Tag(String slug) { this.slug = slug; } } class Post { final String postId; final String authorId; String body; int score; Post(String postId, String authorId, String body) { this.postId = postId; this.authorId = authorId; this.body = body; } } final class Question extends Post { String title; final Set tagSlugs = new HashSet<>(); String acceptedAnswerId; Question(String postId, String authorId, String title, String body) { super(postId, authorId, body); this.title = title; } } final class Answer extends Post { final String questionId; Answer(String postId, String authorId, String questionId, String body) { super(postId, authorId, body); this.questionId = questionId; } } final class VoteService { private final Set voted = new HashSet<>(); // userId|postId boolean vote(User u, Post p, int delta) { String k = u.userId + "|" + p.postId; if (!voted.add(k)) return false; p.score += delta; return true; } } final class QaStore { final Map questions = new HashMap<>(); final Map> answersByQ = new HashMap<>(); final Map> questionIdsByTag = new HashMap<>(); void addQuestion(Question q) { questions.put(q.postId, q); for (String t : q.tagSlugs) { questionIdsByTag.computeIfAbsent(t, x -> new ArrayList<>()).add(q.postId); } } void addAnswer(Answer a) { answersByQ.computeIfAbsent(a.questionId, x -> new ArrayList<>()).add(a); } List byTag(String slug) { List ids = questionIdsByTag.getOrDefault(slug, List.of()); List out = new ArrayList<>(); for (String id : ids) out.add(questions.get(id)); return out; } } ``` **SOLID** - **S:** vote vs store vs post body. - **O:** `Post` open for Comment later. - **L:** Answer/Question as Post. - **I:** don’t put search Elasticsearch on `Post`. - **D:** `VoteService` depends on `Post`, not SQL. **Core algorithm / DS** - HashMaps by id; tag inverted index. Search “later: inverted index / ES” in one sentence. **Follow-ups** - Accept answer: only question author; one `acceptedAnswerId`. - Scale: not this 45-min entity sketch. **If stuck:** User, Question, Answer, Tag, Vote; HashMap store; `addQuestion` / `addAnswer` / `byTag`. --- ### Logger system SOLID — our R2 same-day — AUTA — Reddit 1ueybmg https://old.reddit.com/r/LeetcodeDesi/comments/1ueybmg/amazon_sde1_auta_india_interview_experience_offer/ Reprint: amazonsdeprep `1ueybwz`. AUTA India 2025 passout; R1+R2 **same day** Bangalore onsite. R2: **designing a logger system (SOLID, patterns)**. Fuller than a priority-pack one-liner. **What they actually asked** **Logger system LLD** with **SOLID** and **patterns**. (R1 was greedy/tree/puzzle UNNAMED.) **Clarify** - Levels DEBUG..ERROR? Multiple sinks (console, file)? - Sync vs async? Format timestamp + level + message? - Singleton? (say you can construct one `Logger` in the app, not a global mutable singleton.) - Thread-safe? **Classes** ```java enum LogLevel { DEBUG, INFO, WARN, ERROR } final class LogRecord { final long ts; final LogLevel level; final String message; LogRecord(long ts, LogLevel level, String message) { this.ts = ts; this.level = level; this.message = message; } } interface LogSink { void write(String formatted); } final class ConsoleSink implements LogSink { public void write(String formatted) { System.out.println(formatted); } } final class FileSink implements LogSink { private final Path path; FileSink(Path path) { this.path = path; } public void write(String formatted) { try { Files.writeString(path, formatted + System.lineSeparator(), StandardOpenOption.CREATE, StandardOpenOption.APPEND); } catch (IOException e) { throw new UncheckedIOException(e); } } } interface LogFormatter { String format(LogRecord r); } final class PlainFormatter implements LogFormatter { public String format(LogRecord r) { return r.ts + " " + r.level + " " + r.message; } } final class Logger { private final LogLevel min; private final LogFormatter formatter; private final List sinks; private final Object lock = new Object(); Logger(LogLevel min, LogFormatter formatter, List sinks) { this.min = min; this.formatter = formatter; this.sinks = List.copyOf(sinks); } public void log(LogLevel level, String message) { if (level.ordinal() < min.ordinal()) return; LogRecord r = new LogRecord(System.currentTimeMillis(), level, message); String line = formatter.format(r); synchronized (lock) { for (LogSink s : sinks) s.write(line); } } } ``` **SOLID** - **S:** format vs sink vs filter-by-level. - **O:** new `JsonFormatter` / `SocketSink` without editing `Logger`. - **L:** any sink/formatter. - **I:** sink is `write`; formatter is `format`. - **D:** `Logger` depends on abstractions. **DIP** is the point of this IE. Patterns to name: **Strategy** (formatter, sink), **Composite** (list of sinks), optional **Decorator** (async queue wrapping a sink). Avoid preaching Singleton; if they push it, “one instance via DI, not `Logger.getInstance()` mutable global”. **Core algorithm / DS** - None beyond a list of sinks. Async: `BlockingQueue` + daemon thread (Producer-Consumer). **Follow-ups** - Thread-safety: lock around sink writes, or one queue. - Failure: file disk full — don’t crash the request path (swallow after metric). - Performance: async logger; never hold the lock while doing network I/O if you add a socket sink. **If stuck:** `log(level, msg)` + `ConsoleSink` + min-level check. Then extract interfaces and name SOLID out loud. --- ### LFU Cache + extensible cache — our R2 — not UTA/AUTA — Reddit 1idtlan https://old.reddit.com/r/leetcode/comments/1idtlan/selected_amazon_india_sde_1_full_time_new_grad/ R1 21 Nov / R2 **22 Nov 2024**: **LFU Cache** (candidate linked slug) + **LLD make that cache extensible**. Consecutive-day. Not Login Tracker. Not Bhavya LRU (different IE). **What they actually asked** Implement **LFU**, then make the cache **extensible** (eviction policy as a strategy). **Clarify** - Capacity? `get` miss -1? Tie-break = LRU among same frequency (standard LC 460)? - Thread-safe? Generic? **Classes** ```java final class CacheNode { int key, value, freq; CacheNode prev, next; CacheNode(int key, int value) { this.key = key; this.value = value; this.freq = 1; } } final class NodeList { final CacheNode head = new CacheNode(0, 0); final CacheNode tail = new CacheNode(0, 0); int size = 0; NodeList() { head.next = tail; tail.prev = head; } void addFront(CacheNode n) { n.next = head.next; n.prev = head; head.next.prev = n; head.next = n; size++; } void remove(CacheNode n) { n.prev.next = n.next; n.next.prev = n.prev; size--; } CacheNode removeLast() { if (size == 0) return null; CacheNode n = tail.prev; remove(n); return n; } } interface EvictionPolicy { void onGet(CacheNode n); void onPutNew(CacheNode n); CacheNode evict(); } final class LfuPolicy implements EvictionPolicy { private int minFreq = 0; private final Map freqMap = new HashMap<>(); public void onGet(CacheNode n) { bump(n); } public void onPutNew(CacheNode n) { freqMap.computeIfAbsent(1, f -> new NodeList()).addFront(n); minFreq = 1; } public CacheNode evict() { NodeList list = freqMap.get(minFreq); CacheNode n = list.removeLast(); if (list.size == 0) freqMap.remove(minFreq); return n; } private void bump(CacheNode n) { NodeList old = freqMap.get(n.freq); old.remove(n); if (old.size == 0) { freqMap.remove(n.freq); if (minFreq == n.freq) minFreq++; } n.freq++; freqMap.computeIfAbsent(n.freq, f -> new NodeList()).addFront(n); } } final class LruPolicy implements EvictionPolicy { private final NodeList order = new NodeList(); public void onGet(CacheNode n) { order.remove(n); order.addFront(n); } public void onPutNew(CacheNode n) { order.addFront(n); } public CacheNode evict() { return order.removeLast(); } } final class ExtensibleCache { private final int capacity; private final Map map = new HashMap<>(); private final EvictionPolicy policy; ExtensibleCache(int capacity, EvictionPolicy policy) { this.capacity = capacity; this.policy = policy; } public int get(int key) { CacheNode n = map.get(key); if (n == null) return -1; policy.onGet(n); return n.value; } public void put(int key, int value) { if (capacity == 0) return; CacheNode n = map.get(key); if (n != null) { n.value = value; policy.onGet(n); return; } if (map.size() >= capacity) { CacheNode e = policy.evict(); map.remove(e.key); } CacheNode fresh = new CacheNode(key, value); map.put(key, fresh); policy.onPutNew(fresh); } } ``` **SOLID** - **S:** DLL vs policy vs cache map. - **O:** `LruPolicy` / `LfuPolicy` without rewriting `get`/`put` — **this is the extensible ask**. - **L:** any `EvictionPolicy`. - **I:** three policy hooks. - **D:** cache depends on `EvictionPolicy`. **Core algorithm / DS** - LFU: `key → node`, `freq → DLL` (LRU order inside freq), `minFreq`. get/put O(1). - Extensible: Strategy on eviction. **Follow-ups** - FIFO policy: DLL without moving on get. - Thread-safety: one lock on `ExtensibleCache`. **If stuck:** implement LFU `get`/`put` first (freq map). Then extract `EvictionPolicy` and say LRU is another impl (point at Bhavya card). --- ### AUTA unnamed System Design (rest of hour) — our R2 — AUTA — Arijit Char — **TALK-TRACK ONLY** https://www.linkedin.com/posts/arijit-char_my-amazon-sde-1-auta-interview-experience-activity-7366548692872433664-Fw-c Tech 1 12 Aug 2024; Tech 2 **26 Aug 2024**; rejected 27 Aug. AUTA 2024/2025 grads. **What they actually asked** 15–20 min LP **UNNAMED**, then **one unnamed System Design** for the **rest of the hour**. Unexpected for an AUTA fresher. **The prompt is unnamed.** Do **not** invent caching, API gateway, or Job 10454435 “APIs/databases/caching layers” (CampusToCareer Class C) as what Arijit was asked. **Clarify (questions to ask them — this *is* the card)** 1. What is the **user-facing action** (the verb)? One sentence. 2. **Read vs write** ratio? QPS ballpark, or “single box is fine”? 3. **Entities** and uniqueness (ids)? 4. Consistency: can a read be 1s stale? 5. Single machine vs multi-AZ? (If they say “keep it simple”, stay in-process.) 6. Failure: what must not double-charge / double-ship? **How to structure ~40 min** | Min | Do | | --- | --- | | 0–5 | Repeat the prompt in your words. Freeze scope. Reject extras. | | 5–12 | Entities + APIs **they** named. Draw 4–6 boxes max (client, app, store). | | 12–25 | One deep slice: the hottest read or the write path. Data model + one invariant. | | 25–35 | Bottleneck: what breaks at 10×. One mitigation **if they asked scale**. | | 35–40 | Failure + one metric. Stop adding components. | **Do not** - Open with Redis because a blog said AUTA SD = caching. - Design SNS, or copy Rate Limiter, unless **they** said rate limit. - Treat this as evidence Job 10454435 has a published SD question. **If stuck:** “I’ll list entities, then the one happy-path method, then ask which axis you want to push (scale, consistency, failure).” --- ### Delivery stations / parcels + classes + topo — our R2 — not UTA/AUTA — LC 6369243 https://leetcode.com/discuss/post/6369243/amazon-sde-1-interview-experience-accept-kize/ **First-hand wording:** delivery stations / parcels + **classes** + **topological sort**. Same post also had max-sum switching two sorted LLs on another slot. **Do not stamp LC 962 Width Ramp. Do not stamp LC 210 Course Schedule II** (210 is linked on **6282609**, a different post). **What they actually asked** Model **delivery stations** and **parcels** with classes, plus **topo** (station/route dependencies). Exact API UNNAMED beyond that — stay on parcels + directed deps + order. **Clarify** - Station A must finish before station B (directed graph)? - Parcel has a path of stations vs global station DAG? - Cycle = invalid network? - One parcel or batch? **Classes** ```java final class Station { final String stationId; final String name; Station(String stationId, String name) { this.stationId = stationId; this.name = name; } } final class Parcel { final String parcelId; final List stationPath; Parcel(String parcelId, List stationPath) { this.parcelId = parcelId; this.stationPath = List.copyOf(stationPath); } } final class DeliveryNetwork { private final Map stations = new HashMap<>(); private final Map> mustBefore = new HashMap<>(); // u -> nodes that depend on u private final Map indegree = new HashMap<>(); void addStation(Station s) { stations.put(s.stationId, s); mustBefore.putIfAbsent(s.stationId, new ArrayList<>()); indegree.putIfAbsent(s.stationId, 0); } /** from must complete before to */ void addConstraint(String from, String to) { mustBefore.get(from).add(to); indegree.put(to, indegree.getOrDefault(to, 0) + 1); indegree.putIfAbsent(from, indegree.getOrDefault(from, 0)); } List processingOrder() { Deque q = new ArrayDeque<>(); Map deg = new HashMap<>(indegree); for (Map.Entry e : deg.entrySet()) { if (e.getValue() == 0) q.add(e.getKey()); } List order = new ArrayList<>(); while (!q.isEmpty()) { String u = q.removeFirst(); order.add(u); for (String v : mustBefore.getOrDefault(u, List.of())) { int d = deg.get(v) - 1; deg.put(v, d); if (d == 0) q.add(v); } } if (order.size() != stations.size()) throw new IllegalStateException("cycle"); return order; } } ``` **SOLID** - **S:** Station/Parcel vs graph ops. - **O:** `RoutingPolicy` later without stuffing it into `Parcel`. - **L:** n/a. - **I:** network API is add + order, not a god “Amazon Logistics”. - **D:** topo lives on `DeliveryNetwork`. **Core algorithm / DS** - DAG adjacency + **Kahn** indegree queue. O(V+E). Cycle if not all stations emitted. - This is **your** graph, described as delivery stations — not “LC 210” even though the algorithm is the same family. **Follow-ups** - Parcel path must be a subsequence of the global topo order — validate in O(path). - Failure: cycle → reject config, don’t ship. **If stuck:** `Station`, `Parcel`, `addConstraint`, Kahn’s algorithm. Say “topo order of stations”. --- ### Searchable-prefix top-K historical terms — unlabeled / later in loop — not UTA/AUTA — LC 6282609 — SERP only https://leetcode.com/discuss/post/6282609/ **I could not verify** the full body this pass (**Cloudflare**). SERP wording: **searchable-prefix → top-K historical terms** (Trie). Round split R1 vs R2 **not labeled** in notes — do not invent the day. CS II **210 is linked on this post only** — do not copy 210 onto LC 6369243. **What they actually asked** (SERP, not a verified transcript) Prefix search over **historical terms**, return **top-K**. Treat as a **pattern card**. **Clarify** (if this lands) - Historical = past queries with counts? Recency vs frequency? - K fixed? Unicode? - In-memory Trie? **Classes** (pattern sketch, not “this was the official API”) ```java final class TermNode { final Map kids = new HashMap<>(); int count; // if this node ends a term String term; } final class PrefixTopK { private final TermNode root = new TermNode(); void add(String term, int inc) { TermNode n = root; for (int i = 0; i < term.length(); i++) { n = n.kids.computeIfAbsent(term.charAt(i), c -> new TermNode()); } n.term = term; n.count += inc; } List topK(String prefix, int k) { TermNode n = root; for (int i = 0; i < prefix.length(); i++) { n = n.kids.get(prefix.charAt(i)); if (n == null) return List.of(); } PriorityQueue heap = new PriorityQueue<>(Comparator.comparingInt(a -> a.count)); dfs(n, k, heap); List out = new ArrayList<>(); while (!heap.isEmpty()) out.add(heap.poll().term); Collections.reverse(out); return out; } private void dfs(TermNode n, int k, PriorityQueue heap) { if (n.term != null) { heap.offer(n); if (heap.size() > k) heap.poll(); } for (TermNode c : n.kids.values()) dfs(c, k, heap); } } ``` **SOLID** — Trie node vs query service; optional `RankingPolicy` (count vs recency). **Core algorithm / DS** - Trie + bounded min-heap of size K on the subtree. Precompute top-K per node if they push QPS. **Follow-ups** - If body stays unverified, say “pattern: Trie + heap” and ask them to confirm ranking. **If stuck:** insert terms in a Trie; DFS subtree; heap of size K. --- ### Spring login Controller / Facade / Service / Repository — our R3/HM — not UTA/AUTA — Bhavya — **not R2, not Login Tracker** https://www.linkedin.com/posts/bhavya-77816218a_amazon-interviewexperience-sde1-activity-7473680829714546688-jeL9 HM (their R3): DRDO / Info Edge projects; **Spring login Controller / Facade / Service / Repository**; follow-up **eliminate if-else validations in the façade**. LRU was Interview 2. This is **not** Login Tracker. **What they actually asked** Layer a **login** flow in Spring: Controller, Facade, Service, Repository. Then remove if-else validation piles in the façade. **Clarify** - Username/password only? Session vs JWT? (Don’t over-build.) - Validation = null/format vs credential check? **Classes** ```java final class LoginRequest { final String username; final String password; LoginRequest(String username, String password) { this.username = username; this.password = password; } } interface Validator { void validate(LoginRequest req); // throws if invalid } final class NonEmptyValidator implements Validator { public void validate(LoginRequest req) { if (req.username == null || req.username.isBlank()) throw new IllegalArgumentException("username"); if (req.password == null || req.password.isEmpty()) throw new IllegalArgumentException("password"); } } interface UserRepository { Optional findByUsername(String username); } final class UserRecord { final String username; final String passwordHash; UserRecord(String username, String passwordHash) { this.username = username; this.passwordHash = passwordHash; } } final class AuthService { private final UserRepository repo; AuthService(UserRepository repo) { this.repo = repo; } boolean authenticate(LoginRequest req) { return repo.findByUsername(req.username) .filter(u -> u.passwordHash.equals(hash(req.password))) .isPresent(); } private String hash(String p) { return Integer.toHexString(p.hashCode()); } // stub } final class LoginFacade { private final List validators; private final AuthService auth; LoginFacade(List validators, AuthService auth) { this.validators = validators; this.auth = auth; } boolean login(LoginRequest req) { for (Validator v : validators) v.validate(req); // no if-else ladder return auth.authenticate(req); } } final class LoginController { private final LoginFacade facade; LoginController(LoginFacade facade) { this.facade = facade; } boolean postLogin(LoginRequest req) { return facade.login(req); } } ``` **SOLID** — Facade orchestrates; Service is auth; Repository is IO; **OCP** on validators (the if-else follow-up). **S** so Controller stays HTTP-thin. **Follow-ups** — chain of validators; don’t put SQL in the controller. **If stuck:** four class names + “validators as a list, not if-else”. --- ### Student rollNo / marks / name / rank HashMap OOD — our R1 — UTA — LC 6653463 https://leetcode.com/discuss/post/6653463/amazon-software-dev-engineer-1-universit-dtk5/ University Talent Acquisition named. R1: **student rollNo/marks/name/rank HashMap OOD**; **HashMap internals**; count BT nodes with two children. **What they actually asked** OOD for students with **rollNo, marks, name, rank**, using **HashMap**. Then **how HashMap works**. **Clarify** - Rank = dense rank on marks? Ties? - Key = rollNo? Unique? - Recompute rank on each insert vs query-time sort? **Classes** ```java final class Student { final int rollNo; String name; int marks; int rank; Student(int rollNo, String name, int marks) { this.rollNo = rollNo; this.name = name; this.marks = marks; } } final class ClassRoster { private final Map byRoll = new HashMap<>(); void add(Student s) { byRoll.put(s.rollNo, s); recomputeRanks(); } Student get(int rollNo) { return byRoll.get(rollNo); } void recomputeRanks() { List all = new ArrayList<>(byRoll.values()); all.sort((a, b) -> Integer.compare(b.marks, a.marks)); for (int i = 0; i < all.size(); i++) all.get(i).rank = i + 1; } } ``` **SOLID** — `Student` is data; `ClassRoster` owns the map and rank rule. Rank policy could be a strategy if they ask dense vs competition rank. **Core algorithm / DS** - HashMap rollNo → Student. Rank: sort O(n log n) on mutation (fine for Live Code). - **HashMap internals (they asked):** array of buckets; `hash ^ (hash >>> 16)` (Java); index `hash & (n-1)` for power-of-two capacity; collision = linked list then treeify at 8; `equals` after hash; load factor 0.75 → resize 2×; key must have stable `hashCode`/`equals`. `rollNo` as `Integer` is fine. **Follow-ups** - Why not TreeMap? Sorted by roll, not marks. TreeMap is O(log n) get. - ConcurrentHashMap vs HashMap: no structural sync on `HashMap`. **If stuck:** `Map`, `add`/`get`, sort by marks to fill `rank`. Then 4 sentences on buckets + equals. --- ### Alexa charge / battery LLD SOLID — BR — not UTA/AUTA — GFG sde-1-29 — year-out — short https://www.geeksforgeeks.org/interview-experiences/amazon-interview-experience-for-sde-1-29/ 2022-era loop. BR: **Alexa charge / battery LLD SOLID**. Not Connect Sticks “Alexa ropes”. **What they actually asked** LLD around **Alexa charging / battery**, judged on **SOLID**. **Clarify** — device vs battery vs charger protocol? One device? ```java interface Battery { int percent(); void consume(int delta); void charge(int delta); } final class LithiumBattery implements Battery { private int percent = 100; public int percent() { return percent; } public void consume(int delta) { percent = Math.max(0, percent - delta); } public void charge(int delta) { percent = Math.min(100, percent + delta); } } interface PowerSource { void supply(Battery b, int delta); } final class UsbCharger implements PowerSource { public void supply(Battery b, int delta) { b.charge(delta); } } final class AlexaDevice { private final Battery battery; private final PowerSource charger; AlexaDevice(Battery battery, PowerSource charger) { this.battery = battery; this.charger = charger; } void play() { battery.consume(1); } void plugIn() { charger.supply(battery, 10); } boolean needsCharge() { return battery.percent() < 20; } } ``` **SOLID** — Device does not own chemistry (**D** + **S**). New `SolarDock` is **O**. Battery impls **L**. Tiny interfaces **I**. **Follow-ups** — low-battery callback (Observer). Don’t design Alexa cloud. **If stuck:** `Battery` interface, `AlexaDevice` holds one, `charge`/`consume`. --- ### LED RGB OOPS / Office Structure OOD / pile of books — older GFG — compact Not UTA-default 2026. Opened remainder 2021–23 (slugs often republished 2025). #### LED RGB OOPS/SOLID — our R1 analogue — GFG sde-1-16 (OA-as-R1) https://www.geeksforgeeks.org/interview-experiences/amazon-interview-experience-for-sde-1-16/ **Asked:** **LED RGB OOPS/SOLID**. ```java interface ColorSink { void setRgb(int r, int g, int b); } final class LedStrip implements ColorSink { int r, g, b; public void setRgb(int r, int g, int b) { this.r = clamp(r); this.g = clamp(g); this.b = clamp(b); } private static int clamp(int x) { return Math.max(0, Math.min(255, x)); } } interface Effect { void apply(ColorSink sink); } final class SolidEffect implements Effect { private final int r, g, b; SolidEffect(int r, int g, int b) { this.r = r; this.g = g; this.b = b; } public void apply(ColorSink sink) { sink.setRgb(r, g, b); } } final class BlinkController { private final ColorSink sink; private final Effect effect; BlinkController(ColorSink sink, Effect effect) { this.sink = sink; this.effect = effect; } void tick() { effect.apply(sink); } } ``` SOLID: effect vs hardware. If stuck: `Led` with r/g/b + `setColor`. #### Office Structure OOD — our R1 — GFG off-campus-8 https://www.geeksforgeeks.org/interview-experiences/amazon-interview-experience-for-sde-1-off-campus-8/ **Asked:** **Office Structure OOD**. Composite: Office → Building → Floor → Room (or Employee reporting tree). Pick one and say it. ```java interface OrgNode { String name(); int headcount(); } final class Employee implements OrgNode { private final String name; Employee(String name) { this.name = name; } public String name() { return name; } public int headcount() { return 1; } } final class Department implements OrgNode { private final String name; private final List children = new ArrayList<>(); Department(String name) { this.name = name; } void add(OrgNode n) { children.add(n); } public String name() { return name; } public int headcount() { int s = 0; for (OrgNode n : children) s += n.headcount(); return s; } } ``` Same Composite as file library. If they meant physical office: `Room extends Space`, `Floor` holds rooms. #### Pile of books DS — our R2 — same off-campus-8 **Asked:** **pile of books DS**. Stack of books (LIFO pile). Optional search-by-title = not O(1) on a pile — say so. ```java final class BookItem { final String title; BookItem(String title) { this.title = title; } } final class BookPile { private final Deque pile = new ArrayDeque<>(); void placeOnTop(BookItem b) { pile.push(b); } BookItem takeTop() { return pile.pop(); } BookItem peek() { return pile.peek(); } boolean isEmpty() { return pile.isEmpty(); } } ``` Follow-up “find a title”: scan O(n), or secondary HashMap title → count (not position). If stuck: “it’s a stack”. --- ### NMF / INTERN (one line, not cards) Canada cart/checkout (Jay Patel AUTA Canada), intern custom eviction DS (Saloni), 5-round board-game LLD (LC 6813913 OA-as-R1 first live): **see NMF / INTERN appendix** — not FTE §5.C. ## 4. Leadership Principles — all 16 + every exact prompt in bible §5.D Notes for Adarsh. These are answers to LP prompts **other** SDE I / UTA / AUTA candidates reported. Your loop may differ. Unnamed stays unnamed. Job **10454435** still has no public IE that names a live-round LP. Do not treat this section as a prediction of 18 Aug. **Live Code vs production:** DSA in Java. Internships and projects on the resume were Python / TypeScript (FastAPI, NestJS, LangGraph, React). Say that once if they ask stack; do not pretend Ylogx/IQVIA shipped in Java. **InstaRecon (if they open GitHub):** one line — security awareness demo, consent, no production attacks — then move to StratifyLabs / Argus / Ylogx / IQVIA. No phishing or credential steps. **Primary spread (no project as PRIMARY on more than 3 LPs):** | LP | Primary | Backup | Optional third | | --- | --- | --- | --- | | Customer Obsession | GiftedBooks | Ylogx SQL RAG chatbot | Argus alerts | | Ownership | Ylogx RLS/RBAC + 99.9% | Horizon ERC software | IQVIA agent evals | | Invent and Simplify | IQVIA Hybrid RAG + test-case gen | StratifyLabs browser inference | GiftedBooks PYQ topics | | Are Right, A Lot | Argus 73%→89% mAP | Ylogx latency measurement | IQVIA LangSmith | | Learn and Be Curious | IQVIA LangGraph | Horizon ROS2 | hackathons | | Hire and Develop the Best | IEDC CUSAT Tech Team | Horizon teammates | hackathon teammates | | Insist on Highest Standards | Argus 15k images + mAP gate | Ylogx 99.9% / sub-210ms | GiftedBooks 99.5% | | Think Big | StratifyLabs marketplace + 3D lab | IQVIA Deep Research 200+ sites | Argus 20+ cameras | | Bias for Action | Horizon ERC 2024 date | CodeRecet 1st / 8 hackathons | Ylogx cache ship | | Frugality | Ylogx Redis −35% + CloudFront/ECS | Horizon costmap vs extra hardware | StratifyLabs browser vs GPU farm | | Earn Trust | GiftedBooks RAG + 99.5% | Ylogx RLS 3-tier | IQVIA LangSmith before ship | | Dive Deep | Ylogx Redis latency + RLS | IQVIA retrieval quality | Argus eval set | | Have Backbone; Disagree and Commit | IQVIA hybrid vs vector-only | Ylogx RLS in DB vs app-only | Horizon software vs more sensors | | Deliver Results | Horizon 17th/80+ | Ylogx 40% / 99.9% / 210ms | GiftedBooks doubt time | | Strive to be Earth’s Best Employer | Horizon knowledge sharing | IEDC CUSAT | hackathon teammates | | Success and Scale Bring Broad Responsibility | Argus 20+ cameras + 2x compliance | Ylogx ALB/ECS | IQVIA evals so wrong answers don’t scale | Ylogx 403/noindex SEO is **prep-only** — not on the Aug 2026 resume. Do not lead Dive Deep with it. Use Redis + RLS (on-resume) or IQVIA retrieval quality. --- ### 4.A All 16 LPs (2–3 STAR options each) #### Customer Obsession — primary GiftedBooks (1/3) **LPs this story can hit:** Customer Obsession, Earn Trust, Deliver Results (backup). **Primary STAR (~60s)** - **S:** Students on GiftedBooks were losing hours on doubts even with VR labs and PDFs in front of them. - **T:** Cut time-to-answer without inventing content; answers had to come from the student’s own material. - **A:** (1) Shipped RAG over uploaded PDFs so Q&A was contextual, not generic chatbot. (2) Kept API responses sub-300ms and the suite at 99.5% uptime so the assistant was usable during study, not a demo. (3) Added prioritized topic suggestions from PYQ analysis so students studied what exams actually ask. - **R:** Resume: reading efficiency +35%, engagement +50%, 2.5x faster content comprehension, average doubt resolution from hours to 3–10 minutes. **Backup (Ylogx chatbot):** Non-technical users could not pull analysis from Postgres without an analyst. LangChain SQL RAG chatbot; data-analysis productivity +65%. Same LP, employer story. **Optional (Argus):** PPE alerts so floor staff see violations, not a dashboard only engineers can read. Safety violations −50%, compliance 2x. **Probes** - **Metric:** GiftedBooks: hours → 3–10 min, +35% / +50% / 2.5x, sub-300ms, 99.5%. Ylogx: +65% analysis productivity. Do not invent student headcount. - **What failed first:** PDF Q&A that is slow or generic does not replace a teaching assistant. First pass without PYQ still left people guessing *what* to study. - **Differently:** Put a small RAG eval set (wrong-citation vs grounded) in earlier, same habit as IQVIA LangSmith — resume does not claim GiftedBooks had LangSmith. **GitHub:** `giftedbooks` README currently describes AegisAI (mismatch). Resume is authoritative. Do not mix AegisAI into this STAR. --- #### Ownership — primary Ylogx (1/3) **LPs this story can hit:** Ownership, Earn Trust (backup), Dive Deep (backup). **Primary STAR (~60s)** - **S:** Ylogx intern (Nov 2024–Oct 2025). Full-stack AI BI on FastAPI + NestJS + Postgres. Chatbot and reports would have been wrong *and* a leak if org boundaries were app-only. - **T:** Own correctness and isolation for three org tiers, not just “chatbot works on my user.” - **A:** (1) RLS + RBAC for 3 organizational tiers in the data path the bot and reports share. (2) Kept the BI app at 99.9% uptime while report generation went 40% faster. (3) Redis cache on the bot path: −35% database latency so security did not mean “just add a check and ignore load.” - **R:** 40% faster reports, 99.9% uptime, +65% analysis productivity, −35% bot DB latency, 30 KPI dashboards, ops efficiency +60%, sub-210ms, CloudFront/ECS/Docker CI/CD, GoDaddy DNS + Route 53 + ALB. **Backup (Horizon):** Core software on the ERC 2024 rover. Competition date does not slip. GStreamer 60 FPS + costmap were owned as ship-blockers, not “someone else’s camera ticket.” 17th / 80+ teams. Public `Gstreamer-UDP` is a supporting webcam-stream artifact, not a second project. **Optional (IQVIA):** Own evals/tracing on Deep Research + Hybrid RAG, not “agent returned text.” LangSmith tracing, evals, test-case gen from 200+ page BRDs. **Probes** - **Metric:** 99.9%, 40%, −35%, 3 tiers, sub-210ms. Horizon: 17th/80+, 60 FPS, −55% collision risk. - **What failed first:** App-only role checks fail closed-demo and open in a JOIN. Untuned report SQL made “AI BI” a waiting room. - **Differently:** Treat RLS policies as tested artifacts (denied-cross-tier cases) from day one, same way Argus treated mAP as a gate. --- #### Invent and Simplify — primary IQVIA (1/3) **LPs this story can hit:** Invent and Simplify, Learn and Be Curious, Have Backbone (same program, different angle). **Primary STAR (~60s)** - **S:** IQVIA intern (Apr 2026–present). Research and BRDs were 200+ websites / 200+ page PDFs. Manual synthesis and hand-written test cases do not scale. - **T:** One retrieval/orchestration path that ranks sources and turns BRDs into test cases with traces, not a pile of prompts. - **A:** (1) LangGraph multi-agent Deep Research: Firecrawl, Bing, DuckDuckGo, Google Playwright; rank information across 200+ sites. (2) Hybrid RAG: Azure AI Search (Hybrid + Semantic) + GraphDB + LangGraph for adaptive retrieval on 200+ page BRD/PDFs. (3) LangSmith tracing/evals and test-case generation so the “invention” is checkable. - **R:** Resume: 200+ websites ranked; 200+ page BRD/PDF processed; stateful agents + evals + test-case gen. Do not add Qdrant — that is prep wording; resume is Azure AI Search + GraphDB. **Backup (StratifyLabs):** Browser-based inference instead of a local training loop for every tweak. ML iteration −30%. Marketplace 50+ models/datasets. Do not invent README features; StratifyLabs GitHub README is default Next.js. **Optional (GiftedBooks):** PYQ topic suggestions instead of “read the whole PDF.” +35% reading efficiency. **Probes** - **Metric:** 200+ sites, 200+ page docs, StratifyLabs −30% iteration / 50+ marketplace items. - **What failed first:** Vector-only on long BRDs retrieves similar paragraphs, not the requirement graph. Untraced agents cannot tell a bad rank from a bad generator. - **Differently:** Freeze an eval slice of BRD sections → expected test cases before adding another search tool. --- #### Are Right, A Lot — primary Argus (1/3) **LPs this story can hit:** Are Right A Lot, Insist on Highest Standards, Success and Scale. **Primary STAR (~60s)** - **S:** Argus PPE / attendance on camera. A detector that “looks fine” in a notebook is not right on a floor. - **T:** Move from a weak eval number to a number you would actually alert on. - **A:** (1) Treat 73% mAP as a fail, not a starting blog metric. (2) Train/eval on 15,000+ images; iterate YOLOv9 until 89% mAP. (3) Run at 24 FPS so the “right” model is also the one that keeps up with the stream. Postgres logs for what fired. - **R:** 73%→89% mAP; 24 FPS; safety violations −50%; 20+ camera feeds; compliance 2x. GitHub `argus-stream-api-server` exists as a supporting artifact. **Backup (Ylogx):** “Faster reports” only after measuring: 40% report gen, sub-210ms, Redis −35% bot DB latency. Right = measured, not “feels snappy.” **Optional (IQVIA):** LangSmith evals before treating Deep Research / test-case gen as done. **Probes** - **Metric:** 73→89 mAP, 15k images, 24 FPS, −50% violations, 2x compliance, 20+ cameras. - **What failed first:** 73% mAP — too many misses for PPE. Shipping that would scale *wrong* alerts. - **Differently:** Lock a held-out camera/site split earlier so 89% is not an accident of train/test leak. Resume does not name the split; do not invent one. --- #### Learn and Be Curious — primary IQVIA (2/3) **LPs this story can hit:** Learn and Be Curious, Invent and Simplify, Dive Deep (backup). **Primary STAR (~60s)** - **S:** Multi-agent research + hybrid retrieval + tracing was not the Ylogx FastAPI/NestJS day job. LangGraph / LangSmith / Azure AI Search hybrid were new. - **T:** Learn enough to architect, not tutorial-complete. - **A:** (1) LangGraph for stateful multi-agent Deep Research across 200+ sites. (2) Hybrid + Semantic search + GraphDB because long BRDs are not a single embedding query. (3) LangSmith tracing/evals so curiosity has a stop condition (pass/fail cases), including test-case gen. - **R:** Platform as on resume: 200+ sites ranked; 200+ page BRDs; evals + test-case gen. **Backup (Horizon):** ROS2, GStreamer 60 FPS, ZED 2 at 2M+ pts/s, RViz/Gazebo, costmap fusion — not a web intern stack. 17th/80+, obstacle detection +40%, collision risk −55%. **Optional (hackathons):** 8 national/regional events; 1st CodeRecet, MLH Best Project, Magnathon 2.0 runner-up — learn a stack in hours, ship. No fake prize metrics beyond the resume. **Probes** - **Metric:** IQVIA 200+/200+; Horizon 60 FPS, 2M+ pts/s, +40%, −55%, 17th/80+. - **What failed first:** Treating “RAG” as one vector index. Long BRDs needed hybrid + graph + traces. - **Differently:** A one-page “what we will not retrieve” list earlier (out of scope for a BRD chapter) so agents do not wander 200 sites without a ranker. **Mapped GFG 2025 named LP:** this card is the Learn and Be Curious answer. Pair with Dive Deep (Ylogx Redis/RLS) if they ask both. --- #### Hire and Develop the Best — primary IEDC CUSAT (1/3 on IEDC/education) **Honesty lock:** Resume: Software Team Member, Team Horizon; Tech Team, IEDC CUSAT. **Not** a people manager. No invented reports, ratings, or headcount. **Primary STAR (~60s)** - **S:** IEDC CUSAT Tech Team + CUSAT CSE (CGPA 8.42/10). New people joining club/hackathon work did not share one stack. - **T:** Raise the floor so a teammate can ship, not collect a “mentor” title. - **A:** (1) Worked as Tech Team: shared setup, reviews, and “here is the path we already burned” on tools we actually used. (2) Same pattern at hackathons (8 national/regional): pair on the risky module instead of hoarding it. (3) On Horizon, software-team knowledge (ROS2/camera/costmap) had to be usable by the rest of the rover team, not a solo notebook. - **R:** Honest outcomes on resume: IEDC Tech Team; Horizon 17th/80+ as core software; 1st CodeRecet, MLH Best Project, Magnathon 2.0 runner-up. Do not claim you hired anyone. **Backup (Horizon teammates):** Unblock camera/mapping so the group can run ERC, not “I did their job for credit.” **Optional (hackathon teammates):** Same 8-hackathon set. Name collaboration, not management. **Probes** - **Metric:** 8.42 CGPA, 8 hackathons, named placements, 17th/80+. No “N mentees.” - **What failed first:** If only you understand GStreamer/ZED, the rover fails when you are on another subsystem. - **Differently:** Write the 10-line runbook (topic names, launch order) earlier. Resume does not claim a wiki; say you would, not that you did. --- #### Insist on Highest Standards — primary Argus (2/3) **Primary STAR (~60s)** - **S:** Industrial safety CV. 73% mAP is a model card, not a standard you alert humans on. - **T:** Standard = eval number + live FPS + logged alerts. - **A:** (1) 15,000+ images, not a toy set. (2) YOLOv9 73%→89% mAP. (3) 24 FPS on the stream; Postgres logs; containerized path to 20+ cameras. - **R:** −50% safety violations, 2x compliance. **Backup (Ylogx):** 99.9% uptime, sub-210ms, CI/CD on ECS/Docker — BI that is down is not “AI.” **Optional (GiftedBooks):** 99.5% uptime + sub-300ms; a study assistant that times out during exams is not a product. **Probes** - **Metric:** 15k, 89% mAP, 24 FPS, 99.9%, 210ms, 99.5%, 300ms. - **What failed first:** 73% mAP. Or a chatbot that hits Postgres on every NL turn (Ylogx before Redis). - **Differently:** Publish the fail cases (missed helmet, leaked tier, timeout) as the standard, not only the happy metric. --- #### Think Big — primary StratifyLabs (1/3) **Primary STAR (~60s)** - **S:** CV work was stuck in local iteration. StratifyLabs is a CV SaaS with a 3D simulation lab (stratifylabs.design), not a one-model demo. - **T:** Make experiment → share → reuse the default, not a Colab per person. - **A:** (1) 3D sim lab for real-time experimentation/prototyping. (2) Browser-based inference: ML iteration −30%. (3) Marketplace 50+ pretrained models/datasets, community profiles, URDF editor with WebGL; Gemini RAG bots for the simulated environment. - **R:** −30% iteration; 50+ marketplace items. Do not add GitHub-README features that are not on the resume. **Backup (IQVIA Deep Research):** 200+ websites, ranked, multi-agent — research as a platform, not one Firecrawl script. **Optional (Argus):** 20+ cameras, not one webcam demo. **Probes** - **Metric:** −30%, 50+ models/datasets, 200+ sites, 20+ cameras. - **What failed first:** Local-only inference made every experiment a machine problem. Vector-only research did not rank 200 sources. - **Differently:** A clearer “what is marketplace vs what is your fine-tune” boundary earlier. Do not invent a GTM number. --- #### Bias for Action — primary Horizon (1/3) **Primary STAR (~60s)** - **S:** Team Horizon, Feb–Jun 2024. ERC 2024 date is fixed. Semi-autonomous Mars rover, ROS2. - **T:** Ship perception + planning that can run, not a perfect lab stack after the event. - **A:** (1) Real-time camera 60 FPS with GStreamer (supporting public repo: Gstreamer-UDP webcam stream — same family, not a different bullet). (2) ZED 2 mapping 2M+ pts/s into RViz/Gazebo. (3) Costmap + sensor fusion + predictive planning instead of waiting on extra hardware. - **R:** 17th globally / 80+ teams; obstacle detection +40%; collision risk −55%. **Backup (hackathons):** 1st CodeRecet; MLH Best Project; Magnathon 2.0 runner-up; 8 events. Action = production-ready deploy in the window, as the resume states. **Optional (Ylogx Redis):** Measure bot DB latency, ship cache, −35% — do not wait for a rewrite. **Probes** - **Metric:** 17th/80+, 60 FPS, 2M+ pts/s, +40%, −55%. Hackathons: named placements only. - **What failed first:** A rover that maps in bags but has no costmap still collides. Action without fusion is just a fast video. - **Differently:** Time-box “one sensor vs fusion” with a collision-risk number earlier (resume has −55% after the work). --- #### Frugality — primary Ylogx (2/3) **Primary STAR (~60s)** - **S:** BI + SQL RAG on Postgres. Every NL question hitting the DB is money and latency. - **T:** Cut load without buying a bigger instance as the first move. - **A:** (1) Redis cache on the bot path: −35% database latency. (2) Deploy CloudFront + ECS + Docker CI/CD instead of over-provisioning a snowflake host. (3) ALB + Route 53 + GoDaddy DNS — one routing path, sub-210ms. - **R:** −35% bot DB latency, sub-210ms, 99.9% uptime, 40% faster reports. **Backup (Horizon):** Costmap + fusion (−55% collision risk) vs adding hardware. Software on the sensors you have. **Optional (StratifyLabs):** Browser inference (−30% ML iteration) vs everyone needing a training box. **Probes** - **Metric:** −35%, 210ms, −55% collision, −30% iteration. No invented AWS bill. - **What failed first:** Uncached SQL RAG. Extra rover sensors as the default spend. - **Differently:** Cache invalidation rules written down with RLS (cached answer still must be tier-correct). Resume does not detail TTL; do not invent one. --- #### Earn Trust — primary GiftedBooks (2/3) **Primary STAR (~60s)** - **S:** Students trust a RAG tutor with their PDFs and exam prep. Hallucinated citations and downtime both burn that. - **T:** Ground answers in the upload; keep the suite up. - **A:** (1) Contextual PDF Q&A, not a general LLM with a textbook vibe. (2) sub-300ms API, 99.5% uptime. (3) PYQ-prioritized topics so the product is honest about what matters for *their* exam, not a random syllabus. - **R:** Doubt time hours → 3–10 min; +35% / +50% / 2.5x as on resume. **Backup (Ylogx RLS):** 3 org tiers. Trust = you cannot see another org’s rows. RBAC + RLS, not a UI hide. **Optional (IQVIA):** LangSmith evals/traces before research/test cases go to whoever consumes the BRD. **Probes** - **Metric:** 99.5%, 300ms, 3–10 min; Ylogx 3 tiers; do not invent zero-incident claims. - **What failed first:** Ungrounded Q&A. App-only RBAC. - **Differently:** Same eval habit as IQVIA on GiftedBooks citations. Not claimed on resume — say you would add it. --- #### Dive Deep — primary Ylogx (3/3 Ylogx primaries full) **Primary STAR (~60s)** — last-bug / latency / isolation, **not** SEO - **S:** SQL RAG chatbot was “working” while bot database latency and cross-tier risk were the real product. Resume: RLS/RBAC 3 tiers + Redis −35% bot DB latency. - **T:** Find whether slowness was query shape, missing cache, or security checks done in the wrong layer. - **A:** (1) Measure bot DB latency, not only “SQL returned.” (2) Put isolation in Postgres RLS + RBAC for 3 tiers so a JOIN cannot outrun the app. (3) Redis cache for the hot bot path (−35%) without skipping RLS. - **R:** −35% bot DB latency, +65% analysis productivity, 99.9% uptime still held. **Backup (IQVIA retrieval):** Wrong chunks on 200+ page BRDs. Deep dive = hybrid+semantic vs vector-only + GraphDB + LangSmith traces, not another prompt. **Optional (Argus):** 73% mAP — dive into data/eval, not a bigger backbone as the first story. 15k images → 89%. **Probes** - **Metric:** −35%, 3 tiers, 200+ page BRDs, 73→89 mAP. - **What failed first:** Assuming the generator was wrong when retrieval/tier/cache was wrong. - **Differently:** One dashboard for p95 bot query time + denied RLS probes. Resume does not name p95; say latency was measured enough to claim −35%. **Do not use:** Ylogx 403/noindex www vs non-www (prep only). --- #### Have Backbone; Disagree and Commit — primary IQVIA (3/3 IQVIA primaries full) **Primary STAR (~60s)** - **S:** Default for “RAG on PDFs” is vector-only. IQVIA BRDs are 200+ pages; test-case gen from the wrong section is expensive. - **T:** Argue for Hybrid + Semantic Azure AI Search + GraphDB + traces, not ship the demo index. - **A:** (1) State the failure mode: similar embeddings ≠ requirement coverage. (2) Propose Hybrid + Semantic + GraphDB + LangGraph adaptive retrieval. (3) Commit via LangSmith evals/test-case gen — once the path is chosen, instrument it rather than keep debating tools. - **R:** Hybrid RAG as on resume; 200+ page BRDs; evals + test-case gen. Disagree on retrieval; commit on evals. **Backup (Ylogx):** RLS in the database vs app-only filters. Disagree because app-only fails on raw SQL/JOINs. Commit: 3-tier RLS + RBAC as the platform rule. **Optional (Horizon):** Software costmap vs “buy another sensor.” Commit to fusion on ZED 2 + costmap; −55% collision risk. **Probes** - **Metric:** 200+ pages, 3 tiers, −55% collision. No invented “I overruled my manager.” - **What failed first:** Vector-only. App-only RBAC. - **Differently:** Write the decision (hybrid vs vector) as an eval table before the argument so commit is on numbers. **Conflict framing:** Technical disagreement with a teammate/stakeholder who wanted the faster vector-only or app-only path. No named fight on the resume. Do not invent a manager blow-up. --- #### Deliver Results — primary Horizon (2/3) **Primary STAR (~60s)** - **S:** ERC 2024, 80+ international teams. Horizon software intern Feb–Jun 2024. - **T:** A rover that runs the challenge, not a lab video. - **A:** (1) GStreamer 60 FPS feed. (2) ZED 2 2M+ pts/s mapping. (3) Costmap planning, fusion, +40% obstacle detection. - **R:** 17th place globally / 80+ teams; −55% collision risk. **Backup (Ylogx):** 40% faster reports, 99.9% uptime, sub-210ms, +65% analysis, +60% ops from 30 KPI dashboards. Use if they want internship metrics. **Optional (GiftedBooks):** Hours → 3–10 min doubts; +35% / +50% / 2.5x. **Probes** - **Metric:** 17th/80+, 40%, 99.9%, 210ms, 3–10 min. - **What failed first:** Perception without planning (Horizon). Reports without uptime (Ylogx). - **Differently:** Sequence demo-risk items (60 FPS, costmap) on a calendar to the ERC date earlier. --- #### Strive to be Earth’s Best Employer — primary Horizon (3/3 Horizon primaries full) **Honesty lock:** Same as Hire and Develop. Teammate environment, not Amazon-scale HR. No fake people-management. **Primary STAR (~60s)** - **S:** Horizon rover software is unusable if camera/mapping knowledge lives in one head. ERC is a team score. - **T:** Make the software path teachable under a fixed date. - **A:** (1) Work as software team member, not a hero module. (2) Share GStreamer/ZED/costmap constraints with the rest of the team so they can integrate. (3) Same habit at IEDC/hackathons: the person next to you can run the build. - **R:** 17th/80+ is a team result. IEDC Tech Team + 8 hackathons on resume. Do not claim retention surveys. **Backup (IEDC CUSAT):** Tech Team — help people join and ship. CGPA 8.42 is education, not this LP’s metric. **Optional (hackathons):** MLH / CodeRecet / Magnathon teammates. Help juniors/peers on the critical path. **Probes** - **Metric:** Team rank 17th/80+. No invented “happiness score.” - **What failed first:** Siloed ROS nodes. - **Differently:** Pair earlier on launch files. Do not invent a mentoring program name. --- #### Success and Scale Bring Broad Responsibility — primary Argus (3/3 Argus primaries full) **Primary STAR (~60s)** - **S:** One camera demo does not create safety. Wrong alerts at 20+ cameras scale harm (alarm fatigue) as well as good. - **T:** Only scale a detector that passed mAP; log what you alert. - **A:** (1) Do not scale 73% mAP. (2) 89% mAP, 24 FPS, 15k images. (3) Containerized 20+ feeds, Postgres logs, alerts that cut violations 50% and 2x compliance. - **R:** 20+ cameras, −50% violations, 2x compliance. **Backup (Ylogx):** ALB + ECS + CloudFront — scale the BI path that already has RLS. 99.9%, 210ms. Scaling without RLS scales leaks. **Optional (IQVIA):** Evals so ranked research / generated tests do not scale garbage across 200+ pages/sites. **Probes** - **Metric:** 20+ cameras, 89% mAP, 99.9%, 200+ docs/sites. - **What failed first:** Scaling a 73% model. Scaling SQL RAG without cache/RLS. - **Differently:** Per-camera error budget. Resume does not state it — say you would add it. --- ### 4.B Map EVERY exact §5.D prompt to one primary story + probes Exact wording from Question-Research-BIBLE.md §5.D (plus the extra rows that section points at). Unnamed → default pair at the bottom. These are what other candidates were asked; not a 10454435 list. | Exact prompt (bible) | Mapped | Primary story | Probes if they stay | | --- | --- | --- | --- | | Learn and Be Curious; Dive Deep | R1 GFG 2025 (OA-as-R1 first live) | **Learn:** IQVIA LangGraph §4.A. **Dive Deep:** Ylogx Redis+RLS §4.A | How you knew retrieval vs latency was the bug; eval/latency number | | two LP UNNAMED (went poorly) | R2 same GFG 2025 | Default pair: Dive Deep (Ylogx) + Deliver Results (Horizon 17th **or** IQVIA evals) | Depth on Action, not titles | | current role; last time you deep-dived a bug; conflict coworker/manager; last negative feedback; learned something not required | BR GFG 2025 | See **dedicated blocks** below | They chain these; keep four stories distinct | | two LP UNNAMED deep follow-ups | R2 Naina UTA | Default pair + one backup | Follow-ups on why/metric | | Tell me about a time when you found an issue in a product and resolved it (even though it wasn’t your task). | R2 IE.in 2024-grad AUTA | Ylogx: bot DB latency + RLS while building chatbot/reports — isolation/latency was not “just SQL gen.” Backup: GiftedBooks doubt-time as product issue | Whose task was it on paper; −35% / 3 tiers | | Tell me about a time when you handled an urgent requirement or made a trade-off decision. | same IE.in | Horizon ERC date: costmap/fusion vs extra hardware; ship 60 FPS + planning. Backup: IQVIA hybrid vs vector-only | What you cut; −55% / 17th | | Tell me about a time when you did something outside of your scope of work or responsibilities. What was it? What was the outcome? | R2 LC 7850431 | Horizon: own GStreamer/mapping as software-team blocker. Backup: IQVIA test-case gen expanding from RAG. Ylogx RLS if chatbot ticket did not include platform isolation | Outcome: 17th/80+ or 3-tier RLS | | deep dive to find a problem; didn’t know what to do next; tough/critical feedback | BR LC 7850431 | **Deep dive:** Ylogx Redis+RLS. **Didn’t know:** IQVIA LangGraph. **Feedback:** Argus 73% mAP as fail | Instant you were stuck; 73→89 | | Tell me about a time you handled tasks with a strict deadline | R1 **and** R2 LC 7724048 | Horizon ERC 2024 (same story, different interviewer OK). Backup: hackathon 1st CodeRecet | Date was immovable; what shipped first | | Tell me about a time you had to take up responsibility outside of your own work. | R2 LC 6570344 | Same as 7850431 out-of-scope: Horizon camera/planning or Ylogx RLS | 17th or 3 tiers | | Was there a time when you had to show bias for action? | same LC 6570344 | Horizon ERC §4.A Bias for Action | 60 FPS / costmap vs waiting | | What’s a task you’re most proud of? | R2 Ruchi FTC | Pick **one:** Horizon 17th/80+ **or** GiftedBooks hours→3–10 min **or** Argus 73→89. Do not list all | Why that metric | | Tell me about a time you had to quickly learn something new. | R2 Rudraksh | IQVIA LangGraph **or** Horizon ROS2 | What you read/tried/discarded | | Describe a mistake you made. What did you learn? | BR Rudraksh | Argus: treating 73% mAP as progress. Learned: mAP gate + 15k images before scale. Backup: Ylogx SQL RAG without cache | 73→89 or −35% | | Tell me about a time you faced a significant technical challenge. | R3/HM GFG Apr 2026 | IQVIA Hybrid RAG on 200+ page BRDs **or** Horizon ZED 2M+ pts/s + costmap | Constraint; metric | | Describe a situation where you had to solve a problem with limited information. | same | IQVIA: rank 200+ sites without a single gold page. Backup: Horizon field sensors vs lab | Ranker + evals; fusion | | Tell me about a time you had a conflict with a teammate/manager. | same | IQVIA hybrid vs vector-only **or** Ylogx RLS-in-DB vs app-only. Technical. No invented personal fight | How you committed after | | When you had tough deadlines, and you had to make compromise what did you do? | R2 GFG sde-1-17 | Horizon: software costmap vs more hardware. Do not invent a quality-cut on 99.9% | −55%; what you refused to cut (safety/isolation) | | When you worked out of your designated work? | same | = out of scope: Horizon / Ylogx RLS / IQVIA test-case gen | Outcome metric | | A time I went above and beyond for customers; A time I helped teammates/juniors | R2 Bhavya | **Customers:** GiftedBooks 3–10 min **or** Ylogx +65% for non-technical users. **Teammates:** IEDC / Horizon / hackathons (Hire and Develop) | Two different projects | | Ownership; Working under pressure; Learning and adapting to new technologies | R2 Aditya | **Ownership:** Ylogx RLS+uptime. **Pressure:** Horizon ERC. **Learn:** IQVIA LangGraph | Three LPs, three projects | | eight LP UNNAMED | Vanshika Interview 2 | Point to **§4.A**; start default pair, then Customer Obsession + Ownership | Do not recite 16 names | | BR LP: challenge I solved; missing a deadline; problem I identified myself; simplifying a process | BR LC 8362604 AUTA 2026 | **Challenge:** Argus mAP or IQVIA hybrid. **Missing a deadline:** see dedicated block (do not invent a miss). **Identified myself:** Ylogx latency/RLS or Argus 73%. **Simplify:** IQVIA test-case gen / StratifyLabs browser inference | Rate-limit/geofencing were **their** story follow-ups, not your Rate Limiter LLD | | Tell me about a time you got feedback; faced critical issues; went beyond your task/job | BR LC 6806195 AUTA | **Feedback:** Argus 73%. **Critical:** Ylogx isolation/uptime or Horizon collision risk. **Beyond:** Horizon GStreamer or IQVIA evals | Same three as 7850431 BR | | Can you describe a complex problem that required in-depth research, POCs, multiple solutions? | HM LC 7563011 AUTA | IQVIA: Firecrawl/Bing/DDG/Playwright vs one scraper; vector vs Hybrid+Semantic+GraphDB; evals as the POC stop. Backup: Ylogx FastAPI+NestJS+Postgres+Redis+RLS vs “just LangChain” | What you discarded | | LP first ~15 min UNNAMED | R1 Akash AUTA | Default pair | Short STAR | | 15–20 min generic LP then SD | R2 Arijit AUTA | Default pair; be ready to stop LP | Do not eat the hour | | intense ~30 min behavioral UNNAMED | R2 Karun University TA | §4.A depth; they may only code after | Metrics ready | | all 16 LP STAR ~15–20 min each UNNAMED exact | BR Nisarg AUTA | Full **§4.A** — one primary each, no project reused >3 | They will probe 2–3 | **Also named in bible §6 / Fleet extras (map here so they are not dropped):** | Prompt | Source | Story | | --- | --- | --- | | LP dive deep; completed a project on your own; communicate if you will miss deadline | LC 7563011 R2 | Dive Deep Ylogx; **own project:** Argus or GiftedBooks or StratifyLabs (internships were team). **Miss deadline:** dedicated block | | learning not part of job | LC 6653463 R2 | IQVIA LangGraph **or** Horizon ROS2 (same as Learn) | | LP deep dive; negative feedback | LC 6653463 R3 | Ylogx dive + Argus 73% | | learned something new; comfort zone | LC 7406809 later LP / LC 6653845 | IQVIA or Horizon ROS2 | | problem I didn’t know how to approach; stepped out of comfort zone | LC 7280347 R1 | IQVIA LangGraph or Horizon ROS2 | | deep dive; missed a commitment; convince someone of your approach | LC 7724048 BR | Dive Ylogx; miss-deadline block; convince = Backbone hybrid or RLS-in-DB | | Why did you choose that approach? / what would you do differently? / how did you arrive at that decision? | Rushikesh BR | Any §4.A primary; answer with discarded option + metric | | LP multi-level why / impact / differently / disagreements / measure success | igreaper BR | Same as Rushikesh + Backbone + Are Right (how you measured) | | struggled to meet a deadline; why the deadline mattered | Dhananjai R2 | Horizon ERC — date is the competition; 17th/80+ | | initiative; convince someone | Sreeja intern §7 | Initiative: Ylogx RLS or IQVIA evals. Convince: Backbone card. Intern format — still use on-resume FTE stories | | tight deadline; teammate disagreement | DEV intern VO | Horizon + Backbone | | helped a peer; missed a deadline | LC 6475219 R2 | IEDC/Horizon help; miss-deadline block | | most difficult project; negative feedback; deadlines | Raghav R1 | Argus or IQVIA; 73% mAP; Horizon date | | LP tough situation; unfamiliar technology | Uday R1 | Horizon ERC; IQVIA LangGraph | | LP comfort zone; negative feedback | LC 6573582 BR | ROS2/LangGraph; Argus 73% | | Innovate / Frugality (with architecture) | LC 7981646 extra | Invent IQVIA + Frugality Ylogx Redis/ECS | | Customers; above and beyond; helped juniors | Bhavya (AllQuestion LP bank) | GiftedBooks / Ylogx chatbot; IEDC | | Improve a solution via deeper analysis | Bhavya BR | Dive Deep Ylogx or Argus eval | | Situation you were completely stuck | GFG intern HackOn | IQVIA “didn’t know next” | | Learned something very quickly and implemented it | GFG intern Sep 2024 | Hackathon **or** LangGraph | | deep dive; convince someone | LC 8014509 BR | Ylogx + Backbone | | LP academic/internship UNNAMED | Arijit R1 | Current role IQVIA; one intern metric | | collaboration / ownership UNNAMED | Uday BR | Horizon team + Ylogx Ownership | | project critical work | LC 6475219 R3 | Argus or Horizon | | LP mix + bucket-sort DSA | Taanya | Any two from default pair | | BR 3–4 LP deep dives UNNAMED | LC 8029194 | §4.A | | LP 5 UNNAMED | LC 8014509 R2 | §4.A | | 2 LP UNNAMED (several AUTA/OA-as-R1 rows) | Naina, GFG 2025 R2, 6800853, Rajprem, etc. | Default pair | | internships + LP UNNAMED | Prince (bank) | IQVIA + Ylogx + Horizon one-liners then one STAR | | BR LP-only / formality UNNAMED | Reddit AUTA Chennai; LC 7406809 | Default pair, still use numbers | **Unnamed LP rounds — default pair (use this, do not guess titles):** 1. **Dive Deep** — Ylogx bot DB latency + RLS (on-resume). 2. **Deliver Results** — Horizon 17th/80+ **or** IQVIA LangSmith/test-case gen if they already heard rover. If they want a third: **Customer Obsession** GiftedBooks 3–10 min. --- #### Dedicated short blocks (conflict / deadline / out-of-scope / feedback / didn’t-know / trade-off / invent / dive-bug) **Current role (GFG 2025 BR)** Software Developer Intern, IQVIA, Kochi, Apr 2026–present. LangGraph Deep Research (200+ sites, Firecrawl/Bing/DDG/Playwright) and Hybrid RAG (Azure AI Search Hybrid+Semantic, GraphDB, LangGraph) on 200+ page BRD/PDFs, LangSmith tracing/evals/test-case gen. Before that: Ylogx intern Nov 2024–Oct 2025 (FastAPI/NestJS/Postgres BI). Java is on the resume for Live Code; this job’s production path is Python. **Last time you deep-dived a bug** Ylogx: chatbot “worked,” bot DB latency and tier isolation did not. Actions: measure latency, RLS+RBAC 3 tiers, Redis −35%. Not SEO 403/noindex. **Conflict coworker/manager** IQVIA: hybrid+semantic+graph vs vector-only for 200+ page BRDs. Or Ylogx: RLS in Postgres vs app-only. Disagree with data; commit to evals or to RLS as platform rule. Resume has no named interpersonal incident — do not invent one. **Last negative feedback** On-resume honest version: Argus eval at 73% mAP — the metric was the feedback; not production-quality for PPE. You did not ship that as the standard; 15k images → 89% mAP, 24 FPS. If they insist on *person* feedback and you have no confirmed review story, say so and use this. Do not invent a manager quote. **Learned something not required / not part of job** IQVIA LangGraph/LangSmith (new vs Ylogx stack) or Horizon ROS2/GStreamer/ZED (not the web intern stack). **Issue in a product, not your task** Ylogx: isolation/latency while delivering chatbot+reports. Outcome: 3-tier RLS, −35% bot DB latency, 99.9% held. Backup: GiftedBooks doubt hours as the product issue you built RAG+PYQ to close. **Urgent requirement / trade-off** Horizon ERC date vs extra sensors. Chose costmap + fusion on ZED 2; −55% collision risk, 17th/80+. IQVIA backup: hybrid vs ship-vector-only. **Out of scope / outside designated work / above and beyond** Horizon GStreamer/mapping ownership; IQVIA test-case gen from BRDs; Ylogx RLS as platform. GiftedBooks for *customer* above-and-beyond (3–10 min). **Didn’t know what to do next / comfort zone / stuck** IQVIA: first multi-agent + hybrid retrieval on 200+ page docs — broke into research agents, rank, hybrid retrieve, then LangSmith stop condition. Horizon ROS2 backup. **Tough / critical / negative feedback** Argus 73% mAP gate. Optional: first SQL RAG without Redis (latency). No fake PIP story. **Strict deadline / tough deadline + compromise / struggled to meet deadline / why it mattered** Horizon ERC 2024. Deadline = event. Compromise = software planning vs more hardware, not “skip safety.” Hackathon backup (1st CodeRecet) if they want a shorter clock. **Missing a deadline / missed a commitment / communicate if you will miss** Resume does **not** state a missed ERC or a missed Ylogx SLA. Do not invent a miss. Honest talk: ERC date was fixed; you sequenced 60 FPS + costmap so the run happened (17th/80+). **Communicate:** flag early if a ship-blocker (feed, costmap, RLS) is late; cut extra hardware/features, not isolation or a 73% safety model. If you later confirm a real miss (off-resume), move it to §4.C before using it. **Completed a project on your own** Argus, GiftedBooks, or StratifyLabs. IQVIA/Ylogx/Horizon were intern/team. Walk problem → architecture → one hard part → resume metric. **Convince someone of your approach / initiative** Backbone: hybrid search or RLS-in-DB. Initiative: you identified 73% as fail, or bot latency, without being asked for a paper. **Helped teammates / juniors / peer** IEDC Tech Team, Horizon software sharing, hackathon pair work. No manager title. **Working under pressure** Horizon ERC. Backup: 8 hackathons. **What’s a task you’re most proud of / most difficult project / challenge I solved / significant technical challenge / complex problem POCs** Pick one and go deep: Argus 73→89, IQVIA hybrid RAG, Horizon 17th, Ylogx RLS+210ms. Proud ≠ longest list. **Problem I identified myself / simplifying a process** Identified: 73% mAP or uncached bot SQL or vector-only BRDs. Simplify: LangSmith test-case gen from BRDs; StratifyLabs browser inference −30%; GiftedBooks PYQ instead of full-PDF grind; Redis vs bigger DB. **Faced critical issues** Ylogx 99.9% + RLS (wrong data is a critical issue). Argus alerting at 24 FPS. Horizon collision risk. --- ### 4.C Off-resume (confirm) Do **not** lead with these unless you confirm they are true and you want them on the record. Prep mapped them; they are **not** Aug 2026 resume bullets. | Story (from `amazon-sde1-interview-prep.md` / GitHub naming) | Why it is off-resume | If confirmed, which LP | | --- | --- | --- | | Django CUSAT student portal security audit (unauthenticated media) | Prep only | Ownership / Dive Deep / out of scope | | Ylogx SEO 403 / noindex www vs non-www | Prep only | Dive Deep — **do not** use as primary; on-resume Dive Deep is Redis+RLS | | Purplle-style CCTV YOLOv8 + ByteTrack + OSNet Re-ID | Prep only; Argus on resume is YOLOv9 15k / 73→89 | Learn / Are Right — use **Argus** unless you confirm Purplle | | LLM uncensored / abliteration / LoRA / DPO / mergekit | Prep only | Learn — weak for Amazon; skip unless asked about safety | | Hospital JWT + rotating refresh (quote → auth architecture) | Prep only | Ownership / Earn Trust | | SuperTokens + MSG91/2Factor + DLT/TRAI OTP | Prep only | Customer Obsession / Earn Trust | | Dubai Mall navigator (SVG + Dijkstra) | Prep only | Customer Obsession | | ConvBI / Warpflow as named products | Not resume bullets. Conv-BI GitHub exists — label **GitHub / Ylogx-adjacent**, not a separate job | Customer Obsession / Invent — prefer **Ylogx SQL RAG +65%** | | Qdrant on the BRD system | Prep; resume is Azure AI Search + GraphDB | Do not say Qdrant | | InstaRecon internals | Ethics one-liner only | Not an LP story | | GiftedBooks GitHub AegisAI README | Mismatch | Never mix into GiftedBooks STAR | | StratifyLabs default Next.js README extras | Not resume | Do not invent | **Java vs production (say once):** Live Code in Java. Ylogx/IQVIA/Horizon/projects shipped Python/TS/ROS2 as on the resume. ## 5. Project & tech-stack question matrix (resume + GitHub) GitHub: [adarshx01](https://github.com/adarshx01). Resume-matching repos only. Skip unrelated forks (care-fe, tensorflow, selenium, etc.). **InstaRecon / PhiSiFi (if they scroll GitHub):** security-awareness demo, consent, no production attacks. Then move to StratifyLabs / Argus / Ylogx / IQVIA. No phishing, credential, or exploit talk. **Off-resume GitHub (do not mix into resume bullets):** Conv-BI README 404; description “AI custom d&d report builder similar to POWER BI” — **Ylogx-adjacent**, not a separate resume project. GiftedBooks README currently describes **AegisAI** — **mismatch**; GiftedBooks answers = resume only. `argus-stream-api-server` README 404. StratifyLabs default Next.js README — do not invent; resume features win. `Gstreamer-UDP` (Python GStreamer UDP webcam) supports the Horizon 60 FPS story. Horizon-Website-old, Team-CUSAT, visionlabServer, AegisAI, warpflow: only if honest and they do not contradict the resume. --- ### 5.1 IQVIA intern — Apr 2026–present (Kochi) **Stack (resume):** LangGraph, LangChain, FastAPI, Firecrawl, Bing / DuckDuckGo / Google Playwright scraping, Azure AI Search (hybrid + semantic), GraphDB, LangSmith. Python in production. **Java-vs-Python:** DSA in Java here. This intern work is Python agents + FastAPI. If they ask “could this be Java?” — same graph of nodes and the same retrieval interfaces; I would wrap Azure SDKs in Java services. I did not ship this as a JVM service. #### Walk me through this project (60s) At IQVIA I own two research systems. First, a LangGraph Deep Research platform: a stateful agent graph that fans out Firecrawl plus Bing, DuckDuckGo, and Google Playwright scraping, ranks sources across **200+ websites**, and writes a result. Second, a Hybrid RAG agent: Azure AI Search (keyword + vector + semantic) plus a GraphDB, with LangGraph choosing retrieval mode for **200+ page BRD/PDF** documents, plus LangSmith tracing for evals and generated test cases. The point is not “we called an LLM” — it is ranked, grounded retrieval with traces. #### Walk me through this project (3 min) - **Problem:** analysts cannot read 200-page BRDs or the open web by hand for every research request. Naive “stuff the PDF in context” blows token limits and hallucinates citations. - **Deep Research graph:** planner node → parallel scrape/search tools → ranker (source quality, recency, agreement) → synthesizer. State lives on the LangGraph checkpoint so a failed scrape does not restart the whole run. - **Hybrid RAG:** chunk BRDs; index in Azure AI Search; keep entities/relationships in GraphDB (requirements → sections → dependencies). The agent adapts: lexical for IDs/clause numbers, semantic for “what is the retention policy,” graph hops for “which requirements depend on this.” - **Evals:** LangSmith traces every node (query, retrieved chunks, final answer). Test-case generation is itself a traced job so we can see which retrieval path produced a bad case. - **Result (resume):** 200+ sites ranked for research; 200+ page documents processed with stateful orchestration — no extra % invented. #### Why this architecture vs the obvious alternative | Alternative | Why not | | --- | --- | | One-shot ChatGPT over the whole BRD | 200+ pages do not fit; no citations; no eval | | Vector-only FAISS | Misses exact clause IDs / table names; Azure hybrid (keyword + semantic) is the retrieval default | | No GraphDB, only chunks | Cross-section dependencies in BRDs are graph, not cosine | | Linear LangChain chain | Deep Research needs retries, parallel tools, and state — that is a graph | #### Hardest bug / production incident Honest: ranking, not a named outage. Two high-ranked pages contradict each other; first-hit retrieval looks “confident.” Fix was rank by agreement + source type, and refuse to answer without a retrieved span. LangSmith made the bad path visible (wrong tool order, empty scrape still feeding the writer). #### Scale / latency / cost trade-off Crawl + LLM is expensive. Cache scrape results; do not re-embed a BRD on every question; use hybrid search so you retrieve 5–20 chunks, not 200 pages. Graph hops are cheaper than another LLM call when the question is relational. If cost spikes: fewer Playwright renders, more Bing snippets, tighter recency filters. #### Security Skip JWT theatre if they want Ylogx for that. Here: BRDs are confidential — Azure credentials in env/secret store, not in traces; do not log full document text in LangSmith in production; tenant isolation if multiple clients share the app (I will not invent a tenant model that is not on the resume). #### How you tested / evals (LangSmith) Gold questions with expected citations. Trace: query → retrieval set → answer. Fail if answer has no overlapping span with retrieved chunks. Generated test cases from BRD sections, then humans spot-check a sample. That is Insist on Highest Standards / Are Right, A Lot — not “the model sounded good.” #### If you rebuilt it tomorrow Citation-required writer (no span → no sentence). Cheaper crawl cache. Stricter graph schema (requirement IDs as nodes). Eval set before adding a new tool node. #### Design a similar system on a whiteboard (mini-LLD) ``` Client → FastAPI → LangGraph (state: query, docs[], ranks[], answer) ├ tool: Search/Scrape ├ tool: Azure AI Search (hybrid) ├ tool: GraphDB hop └ node: Rank + Write → LangSmith (traces, evals) Index pipeline: PDF → chunk → embed + lexical index + graph extract ``` Clarify: multi-tenant? citation SLA? max latency? #### Conflict / deadline / ownership tied to IQVIA Ownership: intern, but I architected the graphs (resume: “Architected”). Deadline: 200-page BRDs do not wait for a perfect agent — ship hybrid retrieval + traces first, extra tools second. Conflict: skip unless you have a real named disagreement; do not invent a manager fight. --- ### 5.2 Ylogx intern — Nov 2024–Oct 2025 (Remote) **Stack (resume):** Python FastAPI, NestJS, REST, PostgreSQL, LangChain SQL RAG, RLS + RBAC (3 org tiers), Redis, React + Recharts, AWS CloudFront + ECS + Docker, CI/CD, GoDaddy DNS + Route 53 + ALB. **40%** faster reports, **99.9%** uptime, SQL RAG **+65%** analysis productivity, Redis **−35%** bot DB latency, **30** dashboards **+60%** operational efficiency, **sub-210 ms**. **GitHub:** Conv-BI is Ylogx-adjacent (Power-BI-like report builder). Not a separate resume bullet. Label it GitHub if they find it. **Java-vs-Python:** Live Code Java. This product was Python FastAPI (AI/SQL RAG) + TypeScript NestJS (API) + React. Postgres/RLS/Redis ideas are language-agnostic. #### Walk me through this project (60s) Full-stack AI BI: custom report builder on FastAPI + NestJS + Postgres. Chatbot is LangChain **SQL RAG** (NL → constrained SQL), not a free-form LLM over the warehouse. I put **RLS + RBAC for 3 org tiers** in the database so a prompt cannot read another tenant. Redis cut bot DB latency **35%**. **30** real-time KPI dashboards on React/Recharts. AWS: CloudFront, ECS, Docker, CI/CD, **sub-210 ms**. DNS: GoDaddy → Route 53 → ALB. Reports **40%** faster, **99.9%** uptime, analysis productivity **+65%**, ops efficiency **+60%**. #### Walk me through this project (3 min) - **Report builder:** NestJS owns authz + CRUD; FastAPI owns generation/RAG; Postgres is source of truth. - **SQL RAG:** retrieve schema/examples, generate SQL, run **as the user’s DB role** (RLS applies). +65% is “analysts stopped waiting on engineers for every slice.” - **Dashboards:** 30 KPIs, live-ish via API (WebSockets are on the skills list; I will not claim socket fan-out unless asked and I can be specific). - **Deploy:** Docker on ECS, CloudFront for static/API edge, ALB, Route 53 after GoDaddy nameservers. Sub-210 ms is the number I will defend as resume-stated p-ish latency, not a load-test dump I do not have in the repo. #### Why this architecture vs the obvious alternative | Alternative | Why not | | --- | --- | | LLM writes SQL with a service-role DB user | Prompt injection = full dump. RLS is the control. | | Mongo for BI facts | KPI reports need joins, aggregations, transactions — Postgres. | | App-level `WHERE org_id = ?` only | One missed filter = leak. RLS is defense in depth. | | GraphQL everywhere | Resume is REST + ProtoBuf/GraphQL as skills. This app was REST. GraphQL if dashboard over-fetch became the pain; it was not the first cut. | | Bigger RDS instead of Redis | Hot schema/metadata and repeat NL questions — cache. −35% latency. | #### Hardest bug / production incident From prep (on-resume-adjacent ops): **SEO / indexing 403s and noindex** across www vs non-www. Systematic isolation: CloudFront vs origin, DNS (GoDaddy vs Route 53), ALB host headers, robots/noindex. Not glamorous; it is how 99.9% uptime and “the site exists on Google” actually fail. Second class of bug: SQL RAG generating a query that is syntactically fine but wrong grain — caught by running as RLS role + returning the SQL to the user, not hiding it. #### Scale / latency / cost Redis in front of repeat bot queries vs scaling Postgres. CloudFront vs hitting ECS for static assets. Sub-210 ms: cache + connection pooling, not “LLM in the dashboard hot path.” Frugality: cache and CDN before a larger instance class. #### Security (strongest story) - **RBAC:** 3 organizational tiers (role). NestJS enforces at API; Postgres **RLS** enforces at row read. - **JWT / OAuth:** skills list includes JWT, OAuth 2.0, Auth0. Talk tokens at the API gateway; **do not** let the LLM hold a superuser connection string. - **Secrets:** env/ECS task role, not in Git. - **SQL RAG:** parameterized execution, read-only role, timeout, row cap. If the model asks for `pg_catalog` — deny. #### How you tested API tests on NestJS; SQL fixtures proving RLS denies cross-tier rows; dashboard load on the 30 KPIs. RAG: golden NL questions → expected SQL shape, not expected English. I did not put LangSmith on the resume for Ylogx — do not steal IQVIA evals. #### If you rebuilt it tomorrow Query allow-list / semantic layer (metrics table) so the LLM cannot invent joins. Stronger eval set. Same RLS. Maybe read replicas for dashboards, not for the bot’s transactional reads. #### Design a similar system on a whiteboard ``` Browser (React dashboards + chatbot) → CloudFront → ALB → ECS ├ NestJS (auth, RBAC, report CRUD) └ FastAPI (SQL RAG) → Redis (schema + hot answers) → Postgres (RLS policies per tier) Route 53 (after GoDaddy) → ALB ``` #### Conflict / deadline / ownership Ownership: intern who shipped RLS rather than “we’ll filter in the UI.” Deadline: 30 dashboards vs perfect RAG — dashboards first for ops (+60%), bot behind RLS. Backbone: **DB-enforced RLS vs app-only auth** — I would not ship the bot without RLS; that is the disagreement worth having. --- ### 5.3 Team Horizon — Feb–Jun 2024 (CUSAT, ERC) **Stack (resume):** ROS2, GStreamer **60 FPS**, ZED 2 **2M+ pts/s**, RViz, Gazebo, costmap path planning, sensor fusion. **17th / 80+** European Rover Challenge 2024. **+40%** obstacle detection accuracy. Costmap **−55%** collision risk. **GitHub:** `Gstreamer-UDP` (Python GStreamer UDP webcam) supports the 60 FPS camera-feed story. Horizon-Website-old / Team-CUSAT: mention only if they ask and it does not contradict “core software team.” **Java-vs-Python:** DSA Java. Rover software was ROS2 (Python/C++ nodes), GStreamer pipeline, not a JVM service. #### Walk me through this project (60s) Core software on a semi-autonomous Mars rover for ERC 2024. ROS2 graph: camera at **60 FPS** via GStreamer, ZED 2 mapping **2M+ points/s** into RViz/Gazebo, costmap planner with sensor fusion. Obstacle detection **+40%**; collision risk **−55%**. **17th globally of 80+** teams. #### Walk me through this project (3 min) Competition rover: perception → costmap → path. GStreamer for the live feed (UDP-style pipeline; repo `Gstreamer-UDP` is the webcam analogue). ZED 2 depth → occupancy. Costmap + predictive fusion, not “stop if pixel is red.” Gazebo for sim; field is dirt and latency. #### Why this architecture vs the obvious alternative | Alternative | Why not | | --- | --- | | Train a giant vision model and hope | ERC is localization + planning + comms. ROS2 is the integration bus. | | OpenCV blob detector only | +40% obstacle number came from a real pipeline, not a tutorial threshold. | | No costmap, reactive bump-and-turn | −55% collision is planning + fusion. | | TCP webcam MJPEG | 60 FPS needed a GStreamer pipeline, not a naive Flask stream. | #### Hardest bug / production incident Field, not prod SaaS: drop frames vs 60 FPS; costmap lag so the rover plans on stale occupancy. Debug: pipeline latency (GStreamer) vs ROS2 callback vs ZED point-cloud rate. Sim (Gazebo) did not match lighting/dust — that is why we still needed field time. #### Scale / latency / cost 2M+ pts/s cannot all go to a remote laptop. Downsample for viz; keep dense cloud for local costmap. Frugality: student hardware, not a cloud GPU bill. #### Security Skip. No JWT on a rover. If they stretch: do not expose an unauthenticated field telemetry endpoint. #### How you tested Gazebo + RViz playback; field runs; FPS and collision metrics on the resume. Not LangSmith. #### If you rebuilt it tomorrow Better sim-to-real for dust; stricter time-sync between ZED and costmap; same ROS2 split (perception vs planning vs comms). #### Design a similar system on a whiteboard ``` ZED 2 → point cloud → costmap Camera → GStreamer 60 FPS → operator / autonomy Sensors → fusion → planner → actuators All as ROS2 nodes; Gazebo for sim ``` #### Conflict / deadline / ownership Ownership: core software, not “I trained a model.” Deadline: ERC date is fixed — ship a stable 60 FPS + costmap, not a new architecture week-of. Conflict: perception vs planning ownership on a student team — I owned the software integration (camera + mapping + costmap), not fake people-management. --- ### 5.4 StratifyLabs — Computer Vision SaaS ([stratifylabs.design](https://stratifylabs.design)) **Resume only.** GitHub README is default Next.js — do not invent features from it. **Stack (resume):** 3D sim lab, browser-based inference (**−30%** ML iteration), marketplace **50+** models/datasets, URDF editor, WebGL, 3D character voice RAG bots (Gemini). **Java-vs-Python:** DSA Java. This is TS/Next + browser WebGL + Python/CV inference. I will not claim a Spring rewrite. #### Walk me through this project (60s) CV training SaaS: 3D simulation lab in the browser so you prototype without a full GPU loop. Browser inference cut ML iteration **30%**. Marketplace of **50+** pretrained models and datasets, community profiles, URDF editor with WebGL. Gemini RAG voice bots as 3D characters against the simulated scene. #### Why this architecture vs the obvious alternative Train-on-a-Colab-notebook vs a shared lab: iteration is the product. WebGL/URDF in-browser vs native Gazebo-only: faster for CV people who are not ROS. Gemini RAG bots vs a static tooltip: talk to the scene. #### Hardest bug Browser inference vs native: WebGL/WASM memory, model size, and “it works on my GPU box.” Honest class of bug — I will not invent a Jira ticket. #### Scale / latency / cost −30% iteration is **time**, not a cluster. Cost: run small models in-browser; keep big train jobs off the request path. 50+ models is a catalog, not 50 GPUs per user. #### Security Auth for marketplace/profiles (JWT/OAuth as skills). Do not let a RAG bot exfiltrate another user’s datasets. Skip if they want Ylogx RLS depth. #### How you tested Browser inference on sample models; 3D editor load. No LangSmith on resume for this project. #### If you rebuilt it tomorrow Same: browser loop for iteration. Add a real eval harness for the Gemini bots (ground answers in the current sim state). #### Design a similar system on a whiteboard ``` Next.js + WebGL (URDF, 3D lab) → inference API (models) + object store (datasets) → Gemini RAG bot (scene-conditioned) Marketplace: models, datasets, profiles ``` #### Conflict / deadline / ownership Ownership: product I built (resume Technical Projects). Deadline: ship browser inference before a huge model zoo — 50+ catalog after the −30% loop existed. --- ### 5.5 GiftedBooks — VR learning suite ([giftedbooks.study](https://giftedbooks.study)) **Resume only.** GitHub `giftedbooks` / `giftedbooks-ai` README currently describes **AegisAI** — **do not mix**. AegisAI is a different GitHub artifact. **Resume:** VR 3D labs, AI avatars, RAG PDF Q&A **sub-300 ms** API, **99.5%** uptime, PYQ topic suggestions, reading **+35%**, engagement **+50%**, **2.5×** comprehension, doubts **hours → 3–10 min**. **Java-vs-Python:** DSA Java. This is a TS/Python RAG + VR client. Sub-300 ms is the API number on the resume. #### Walk me through this project (60s) VR learning app: 3D labs + AI avatars. Students upload PDFs; RAG answers in **sub-300 ms** with **99.5%** uptime. PYQ analysis suggests topics. Reading efficiency **+35%**, engagement **+50%**, comprehension **2.5×**, doubts down to **3–10 minutes**. #### Why this architecture vs the obvious alternative Dump PDF into a long context vs RAG: token limits and latency. Sub-300 ms means retrieve + small generate, not a 200k-token read. VR without RAG is a pretty empty lab. #### Hardest bug RAG latency vs quality: chunk size vs sub-300 ms. Uptime 99.5% is ops (hosting), not a model trick. I will not invent a specific outage. #### Scale / latency / cost Embed once per PDF; cache retrieval; do not re-embed on every question. Cost: smaller chunks + top-k, not full-book generation. #### Security Per-user PDFs — do not retrieve another student’s notes. JWT/session on the API. Secrets off the client. #### How you tested Latency budget (sub-300 ms) as a product constraint; uptime as hosting. No LangSmith on this resume bullet. #### If you rebuilt it tomorrow Same RAG path. Stronger citation UI (highlight PDF span). Keep PYQ suggestions as deterministic analytics, not an LLM guess. #### Design a similar system on a whiteboard ``` VR client → API (auth) → PDF ingest → chunk/embed → vector + metadata → RAG Q&A (sub-300 ms) → PYQ topic ranker (separate from LLM) ``` #### Conflict / deadline / ownership Customer Obsession: students, not internal dashboards. Deadline: VR labs vs RAG — ship Q&A latency first so doubts hit 3–10 min. --- ### 5.6 Argus — Industrial safety AI ([Devfolio](https://devfolio.co)) **Resume:** YOLOv9 **73% → 89% mAP**, **15,000+** images, PPE + attendance, **24 FPS**, violations **−50%**, **20+** cameras, Postgres logging, containerized, compliance **2×**. GitHub `argus-stream-api-server` README **404** — do not invent API routes. **Java-vs-Python:** DSA Java. This is Python CV (YOLOv9/OpenCV) + Postgres. Not a Java detector. #### Walk me through this project (60s) Real-time PPE/attendance CV. YOLOv9 trained on **15k+** images, **73 → 89 mAP**, **24 FPS**. Alerts cut violations **50%**. **20+** camera feeds, containerized, Postgres logs, compliance **2×**. #### Why this architecture vs the obvious alternative Naive OpenCV color/HOG: you will not go 73 → 89 mAP on PPE. YOLO vs two-stage detector: 24 FPS on 20 cameras is the constraint. Postgres vs files: audit trail for safety. #### Hardest bug mAP vs production FPS: a heavier model looks better on a laptop and dies at 20 streams. Tuning until **24 FPS** held. Camera lighting / PPE color — dataset, not a one-line threshold. #### Scale / latency / cost 20 cameras: batch or dedicated workers per stream; do not run 20 copies of the fattest model if 24 FPS breaks. Postgres for events, not video blobs. #### Security Camera feeds are sensitive. Auth on the dashboard; no public stream URLs. Skip RLS depth unless they ask — Ylogx is the RBAC story. #### How you tested mAP on a held-out set (73 → 89); FPS under multi-cam; alert precision enough to claim −50% violations (site metric on resume). #### If you rebuilt it tomorrow Same YOLO + Postgres. Add a replay buffer for disputed alerts. Do not replace YOLO with an LLM “looking at frames.” #### Design a similar system on a whiteboard ``` Cameras → ingest workers → YOLOv9 → alert service ↓ Postgres (events, attendance) Dashboard ← API ← DB ``` #### Conflict / deadline / ownership Highest Standards: 73 mAP was not shippable for safety. Deadline: 24 FPS on 20 cams vs waiting for 95 mAP. --- ### 5.7 Education / hackathons / IEDC **Resume:** CUSAT CSE **8.42/10**, Oct 2022–May 2026. Hackathons: **1st** CodeRecet, **Best Project** MLH.io, **runner-up** Magnathon 2.0 (IEEE), **8** national/regional. ERC 17th (also Horizon). Leadership: Team Horizon software + **IEDC CUSAT** tech team. **Java-vs-Python:** coursework/DSA Java + Python. Hackathon stacks mixed; I will name the resume stack if they pick a project. #### Walk me through (60s) CSE at CUSAT, **8.42**. Software on Horizon (ERC) and IEDC tech team. Eight hackathons — CodeRecet 1st, MLH Best Project, Magnathon runner-up — short-cycle production deploys, not tutorial apps. #### Why hackathons vs a course project Fixed deadline, real demo, deployment. Bias for Action. Not a substitute for Ylogx/IQVIA depth. #### Hardest bug / scale / security / evals Skip unless they pick a named hackathon you can describe without contradicting the resume. Do not invent Magnathon architecture. #### If you rebuilt / whiteboard Skip generic “hackathon platform LLD.” Point to Stratify / GiftedBooks / Argus. #### Conflict / deadline / ownership / Hire-and-Develop **Hire and Develop / Earth’s Best Employer (honest):** IEDC CUSAT tech team + Horizon — I mentored teammates on ROS2/GStreamer and hackathon delivery. I was **not** a people manager, no reports, no hiring bar. Do not fake Amazon-style skip-levels. --- ### 5.8 Tech-stack deep-dives (interview-length, not tutorials) **Java vs resume stack.** Live Code: Java. Production: Python FastAPI (IQVIA, Ylogx RAG, Argus), TypeScript NestJS/React (Ylogx, Stratify, GiftedBooks), ROS2 Python/C++ (Horizon). Bridging line: “I think in HashMap / heap / graph the same way; I write Java in this editor.” **REST vs GraphQL vs ProtoBuf.** Ylogx BI was **REST** (resume). GraphQL helps dashboard over-fetch; we did not need it for 30 Recharts KPIs. ProtoBuf: skills list — good for internal camera/telemetry or gRPC later; browser dashboards stayed JSON REST. If they want one paragraph: REST for public HTTP, GraphQL if the VR/SaaS client needs a graph of nested resources, ProtoBuf when the payload is high-frequency (Argus frames metadata, not the JPEG itself). **WebSockets.** Skills list. Honest use: live KPI tiles or camera alerts. Ylogx resume says “real-time KPI dashboards” — I will describe polling vs WS if asked, and not invent a socket bus that is not in a README. **Postgres vs Mongo vs Redis vs FAISS vs Neo4j.** | Store | When I used it | | --- | --- | | Postgres | Ylogx facts + RLS; Argus event log | | Mongo | skills; not the Ylogx warehouse | | Redis | Ylogx −35% bot latency (hot schema/answers) | | FAISS / vector | RAG (GiftedBooks, IQVIA also Azure Search) | | Neo4j / GraphDB | IQVIA BRD relationships | **RLS vs app-level auth.** Ylogx: **both**. JWT/RBAC at NestJS; **RLS in Postgres** so SQL RAG cannot bypass. App-only `WHERE tenant_id` is one missed query from a leak. **Docker / ECS / k8s.** Resume skills: Docker, Kubernetes, GitHub Actions, CI/CD. **Internships: ECS + Docker** (Ylogx), containers on Argus. Honest: I have k8s on the skills list; the production path I can defend is **ECS + Docker + CloudFront**, not a cluster I ran as platform owner. **CI/CD GitHub Actions.** Ylogx automated pipelines to ECS. Build image → push → deploy. Not a 20-stage textbook. **RAG: chunking, hybrid, graph, evals, when NOT to use an LLM.** - Chunk by structure (BRD sections, PDF pages), not only token windows. - Hybrid (Azure keyword + semantic) for IDs + meaning. - Graph when the question is relational (“depends on”). - Evals: LangSmith (IQVIA). GiftedBooks: latency SLA. - **Do not use an LLM:** Ylogx RLS policy, rover costmap, Argus bounding boxes, authZ, money totals without a SQL result. NL is the interface; **SQL/CV/planner is the source of truth**. **YOLO vs naive OpenCV.** Argus: OpenCV alone does not take PPE from 73 → 89 mAP at 24 FPS. OpenCV still for decode/resize. **ROS2 vs “I trained a model.”** Horizon is a **system**: drivers, time sync, costmap, GStreamer. A weights file is one node. --- ## 6. GenAI / Fluency answers (bible §5.E) **Primary story: IQVIA LangGraph + Hybrid RAG + LangSmith.** Secondary: Ylogx SQL RAG (constrained). Do not use GiftedBooks README/AegisAI. **UTA two-tech Rank A generally did not name GenAI-primary** — if 18 Aug is two DSA, this section is backup. **Where not to use LLMs / hallucination:** no LLM for authZ, RLS, rover actuation, PPE boxes, or unpaid invoices. Ground with retrieval; **LangSmith** traces; fail closed if no supporting chunk. Verify AI code: run it, check complexity, check bounds — same as Vaishali / LC 8014509. --- ### How do you use Gen AI tools; complex tasks; where should / should not use — [LC 7850431](https://leetcode.com/discuss/post/7850431/amazon-sde-1-interview-experience-by-imx-xitu/) (our R3) **Same slot also had:** dynamic **k-th largest** (k changes) — DSA, not GenAI. Point to that card if they context-switch. **Use:** IQVIA Deep Research (200+ sites, rank, synthesize) and Hybrid RAG on 200+ page BRDs. Ylogx SQL RAG for NL → SQL **behind RLS**. GiftedBooks PDF Q&A when the answer must come from the file. **Complex:** multi-tool LangGraph (scrape + search + rank), adaptive retrieval (lexical vs semantic vs graph). **Should not:** Ylogx row security, Argus detections, Horizon costmap, anything that must be auditable and exact. Should: high-volume, pattern-based, **cheaply verifiable** (SQL result, cited chunk). --- ### How make best use of LLMs; verify/validate; efficiency — [LC 7724048](https://leetcode.com/discuss/post/7724048/amazon-sde-1-interview-experience-by-ano-t6fz/) (R3/HM) **Same slot also had:** **Next Greater Element** — DSA. Point to NGE card. **Best use:** narrow output (SQL, cited answer, test case), not open-ended strategy. **Verify:** LangSmith traces; execute SQL as RLS role; require retrieved spans; gold questions. **Efficiency:** hybrid search so the model sees 5–20 chunks; Redis on Ylogx (−35%); do not put the LLM on the sub-210 ms dashboard path. --- ### similar to nodes at distance K; O(n); no parent mapping — labeled Gen AI Fluency — [LC 7623949](https://leetcode.com/discuss/post/7623949/amazon-sde-1-application-interview-exper-92xt/) **This was DSA, not GenAI.** Same constraint as AUTA [LC 7406809](https://leetcode.com/discuss/post/7406809/amazon-sde-1-auta-interview-experience-s-k6t7/) R2. **Point to the Dist-K card.** Do not invent a GenAI answer as if that was the question. If they still ask Fluency after the code: one IQVIA sentence, then stop. --- ### 30 min architecture + Innovate / Frugality — [LC 7981646](https://leetcode.com/discuss/post/7981646/) Whiteboard **IQVIA Hybrid RAG** or **Ylogx SQL RAG** (not Amazon retail HLD). **Invent:** adaptive retrieval + GraphDB instead of “embed the BRD and hope.” **Frugality:** Azure AI Search vs training a private embedder; Redis vs bigger RDS; fewer Playwright renders; cache scrapes. Do not train a foundation model. --- ### Prompt engineering, token limits, DS for “highest KFC orders last 3 months” — Deepak Jul 2026 ([LinkedIn](https://www.linkedin.com/posts/deepak-gautam-a77b93222_amazon-sde-interviewexperience-activity-7485166684211671040-d-gv)) **Do not dump 3 months of rows into an LLM.** Token limits. **DS / system:** warehouse table `(store, day, item, qty)` → **pre-aggregate** last 90 days → top-K in SQL (`GROUP BY`, `ORDER BY`, `LIMIT`). LLM only: NL → SQL or explain the result. **Prompt:** schema + allowed metrics + “return SQL only.” Same pattern as Ylogx SQL RAG. **If they want an in-memory DS:** `HashMap` then heap of size K — that is DSA, not GenAI. --- ### GenAI-related UNNAMED — Nitesh ([LinkedIn](https://www.linkedin.com/posts/nitesh-khanna-75334b23b_amazon-sde1-interviewexperience-activity-7440683395870777344-oRfH)) (R2) Exact prompt unnamed. Have: (1) IQVIA 60s, (2) where not to use LLMs, (3) how you verify. Do not guess their question. --- ### How use GenAI; experience; how verify GenAI code; plus LCA; process scheduler — [LC 8014509](https://leetcode.com/discuss/post/8014509/amazon-sde-1-interview-experience-by-pra-azvd/) (HM) **Mixed slot:** GenAI **and** LCA **and** process-scheduler design. LCA → tree card. Scheduler → LLD (priority queue / fairness) — not an LLM. **Verify GenAI code:** compile/run; dry-run the example; check O(n) vs hidden O(n²); check null/empty; do not paste from ChatGPT into Live Code without tracing. Same standard as my own Java. --- ### YouTube prod issue, 1 hour, may use AI — [LC 8029194](https://leetcode.com/discuss/post/8029194/amazon-interview-sde-1-selected-by-anony-qatd/) (HM) Not “design YouTube.” **Incident:** playback/upload/search broken; 60 min; AI allowed as copilot. 1. Scope: error rate, region, client version (metrics first). 2. AI: summarize logs / suggest hypotheses — **do not apply a patch because the model said so**. 3. Verify: one-box repro, feature flag, rollback. 4. Tie to resume: LangSmith-style traces; Ylogx 99.9% / GiftedBooks 99.5% as “I care about uptime,” not as YouTube SRE. --- ### Validate AI-generated code; reliability; errors; not blind trust — Vaishali ([LinkedIn](https://www.linkedin.com/posts/vaishali-sahu-25205a359_amazon-interviewexperience-sde1-activity-7438128678401789953-6I04)) Same as LC 8014509 verify. Add: models invent APIs; they miss RLS; they write O(n²). IQVIA evals exist because fluency ≠ correctness. --- ### 2–3 general AI Qs UNNAMED — [Reddit AUTA 1ueybmg](https://old.reddit.com/r/LeetcodeDesi/comments/1ueybmg/amazon_sde1_auta_india_interview_experience_offer/) (R3) Also had LC Hard SW UNNAMED. For the AI minutes: IQVIA + should/should-not + verify code. Rank A two-DSA loops often **skip** this. --- ## 7. CS fundamentals actually asked (bible §5.F) Short. Java-backed. UTA two-DSA Rank A generally **did not** name these. ### Processes vs threads, deadlocks, memory management — [IE.in 2025-grad](https://interviewexperiences.in/experience/amazon/amazon-sde-1-2025-grad) (R1) **Same loop as Rate Limiter** (OA+3 SD), **not** UTA two-DSA. **Process vs thread:** process = isolated address space; thread = shared heap, cheaper context switch. Java: `Thread` / pool shares the JVM heap; a crashed native thread can still take the process down. **Deadlock:** four Coffman conditions; Java example — two locks acquired in opposite order. Fix: lock ordering, `tryLock`, fewer locks. Detect: thread dump / jstack. **Memory:** heap (objects) vs stack (frames); GC in Java; intern off-heap only if they push. Do not lecture generations unless asked. ### Kafka ordering / partitioning; B Tree vs B+ Tree — [igreaper](https://igreaper.medium.com/amazon-sde-1-interview-experience-a69578a4f699) (their R3 = our R2; OA-as-R1) **Kafka:** order is **per partition**, not global. Same key → same partition → ordered. More partitions = more parallelism, not a total order. **B vs B+:** both multiway for disks. **B+:** all keys in leaves, leaves linked — range scans. Internal nodes = indexes only. Postgres-style indexes are B+ flavored. I did not operate Kafka in internships; this is CS, not a Ylogx bullet. ### CN; transactions/deadlocks; Bankers Algo; threads vs processes — [GFG sde-1-17](https://www.geeksforgeeks.org/interview-experiences/amazon-interview-experience-for-sde-1-17/) **CN:** one sentence — TCP reliable byte stream vs UDP (Horizon GStreamer UDP feed is the honest UDP example). **Transactions:** ACID; deadlock on two updates in opposite row order — retry or consistent lock order. Ylogx: Postgres. **Bankers:** deadlock **avoidance** — allocate only if the state stays safe. Rare in app code; say that. **Threads vs processes:** same as above. ### HashMap / HashSet internals; why PQ — [LC 6570344](https://leetcode.com/discuss/post/6570344/amazon-sde-1-loop-interview-by-anonymous-i0v6/) (after review-word-count DSA) **HashMap (Java):** array of bins; `hash ^ (hash >>> 16)`; collision = list, treeify at 8 (Java 8+); load factor 0.75, resize 2×. `HashSet` = `HashMap` keys. Null: one null key in HashMap. **Why PQ:** Top-K, Connect Sticks / Huffman-style, Dijkstra. `PriorityQueue` is binary heap, not sorted TreeMap (log n extra). Word-count follow-up: HashMap counts + heap of size K. ### DNS, MAC vs IP, thrashing, virtual memory — GFG 6-months-experienced Dec **2020** (older — very short) **DNS:** name → IP (Ylogx: GoDaddy + Route 53). **MAC vs IP:** L2 local vs L3 routable. **Virtual memory:** pages on disk. **Thrashing:** more paging than work — working set > RAM. ### S3 / NoSQL / sharding / Docker / EC2 / REST — [IE.in L4 2025 fresher](https://interviewexperiences.in/) listed after BR Tie to resume, one breath: Ylogx **REST** on **Docker/ECS** (not “I ran EC2 by hand”), CloudFront in front. **S3** = object store (models/PDFs) vs Postgres for RLS rows. **NoSQL** when you have no joins (session cache → Redis). **Sharding** if one Postgres dies at tenant scale — I did not shard Ylogx; RLS + one primary is what I shipped. --- ## 8. INTERN appendix (short) **INTERN — format-similar, difficulty-weaker. Not FTE UTA evidence.** Pattern only. No full codes. Do not stamp an LC id the intern did not name. | Asked (candidate wording) | Pattern | id if **they** named it | Source | | --- | --- | --- | --- | | Rotated Search + dup/min/rotation follow-ups | BS on rotated; if `a[l]==a[m]==a[r]` shrink | — | [DesiQnA 19202](https://www.desiqna.in/19202/amazon-sde-1-recent-interview-experiences-2026-set-61) | | Remove K Digits | monotonic stack, strip leading zeros | **LC 402** | same | | Rotated Search; Remove K digits to form **maximum** | stack but keep larger digits | — | [Ganesh](https://www.linkedin.com/posts/ganesh-tiwari1_amazon-interviewexperience-sdeintern-activity-7417887104892022784-L-kN) | | Minimizing Tree Diameter with Path Rewiring | tree diameter / reroot; **CF 2131D** | **CF 2131D** | DesiQnA 19202; [LC 7913310](https://leetcode.com/discuss/post/7913310/amazon-sde-intern-interview-experience-b-3pra/) reprint? | | House Robber + House Robber II | circular: max(rob 0..n-2, rob 1..n-1) | named HR II | [IE.in DSA+GenAI](https://interviewexperiences.in/experience/amazon/amazon-interview-experience-sde-1-intern-dsa-round-gen-ai-round) | | Aggressive Cows variation | BS on min distance | UNNAMED | same | | group similar strings one-swap; `["tars","rats","arts","star"]` → `2` | union-find if one swap apart | **UNNAMED** — example matches LC 839 **family**; **do not say they asked LC 839** | same | | NGE variation | monotonic stack | no id | [IE.in oncampus](https://interviewexperiences.in/experience/amazon/amazon-sde-intern-2026-interview-exp-oncampus) (slot titled GenAI Fluency — **was DSA**) | | Stocks max 2 tx variation | DP 2-buy / 4-state | no id | same | | Alien dictionary | topo on letter graph | — | same R2 | | Pacific Atlantic; team dominance / Course Schedule | reverse DFS from oceans; topo | **LC 417**; **LC 207** | [LC 7320620](https://leetcode.com/discuss/post/7320620/amazon-sde-intern6m-interview-experience-6rr7/) | | Daily Temps; Next Greater II; Reorganize String | mono stack; circular NGE; greedy + heap no two adjacent | **LC 739 / 503 / 767** | [LC 8463405](https://leetcode.com/discuss/post/8463405/) | | Asteroid Collision; Minimize Max Diff of Pairs | stack signs; BS on max diff + greedy pair | **LC 735**; **LC 2616** | [LC 7124844](https://leetcode.com/discuss/post/7124844/) | | Candy / resource on scores; Beautiful Subsets (no two differ by k) | two-pass ratings; subset DP / skip-k | named | [Karthik](https://www.linkedin.com/posts/kmagadi_amazon-softwareengineering-sdeintern-activity-7409831425908252672-kXoz) | | BST in-order non-increasing; min window ≥k distinct product ids | reverse inorder / two pointers + freq | UNNAMED | [LC 7261637](https://leetcode.com/discuss/post/7261637/amazon-sde-internship-6m-jan-june-26-on-oo2ql/) | | heap UNNAMED; custom DS time-based eviction | heap / TTL list | UNNAMED | [Saloni](https://dev.to/saloni_jain_aba5e8c508f8a/amazon-sde-i-6-months-2026-interview-experience-off-campus-4ago) — closest public to mentor Login Tracker **shape**, still intern | | GetRandom; count negatives sorted matrix | HashMap+list swap; staircase O(m+n) | — | [LC 7335489](https://leetcode.com/discuss/post/7335489/my-amazon-sde-intern-interview-experienc-f8rp/) Job **3068961** | | Basic Calculator II `3+2*2`→7 | stack + last sign, `*` `/` immediate | — | [DevBrainiac 129](https://devbrainiac.com/blogs/129/amazon-sde-intern-interview-experience-2-rounds-4-coding-problems-selected/) | Skip intern OA. Skip Class B help-account k-th/BFS ([DEV 11da](https://dev.to/net_programhelp_e160eef28/amazon-2026-sde-intern-vo-interview-experience-two-technical-rounds-breakdown-11da)). Sreeja trees/DP UNNAMED — pattern only. --- ## 9. NOT MY FORMAT appendix (short) Do not write full solutions. Not your 60-min UTA two-DSA. | Format | Why NMF | Named bits | URL | | --- | --- | --- | --- | | US 3×60 | US same-day three lives | Unix **Find** (R2 analogue); LCA family; merge two sorted streams | [Levels.fyi oP6vow](https://www.levels.fyi/community/thread/oP6vow/amazon-sde-i--interviewing-experience) | | FTC 5-round / experienced 4–5 | FTC / YOE, not AUTA two-tech | Playlist O(1) except moveByK ([LC 6629134](https://leetcode.com/discuss/post/6629134/amazon-sde-1-ftc-bangalore-april-2025-by-rbwb/)); **LRU / recently opened files in R4/BR** ([Roundz 172](https://roundz.substack.com/p/interview-experience-172-amazon-sde1-l4)); board-game LLD [LC 6813913](https://leetcode.com/discuss/post/6813913/amazon-sde-1-interview-experience-2025-o-p3fd/) | see bible §8 | | SDE-2 Rate Limiter | SDE II / YouTube HLD | **Does not add** SDE I count (still **1**, IE.in 2025-grad, not UTA) | [LC 7311674](https://leetcode.com/discuss/post/7311674/); Hitesh Medium; YouTube d0yM6h0XRxk | | Canada AUTA | geography | cart/checkout + coupons OOD; LRU-like UNNAMED | [Jay Patel](https://www.linkedin.com/posts/jay-patel-06684b153_amazon-amazoninterview-sde-activity-7358585686263750656-wEXo) | | CN | leetcode.cn / nowcoder default | — | bible §8 | | help-accounts | Class B mixed roles | Kth / Jump variants | [DEV 5c24](https://dev.to/net_programhelp_e160eef28/amazon-sde-virtual-onsite-interview-experience-2026-5c24); InterviewShow | Ruchi FTC **two same-day** lives stay in the FTE bank, not this 5-round row. --- ## 10. OPTIONAL MENTOR (not evidence) **Login Tracker (`new_login` / `get_oldest_login`) is not first-hand evidence; unverified in [`Question-Research-BIBLE.md`](Question-Research-BIBLE.md) §10.** Mentor file only: `amazon-sde1-interview-prep.md`. **Do not present as an R2 question for Job 10454435.** **Closest public (different problems):** LRU — Bhavya Interview 2; GetRandom O(1) — DevBrainiac R1 and Reddit [1lqy9uq](https://old.reddit.com/r/leetcode/comments/1lqy9uq/amazon_sde1_interview_experience/) R2; Spring login Controller/Facade/Service/Repository — Bhavya **HM, not a tracker**; intern time-based eviction — Saloni. prachub login/firstUser is labeled **Oracle**. Clarify out loud if it ever appeared: repeat login refresh or duplicate row? peek vs pop oldest? TTL? **Trick:** LRU with insert + peek-oldest — HashMap + DLL (oldest at head, newest at tail). ### Java — HashMap + DLL (from mentor Python) ```java class LoginNode { String userId; long timestamp; LoginNode prev, next; LoginNode(String userId, long timestamp) { this.userId = userId; this.timestamp = timestamp; } } class LoginTracker { private final Map map = new HashMap<>(); private final LoginNode head = new LoginNode(null, 0); // head.next = oldest private final LoginNode tail = new LoginNode(null, 0); // tail.prev = newest LoginTracker() { head.next = tail; tail.prev = head; } private void remove(LoginNode node) { node.prev.next = node.next; node.next.prev = node.prev; } private void addToTail(LoginNode node) { LoginNode last = tail.prev; last.next = node; node.prev = last; node.next = tail; tail.prev = node; } /** O(1). Repeat user refreshes position. */ void newLogin(String userId, long timestamp) { if (map.containsKey(userId)) { remove(map.get(userId)); } LoginNode node = new LoginNode(userId, timestamp); map.put(userId, node); addToTail(node); } /** O(1). Peek — does not remove. */ AbstractMap.SimpleEntry getOldestLogin() { if (map.isEmpty()) { return null; } LoginNode oldest = head.next; return new AbstractMap.SimpleEntry<>(oldest.userId, oldest.timestamp); } } ``` TC/SC: O(1) ops, O(n) users. ### Java sidecar — LinkedHashMap (insertion order) ```java class LoginTrackerLhm { private final LinkedHashMap logins = new LinkedHashMap<>(); void newLogin(String userId, long timestamp) { logins.remove(userId); logins.put(userId, timestamp); } Map.Entry getOldestLogin() { if (logins.isEmpty()) { return null; } return logins.entrySet().iterator().next(); } } ``` Follow-ups in the mentor file (still not evidence): lock for threads; TTL; distributed ≈ same HashMap+order pattern as Rate Limiter — and Rate Limiter SDE I live count stays **1**, not UTA. --- ## 11. Story cheat-sheet Metrics only from the Aug 2026 resume. **Primary project ≤ 3 LPs.** Hire-and-Develop / Earth’s Best Employer = IEDC + Horizon teammates — no fake reports. | LP | Primary project | One-line hook | Resume metric | | --- | --- | --- | --- | | Customer Obsession | GiftedBooks | Students get answers from *their* PDF, not a generic bot | 2.5× comprehension; doubts **3–10 min**; +50% engagement; +35% reading | | Ownership | Horizon | Core software on the ERC rover, not a side script | 17th / 80+; 60 FPS; costmap **−55%** collision | | Invent and Simplify | StratifyLabs | Browser inference instead of a full GPU iteration loop | **−30%** ML iteration; **50+** models | | Are Right, A Lot | IQVIA | Do not ship RAG without traces | LangSmith evals + test-case generation on 200+ page BRDs | | Learn and Be Curious | IQVIA | New stack: LangGraph + Azure hybrid + GraphDB | 200+ sites ranked; adaptive retrieval | | Hire and Develop the Best | IEDC CUSAT / Horizon | Tech-team help on ROS2 and hackathon delivery — **not** a manager | ERC core software; IEDC tech team | | Insist on the Highest Standards | Argus | 73 mAP was not enough for safety alerts | **73 → 89 mAP**; 15k images; **−50%** violations | | Think Big | Horizon | Full autonomy stack for a global rover challenge | 17th globally / 80+; ZED **2M+ pts/s** | | Bias for Action | Hackathons | Ship under a weekend constraint | CodeRecet **1st**; MLH Best Project; Magnathon runner-up; **8** events | | Frugality | Ylogx | Cache and CDN before a larger box | Redis **−35%** latency; CloudFront; **sub-210 ms** | | Earn Trust | Ylogx | Bot cannot read another tier’s rows | RLS + RBAC **3 tiers** | | Dive Deep | IQVIA | Rank sources instead of first-hit scrape | **200+** websites; **200+** page BRDs | | Have Backbone; Disagree and Commit | Ylogx | SQL RAG does not ship without DB RLS | RLS + RBAC **3 tiers** (same control as Earn Trust; frame as the disagreement) | | Deliver Results | GiftedBooks | Latency and uptime as student-facing SLAs | **sub-300 ms**; **99.5%** uptime; doubts **hours → 3–10 min** | | Strive to be Earth’s Best Employer | IEDC CUSAT | Inclusive student tech community, honest scope | IEDC tech team (no headcount) | | Success and Scale Bring Broad Responsibility | Argus | 20 cameras and an audit log, not a demo GIF | **20+** cameras; **24 FPS**; compliance **2×**; Postgres logging | **Secondary hooks (do not steal primary):** Ylogx **40%** faster reports, **99.9%** uptime, **+65%** analysis, **30** dashboards **+60%** if Deliver already used GiftedBooks. Horizon +40% obstacle if Argus already used for standards. ### Off-resume (confirm) — do not present as on-resume From `amazon-sde1-interview-prep.md` only: Django CUSAT portal security audit; Purplle-style CCTV (YOLOv8 + ByteTrack + OSNet); LLM uncensored/abliteration/LoRA. Also GitHub-only: **AegisAI** (not GiftedBooks), **warpflow**, Conv-BI as a **Ylogx-adjacent** repo. **InstaRecon / PhiSiFi:** ethics one-liner, then Stratify / Argus / Ylogx / IQVIA. --- --- *End. Answers for reported SDE I / UTA / AUTA live questions plus resume STAR. Job 10454435: still none. Login Tracker: unverified. Rate Limiter SDE I live-round count: 1 (not UTA two-DSA). R2 lock: 18 Aug 2026.*