⚡ Samsung PPO · Java Algorithm Mastery

Learned: 0 / 0

Crack the Samsung 3-Hour Coding Test

Every classic Samsung R&D India problem from your practice set — re-written in clean, idiomatic Java, each with a precise problem statement, the core idea, a hand-drawn visualization, the full solution, and complexity. Tick problems off as you master them; your progress is saved in this browser.

Tip: use the category filters and search to drill the “MUST DO” topics first — Bipartite, Cycle detection, Burst Balloon, Endoscopy, Mr Lee/Kim, Research Team, Spaceship, Wormhole, Omnious.

🟢 Easy = warm-up🟡 Medium = core test level🔴 Hard = stretch 📊 = interactive visualization

01Bipartite Graph — Same Colour Set

Graph 2-ColouringDFSEasy

❓Problem

Given an undirected graph as an adjacency matrix, decide whether it is bipartite — i.e. whether the vertices can be split into two groups so that every edge joins the two groups (never two vertices inside the same group). If it is bipartite, print one of the two colour groups; otherwise print -1. The graph may be disconnected.

Input 4 0 1 0 1 1 0 1 0 0 1 0 1 1 0 1 0 Output (vertices coloured 0) 0 2

💡Key Idea

A graph is bipartite iff it has no odd-length cycle. Try to 2-colour it: start a component with colour 0, and every neighbour must get the opposite colour (1 - color[u]). If you ever reach a neighbour that is already coloured the same as the current vertex, an odd cycle exists → not bipartite. Loop over all vertices to also colour disconnected components.

Pattern to remember: “opposite-colour DFS/BFS”. The exact same skeleton solves team-splitting, conflict graphs, and is-this-graph-2-colourable questions.

📈Visualization

Group 0 Group 1 0 1 2 3
Every edge crosses from a blue vertex to a pink vertex — no edge stays inside one group → bipartite. If any edge were drawn inside a group, the answer would be −1.
⏱ Time: O(V²) (matrix scan)
💾 Space: O(V) colour array + recursion

02Detect & Print a Cycle — Directed Graph

Graph DFSColours (White/Gray/Black)Medium

❓Problem

Given a directed graph, determine whether it contains a cycle, and if so print the vertices that form one such cycle in order.

Input (n, then m edges u→v) 4 4 0 1 1 2 2 0 2 3 Output Cycle: [0, 1, 2]

💡Key Idea

Use the classic three-colour DFS:

  • WHITE (0) — not visited yet.
  • GRAY (1) — on the current recursion stack (being explored).
  • BLACK (2) — fully finished.

If DFS reaches a GRAY vertex, that edge points back into the active path — a back edge — which means a cycle. Record the back-edge endpoints (cycleStart, cycleEnd) and rebuild the path with a parent[] array.

Directed vs Undirected: for directed graphs a back edge to any GRAY ancestor is a cycle. The parent==v shortcut used for undirected graphs (problem 03) does not apply here.

📈Visualization

0 1 2 3 dashed pink = back edge (2 → 0) closes the cycle 0→1→2→0
Vertices 0,1,2 are GRAY on the stack when the edge 2→0 finds 0 still GRAY → cycle found. Vertex 3 is a dead-end branch.
⏱ Time: O(V²)
💾 Space: O(V)

03Detect & Print a Cycle — Undirected Graph

Graph DFSParent TrackingMedium

❓Problem

Given an undirected graph (n vertices, m edges), detect a cycle and print its vertices.

Input (n m, then m edges) 4 4 0 1 1 2 2 3 3 1 Output Cycle: [1, 2, 3]

💡Key Idea

DFS while remembering the vertex you came from (the parent). A neighbour that is already visited and is not the parent means you reached it by a second route → cycle. The one extra rule vs. the directed case is the v == parent skip, because in an undirected graph the edge you just used appears in both directions.

📈Visualization

0 1 2 3 back edge 3 — 1
Purple = the cycle 1-2-3. The yellow dashed edge 3-1 reaches an already-visited non-parent vertex, revealing the loop.
⏱ Time: O(V²)
💾 Space: O(V)

04Doctor Probability — Most Likely Division

Graph DFSProbabilityMedium

❓Problem

A doctor moves around divisions connected as a directed weighted graph; an edge weight is the probability of moving along it. He spends 10 minutes in each division. Given a total time T, find the division he is most likely to be in at that moment (and the probability), by summing the probability of every walk of the right length ending in each division.

Input (tests; then nodes edges time; then edges f t prob…) 1 6 10 40 1 2 0.3 1 3 0.7 3 3 0.2 3 4 0.8 2 4 1 4 5 0.9 4 4 0.1 5 6 1.0 6 3 0.5 6 6 0.5 Output 6 0.774000

💡Key Idea

Enumerate all walks from the start that last exactly T/10 hops. Carry the running product of edge probabilities p. When time runs out, add p to answer[currentDivision] (many different walks can land on the same division — their probabilities accumulate). Finally pick the division with the largest accumulated probability.

Why DFS and not just one path? Each step branches into several possible moves, each with its own probability. We sum over all branches → this is expectation/total-probability, computed by exhaustive DFS over walks of fixed length.

📈Visualization

0.30.7 0.81.00.9 1 2 3 4 5 6
Each arrow carries a probability. A walk's probability is the product along it; division 6 collects 0.774 by summing every length-4 walk that ends there.
⏱ Time: O(branchingT/10)
💾 Space: O(V²) graph + recursion depth T/10

05Chess Piece — Minimum Knight Moves 📊

Graph BFSGrid / Shortest PathEasy

❓Problem

On an N×M board a moving piece jumps like a knight. Find the minimum number of moves to land exactly on a stationary target. Print -1 if unreachable.

Input (T; then N M; then R C S K) 2 9 9 3 5 2 8 20 20 2 3 7 9 Output Case #1 2 Case #2 5

💡Key Idea

Unweighted shortest path on a grid ⇒ BFS. Each cell has up to 8 knight moves. BFS explores in expanding rings, so the first time we touch the target, its distance is the minimum. Mark cells as visited the moment they enter the queue to avoid re-processing.

📈Visualization — BFS rings (press Play)

start target current ring (frontier) already visited
⏱ Time: O(N·M)
💾 Space: O(N·M)

06Laughing Gas — Time to Fill the Room

Graph BFS Flood FillGridEasy

❓Problem

Gas is released at one cell of a grid and spreads to the 4-adjacent open cells (value 1) each second; walls are 0. Output how many seconds until the gas stops spreading — i.e. the maximum distance from the source to any reachable cell.

Input (T; R C; grid; start row col) 1 3 3 1 1 1 1 0 1 1 1 1 1 1 Output Case #1 4

💡Key Idea

Plain multi-ring BFS flood fill. The source is distance 0; each ring of newly-reached open cells is +1 second. The answer is simply the largest distance label assigned during the flood.

📈Visualization

012
1█3
234
Numbers = seconds for the gas to arrive. The wall (█) is skipped, so the far corner is reached in 4 seconds — the answer.
⏱ Time: O(R·C)
💾 Space: O(R·C)

07Frog Jump — Cheapest Path (0-1 BFS)

Graph 0-1 BFS (Deque)GridMedium

❓Problem

A frog sits on a grid where 1 = lily pad (standable), 0 = water. Moving horizontally along pads is free (cost 0). A vertical hop costs 1. Find the minimum cost to travel from a source pad to a destination pad.

Input (n; n×n grid; sx sy tx ty) 3 1 1 1 0 1 0 1 1 1 0 0 2 2 Output 2 (descend 2 rows = 2 vertical hops; sideways is free)

💡Key Idea

Edges weigh only 0 or 1 ⇒ use 0-1 BFS with a double-ended queue. A 0-cost (horizontal) move pushes to the front; a 1-cost (vertical) move pushes to the back. This keeps the deque sorted by distance, giving Dijkstra-quality answers in O(V+E) without a heap.

Trap: a plain FIFO BFS is wrong when edges have mixed 0/1 weights — it may finalize a node before a cheaper 0-cost route arrives. The deque (front for 0, back for 1) is what makes it correct.

📈Visualization

S→0·
█↓1█
·↓2G=2
Horizontal slides (→) keep the same cost; only vertical hops (↓) add 1. Two descents from the top row to the bottom row ⇒ cheapest cost 2.
⏱ Time: O(N²)
💾 Space: O(N²)

08Endoscopy — Connected Pipes

Graph BFSBitmask / Shape MatchingHard

❓Problem

A grid of pipe pieces (types 1–7); each type opens toward some of {left, right, up, down}. Starting from a given pipe and an endoscope of length L, count how many pipes are reachable. You may move between adjacent pipes only when both sides have a matching opening, and only within L steps.

Pipe openings 1: L R U D 2: U D 3: L R 4: R U 5: R D 6: L D 7: L U (0 = no pipe) Input (T; n m sX sY L; grid) Output count of reachable pipes (incl. start)

💡Key Idea

Encode each pipe as four booleans (its openings). A step from A to its neighbour B on the right is legal only if A opens right AND B opens left. Then it is ordinary BFS with a distance cap: only enqueue a neighbour when dist + 1 ≤ L. Count every cell that gets a distance label.

📈Visualization — opening shapes

123 4567 Two neighbours connect only if their facing edges both carry a line.
⏱ Time: O(n·m)
💾 Space: O(n·m)

09Research Team — Rare Elements (1-Centre)

Graph Multi-BFSMin-of-MaxHard

❓Problem

A grid has roads (1) and blocked cells (0). Up to 5 rare-element locations sit on roads. Build a research centre on a road so that the longest distance from the centre to any element is as small as possible. Output that minimised longest distance.

Input (T; then per test: N C; C locations; N×N grid) Output #t <shortest of the longest distances>

💡Key Idea

Naïvely you'd BFS from every road cell — O((N²)²). Instead, BFS once from each element (only ≤5 of them) to get its distance to every road cell. Then for each candidate cell take the max over the elements (worst element), and the answer is the min of those maxes — a classic min-of-max (1-centre) pattern.

Optimisation insight: flipping the BFS direction (from the few sources, not the many candidates) cuts work from ~160 000 BFS runs to just 5. Always BFS from the smaller set.

📈Visualization

E112█
12★34
23█E2
Distances shown are from element E1. The starred cell ★ is one candidate centre; its score is max(dist to E1, dist to E2). The answer is the candidate whose worst-element distance is smallest.
⏱ Time: O(C·N²)
💾 Space: O(C·N²)

10Mr Kim — Shortest Delivery Route

Backtracking TSP (Path)Permutations + PruningMedium

❓Problem

Starting at the office, Mr Kim must visit all N customers (5–10) and finish at his home. Distance between points is Manhattan |x₁−x₂|+|y₁−y₂|. Find the length of the shortest such route.

Input (T; then N; then office, home, then N customers) 5 0 0 100 100 70 40 30 10 10 5 90 70 50 20 Output #1 200

💡Key Idea

With N ≤ 10, just try every order of customers (backtracking permutations). Keep a running cost; when all customers are visited add the hop to home and update the best. Crucial speed-up: prune the branch as soon as cost ≥ best — this turns a hopeless 10! search into something instant.

For the larger TSP (N up to ~15) the textbook upgrade is bitmask DP: dp[mask][last]. The permutation+prune version is what fits a 3-hour test for N ≤ 10.

📈Visualization

Office C1 C2 C3 Home
One candidate ordering Office → C1 → C2 → C3 → Home. Backtracking tries all orderings and keeps the cheapest total Manhattan length.
⏱ Time: O(N!) with pruning
💾 Space: O(N)

11Mr Lee — Cheapest Round Trip

Backtracking TSP (Cycle)Cost MatrixMedium

❓Problem

Given an N×N airfare matrix (entry 0 = no flight), start at city 0, visit every city exactly once, and return to city 0 at minimum total fare. Print -1 if impossible.

Input (T; then N; then N×N matrix) 1 5 0 14 4 10 20 14 0 7 8 7 4 5 0 7 16 11 7 9 0 2 18 7 17 4 0 Output 30

💡Key Idea

Same permutation backtracking as Mr Kim, but it's a cycle: after placing the last city you must add the edge back to 0. Skip any move where the fare is 0 (no flight). Base case fires at count == N-1 because city 0 is fixed as start.

Mr Kim vs Mr Lee: Kim is an open path (office → home, different endpoints); Lee is a closed cycle (back to the start). One line of difference — recognise which one the statement wants.

📈Visualization

0 1 2 3 4
A Hamiltonian cycle starting and ending at city 0. Backtracking enumerates every such loop and keeps the cheapest.
⏱ Time: O(N!)
💾 Space: O(N)

12Wormhole — Min Distance (DFS)

Backtracking DFS over SubsetsManhattanMedium

❓Problem

A spaceship travels from source to destination. There are N bidirectional wormholes; wormhole i connects point A=(x₁,y₁) and B=(x₂,y₂) and costs w to traverse. Moving on the plane costs Manhattan distance. Find the minimum total cost; you may use any number of wormholes (or none).

Input (T; then N; sX sY tX tY; then N lines: x1 y1 x2 y2 w) Output minimum distance

💡Key Idea

At each state (current position, target, accumulated cost) you may either go straight to the destination, or enter any unused wormhole from either end (pay the walk to that mouth + the wormhole fee, then continue from the other mouth). DFS over the order of wormholes used, marking each used so it isn't re-entered. Track the global minimum.

See problem 34 (Floyd–Warshall) for the same task solved as a graph of 2N+2 nodes — cleaner when N is larger.

📈Visualization

src A B dst walk → A, pay w, teleport to B, walk → dst
⏱ Time: O(N!·2^N) worst
💾 Space: O(N)

13Oil Mine — Fair Circular Distribution

Backtracking Circular PartitionMin-of-Max−MinHard

❓Problem

m oil mines sit in a circle. Split them among n companies so each company gets a contiguous arc (no interleaving). Minimise the difference between the richest and poorest company's total.

Input (T; then n m; then m mine values) 2 2 4 6 13 10 2 2 4 6 10 13 2 Output 5 1

💡Key Idea

Because the layout is a ring, fix where the first cut goes by trying every mine as a starting point. Walk the circle; at each mine choose to either extend the current company or close it and open a new one. When you arrive back at the start having opened exactly n companies, update the answer with max − min of the company totals.

📈Visualization

6 13 10 2
Cuts split the ring into arcs. Best split here: {13} vs {10,2,6} → 13 vs 18 → difference 5.
⏱ Time: O(m · 2^m)
💾 Space: O(m)

14Pillar Banner — Two Equal-Height Stacks

Backtracking Subset Partition3-way choiceMedium

❓Problem

From an array of block heights, build two pillars of equal height (each pillar is a subset of blocks; not every block must be used) to place a banner as high as possible. Print the maximum equal height, or 0 if no non-trivial pair exists.

Input 5 1 2 3 4 6 Output 8 (pillar A = {6,2} = 8, pillar B = {4,3,1} = 8)

💡Key Idea

Each block has three choices: go on pillar 1, go on pillar 2, or be left out. Recurse index by index carrying the two running sums p1, p2. Whenever p1 == p2, that's a valid equal height → update the max. This 3-way recursion is cleaner (and avoids duplicate work) compared with picking blocks in arbitrary order.

This is the "Tug of War / Equal Subset" template. The same shape answers "can we split into two equal-sum halves?" and "balance two loads".

📈Visualization

6
2
4
3
1
Pillar A = {6,2} = 8  |  Pillar B = {4,3,1} = 8  → equal height 8.
⏱ Time: O(3ⁿ)
💾 Space: O(n)

15Jewel Maze — Most Jewels, No Repeats

Backtracking Grid DFSPath ReconstructionMedium

❓Problem

An N×N maze: 0 = passage, 1 = wall, 2 = jewel. Enter at top-left, exit at bottom-right, never stepping on the same cell twice. Collect the maximum number of jewels and print the winning path (marked with 3).

Input (T; then N; then N×N maze) Output jewels + the path grid

💡Key Idea

Brute-force DFS with backtracking: from each cell try all 4 directions onto unvisited non-wall cells, adding 1 whenever you step on a jewel. When you reach the exit, if the jewel count beats the best so far, snapshot the current visited grid as the best path. Restore visited on the way back so other routes can use those cells.

📈Visualization

►█♦►
▼►▲▼
·▲█▼
█··◆
One winning route (purple) from top-left to bottom-right collecting jewels (♦). DFS explores every legal route and keeps the one with most jewels.
⏱ Time: O(4^(N²)) worst (small N)
💾 Space: O(N²)

16Toggle Columns — Maximise All-1 Rows

Backtracking Bitmask SubsetsParity TrickMedium

❓Problem

Given a binary matrix, you may toggle any column (flip all its bits), exactly k toggles in total (a column may be toggled more than once). Maximise the number of rows that become all 1s.

Input (T; then rows cols k; then matrix) 1 3 3 2 1 0 0 1 0 1 1 0 0 Output #1 2

💡Key Idea

Only the parity of each column's toggle count matters — flipping a column twice is a no-op. So the real decision is: which set S of columns ends up flipped an odd number of times. A set of size f is reachable iff f ≤ k and k − f is even (dump the leftover toggles in cancelling pairs). Enumerate all 2^cols subsets, keep the feasible ones, and count all-1 rows.

The exam trap is brute-forcing sequences of k toggles (huge). Collapsing to subset + parity is what makes it fast.

📈Visualization

10→10→1✓
10→11→0✗
10→10→1✓
Flipping columns 2 & 3 (set size 2 = k) makes rows 1 & 3 all-1 → answer 2. The yellow cells are the toggled columns.
⏱ Time: O(2^cols · rows · cols)
💾 Space: O(rows · cols)

17Old Phone — Minimum Touches

Backtracking Bounded DFSExpression SearchHard

❓Problem

An old phone's dial pad has some broken digits; a calculator offers some working digits and operations (+ − × ÷ =). Every key press is one "touch". Find the minimum touches to display a target number — either by typing it directly (if its digits work) or by computing it, e.g. 1 + 4 = (4 touches) to get 5.

Per test: N M O / working digits / operation codes (1=+,2=−,3=×,4=÷) / target Output: #case: minimum touches (≤ O)

💡Key Idea

Search the space of partial calculator expressions with a hard cap of O touches (so the recursion always terminates). State = (previousValue, currentNumber, pendingOp, touches). From any state you may press a working digit (append/start a number) or, once a number is shown, press an operation (which evaluates the pending op into previousValue). Whenever the value equals the target within the budget, record the touch count.

Think of it as an IDDFS / bounded BFS over states. The O cap is what keeps an otherwise infinite search finite.
⏱ Time: exponential, bounded by O
💾 Space: O(O) recursion

18Fishermen — Minimum Walking Distance

Backtracking AssignmentPruningHard

❓Problem

A river bank has N numbered fishing spots (1…N). Several gates each release a number of fishermen; the gate at position g sends a fisherman to a spot at cost |spot − g|. Every fisherman must take a distinct spot. Minimise the total walking distance of all fishermen.

Input (N; G gates; then G lines: gatePosition fishermenCount) 10 3 4 5 6 2 10 2 Output 9

💡Key Idea

Flatten every fisherman into a list tagged with its gate position. This is a minimum-cost assignment: place fishermen one by one onto free spots, accumulate |spot − gate|, and keep the global minimum. Prune any branch whose partial cost already reaches the best found — that keeps the search tiny for the small N of a real test.

Because cost is |spot − gate| on a line, the optimum never "crosses"; the backtracking with pruning finds it exactly. (For large N you'd switch to min-cost matching / Hungarian.)

📈Visualization

1 2 3 4* 5 6* 7 8 9 10* orange* = gate positions (4: 5 men, 6: 2 men, 10: 2 men)
Each fisherman walks to the nearest free spot subject to all being distinct; backtracking minimises the summed walk.
⏱ Time: O(N·N!/(N−F)!) worst, pruned
💾 Space: O(N)

19Spaceship & Bomb — Maximum Coins

Backtracking Grid RecursionOne-time Power-upHard

❓Problem

A spaceship starts at the bottom-centre of a 5-column grid and climbs upward, each step moving to the cell above-left, above, or above-right. 1 = coin, 2 = enemy (blocks the move), 0 = empty. You may detonate a bomb once to clear all enemies in the 5×5 block ahead. Collect the maximum coins before getting stuck or running off the top.

Input (T; then rows; then rows×5 grid) Output #case : max coins

💡Key Idea

Recurse upward exploring the three diagonal moves, adding coins, never stepping onto an enemy. If all three moves are blocked and the bomb is still available, detonate the 5×5 region ahead (clearing enemies) and retry from the same cell with one fewer bomb. The recursion returns the best coin total over all choices.

📈Visualization

01020
02→02→02→01
00▲11
xxSxx
Yellow row = enemies cleared by the one-time bomb. The ship (S) climbs diagonally collecting coins; the bomb opens a blocked wall of enemies.
⏱ Time: O(3^rows) bounded by 5 cols
💾 Space: O(rows)

20Inventory — Maximise Selling Price

Backtracking Bounded Knapsack≤3 configsMedium

❓Problem

You hold D CPUs, E memory chips, F boards. A leftover CPU sells for d, a leftover chip for e. Each of N PC configurations consumes (Dᵢ,Eᵢ,Fᵢ) parts and sells for SPᵢ. Using at most 3 distinct configurations (each any number of times), maximise total revenue (assembled PCs + leftover parts sold raw).

Input (T; then D E F d e; then N; then N lines Dᵢ Eᵢ Fᵢ SPᵢ) 1 10 10 10 2 1 1 1 2 2 3 Output Case #1 30

💡Key Idea

DFS over configurations with two moves at each: skip this config, or use it 1, 2, 3… times while parts remain (incrementing the "distinct configs used" counter, capped at 3). When you stop, add the value of leftover CPUs and chips (D·d + E·e) and update the best.

⏱ Time: O(N³ · max-uses)
💾 Space: O(N)

212D Matrix — Max-Sum Path & Path Count

DP Grid DPCountingMedium

❓Problem

From the top-left to the bottom-right of an N×N grid of digits, moving only right, down, or diagonally down-right, find the maximum digit sum and how many distinct paths achieve it. Cells marked x are blocked. Output 0 0 if no path exists.

Input (T; then N; then N×N grid of digits / x) Output <maxSum> <numberOfMaxPaths>

💡Key Idea

Fill a DP table from the bottom-right backward. Each cell stores two things: the best sum reachable to the goal, and the count of ways achieving it. A cell's best = its digit + max of its three forward neighbours; its count = sum of the counts of every neighbour that ties for that max. Blocked cells are −∞. If the start ends up −∞, there is no path.

Counting-while-optimising is a recurring trick: carry (bestValue, ways) together and add up the ways of all neighbours that match the best.

📈Visualization

j0j1j2
i012
2 ways
9
2
5
1
i110
1
7
1
4
1
i26
1
3
1
0
1
Each cell = (best sum to goal, #ways). Cell (0,0) takes its digit + max(right, diag, down); ties in the neighbours add their counts together.
⏱ Time: O(N²)
💾 Space: O(N²)

22Burst Balloon — Classic Interval DP 📊

DP Interval DP"Last to burst"Hard

❓Problem

Balloons hold numbers. Bursting balloon i earns nums[left]·nums[i]·nums[right] coins, where left/right are its current neighbours (treat out-of-range as 1). After it pops, its neighbours become adjacent. Burst all balloons to collect the maximum coins.

Input (n; then n numbers) 4 3 1 5 8 Output 167

💡Key Idea

The trick is to think about which balloon is the last to burst in a range (left, right). If balloon k is last, its neighbours are exactly the fixed walls left−1 and right+1 (everything between is already gone). So:

dp[l][r] = max over k of ( nums[l-1]·nums[k]·nums[r+1] + dp[l][k-1] + dp[k+1][r] )

Pad both ends with 1, then fill by increasing interval length. Answer is dp[1][n].

Why "last" not "first"? Choosing the first balloon leaves a messy, splitting recurrence. Choosing the last fixes its two multipliers, decoupling the left and right sub-ranges cleanly.

📈Visualization — DP table fills by interval length (press Play)

cell being computed dp[l][r] sub-problems it reads already solved
⏱ Time: O(n³)
💾 Space: O(n²)

23Burst Balloon — Zero-Aware Variant

DP Interval DPEdge-case ScoringHard

❓Problem

The Samsung/CareerCup wording: bursting a balloon scores the product of its left and right neighbours (left only / right only / itself at the boundaries), and balloons with value 0 are best removed first using their surrounding values. Maximise total points.

Input 6 1 0 2 3 0 4 Output 34

💡Key Idea

First, sweep out the zero balloons, crediting each one the product of its previous kept value and its next value. Then run an interval DP over the surviving balloons (padded with 1s): for a sub-range a burst scores nums[left]·nums[right], except for the very outer range where it scores the full triple product. Add the pre-counted zero points to the DP result.

This variant differs from #22 only in the scoring rule and the zero pre-pass. Recognising which scoring a statement intends is half the battle.
⏱ Time: O(n³)
💾 Space: O(n²)

24Marathon — Fastest Time Within Energy

DP Knapsack-styleTwo ConstraintsMedium

❓Problem

Run a marathon of D km with energy budget H. You may pick one of 5 paces for each km; a pace has a (time, energy) cost per km. Find the minimum total time to finish all D km without exceeding energy H. Output minutes and seconds.

Input (T; then D H; then 5 lines: min sec energy) 1 30 130 4 50 7 5 0 5 5 10 4 5 20 3 5 30 2 Output #1 153 20

💡Key Idea

Two quantities accumulate independently — kilometres done and energy spent — so DP over both. dp[k][e] = minimum time to have run k km using exactly e energy. From each state, try all 5 paces for the next km. Answer = min over e ≤ H of dp[D][e]. Convert seconds → min sec at the end.

Faster paces cost more energy: this is the classic "buy speed with a limited budget" trade-off — exactly a bounded knapsack where the count axis is kilometres.

📈Visualization

290
7e
300
5e
310
4e
320
3e
330
2e
5 paces: time/km (bar height, seconds) vs energy/km. Spend just enough energy on faster paces to minimise total time within budget H.
⏱ Time: O(D · H · 5)
💾 Space: O(D · H)

25Tree Cutting — Robot With a Stack

DP Memoised DPProcess by HeightHard

❓Problem

A robot starts at position 0 on a line 0…n and must cut every tree (positions 1…n−1, up to one on each side) and deliver them all to position n. Cutting any tree costs 1; moving distance d costs d. The carried stack must stay non-increasing in height bottom→top (you may only pick up a tree no taller than the one currently on top). Minimise total cost.

Input (T; then n; left[] ; right[]) 1 5 0 3 2 1 0 0 3 2 1 0 Output #1 11

💡Key Idea

The stack rule forces you to collect trees in decreasing height order (tallest at the bottom). So process heights from high to low. For a given height, all its trees sit between positions L (leftmost) and R (rightmost); the robot must sweep that whole span and end at one of the two ends before dropping to the next-lower height. Memoise on (currentHeight, robotPosition). Cutting cost (= total trees) is added naturally as you pass each level.

📈Visualization

012 34=n h3 h2 h1 robot
Pick up tallest (h3) first so the stack stays non-increasing. 6 cuts + 5 movement = total 11.
⏱ Time: O(maxH · n)
💾 Space: O(maxH · n)

26Aggressive Cows — Maximise Min Gap 📊

Binary Search Search on AnswerGreedy CheckMedium

❓Problem

Given stall positions on a line and c cows, place the cows so that the minimum distance between any two cows is as large as possible. Output that largest possible minimum distance.

Input (T; then n c; then n positions) 1 5 3 1 2 8 4 9 Output 3 (cows at 1, 4, 8/9 → min gap 3)

💡Key Idea

"Maximise the minimum" ⇒ binary search on the answer. Sort the positions. For a candidate gap x, greedily place cows left-to-right, dropping a cow whenever it's ≥ x away from the last placed one. If you can seat all c cows, x is feasible — try larger; otherwise try smaller. The feasibility is monotonic (works for x ⇒ works for all smaller x), which is exactly what binary search needs.

Signature of this pattern: the words "maximise the minimum" or "minimise the maximum" with a checkable condition almost always mean binary search the answer + greedy verify.

📈Visualization — binary search the gap (press Play)

placed cow empty stall candidate gap x
⏱ Time: O(n log(maxPos))
💾 Space: O(1)

27Sinkhole — Largest Square With ≤1 Hole

Binary Search 2D Prefix SumMonotonic CheckHard

❓Problem

On an N×M plot with K marked sinkholes, find the largest square sub-region containing at most one sinkhole, and report its corner coordinates.

Input (T; then N M; then K; then K sinkhole coordinates) Output #i topLeftX topLeftY bottomRightX bottomRightY

💡Key Idea

Build a 2-D prefix sum so the number of sinkholes inside any rectangle is an O(1) query. The side length is monotonic: if no square of side k has ≤1 hole, none of side k+1 does either (a bigger square can only contain more). So binary search the side length, and for each candidate scan all squares using the prefix sum.

count(i,j,k) = pre[i+k][j+k] − pre[i+k][j] − pre[i][j+k] + pre[i][j]

📈Visualization — inclusion–exclusion

k×k pre[i+k][j+k]
A rectangle's sinkhole count = big corner − two strips + the doubly-removed corner (inclusion–exclusion on the prefix table).
⏱ Time: O(N·M·log(min(N,M)))
💾 Space: O(N·M)

28Thirsty Crow — Minimum Stones (Worst Case)

Greedy SortingLevel FillingMedium

❓Problem

There are N pots; pot i overflows after Oᵢ stones. The crow wants K pots to overflow but doesn't know which pots are which. Compute the minimum number of stones needed to guarantee K overflows in the worst case.

Input (N; N overflow numbers; K) 2 5 58 1 Output 10 (5 into each pot → the "5" pot overflows)

💡Key Idea

Worst case = adversary reveals the hardest pots first, so the crow must fill all pots level by level. Sort overflow numbers ascending. Raising the water from one level to the next costs that height increment times the number of pots still in play. After K pots overflow, the rest can be ignored:

total = Σ (Oᵢ − Oᵢ₋₁) · (N − i), for i = 0 … K−1

📈Visualization

5
58
Fill both pots to level 5 (cost 5×2 = 10) → the smaller pot overflows. Sorting + incremental level fill gives the worst-case minimum.
⏱ Time: O(N log N)
💾 Space: O(1)

29Omnious Number — Digit Frequency Filter

Math Digit CountingBrute RangeEasy

❓Problem

In a range [a, b], count the "valid" numbers — those in which the given forbidden digits appear, in total, fewer than k times. (A product number is discarded if it contains the forbidden digits k or more times.)

Input (a b k; then n; then n forbidden digits) 24 12943 3 3 1 3 5 Output <count of valid numbers>

💡Key Idea

Ranges in these problems are small enough to iterate. For each number, peel off digits with % 10 and / 10, count how many are forbidden, and accept it if that total is below k. A boolean lookup table for the forbidden digits keeps the inner check O(1).

For huge ranges you'd switch to digit DP, but for Samsung-sized bounds the straight loop is the intended, bug-free answer.

📈Visualization

1 1 2 2 3 forbidden {1,3,5} appear 3× → discard (k=3)
11223 has forbidden digits 3 times → rejected. 11222 has them twice → accepted.
⏱ Time: O((b−a)·digits)
💾 Space: O(1)

30String Compression — Merge Letter Counts

Strings ParsingHash by LetterEasy

❓Problem

A compressed string is a run of letter,count pairs, e.g. a10b5a3. Merge repeated letters by summing their counts and print each present letter (a→z) with its total.

Input a10b5a3 Output a 13 b 5

💡Key Idea

Single linear scan. Read a letter, then read all the digits that follow it into a number, and add that to a size-26 bucket for that letter. Finally print the buckets in order. The only subtlety is correctly consuming a multi-digit count before the next letter.

📈Visualization

a10b5a3 → a=13b=5 bucket[a] += 10, bucket[b] += 5, bucket[a] += 3
⏱ Time: O(len)
💾 Space: O(26)

31Necklace — Balance Red & Blue Beads

Strings Prefix BalanceHashMapMedium

❓Problem

A necklace has 2n beads (R/B) with a knot exactly in the middle (between bead n and n+1); beads can't cross the knot. By removing beads from both ends, find the minimum removals so the remaining middle segment has equal R and B counts.

Input (T; then per test: n, then string) 3 2 RRRR Output #0 4

💡Key Idea

Map B→+1, R→−1 and take a running prefix balance. A segment has equal R and B exactly when its two endpoints share the same prefix balance. Store the first index of each balance in a hashmap; when the same balance reappears with the left end before the knot and the right end after it (so the kept segment straddles the knot), it's a valid balanced middle. Keep the longest; answer = 2n − longest.

"Equal counts of two symbols in a substring" → +1/−1 prefix sums + first-seen hashmap. This is the same engine behind "longest subarray with equal 0s and 1s".

📈Visualization

knot R B R B R B
Keep the longest balanced segment that spans the knot; remove the rest from both ends.
⏱ Time: O(n)
💾 Space: O(n)

32Sum at Level K — Parenthesised Tree

Trees String ParsingDepth TrackingMedium

❓Problem

A binary tree is encoded as nested parentheses, each node written as (value (leftSubtree)(rightSubtree)), values may be negative. Given a level K (root = level 0), output the sum of all node values at that level.

Input (K; then the tree string) 3 (0(5(6()())(-4()(9()())))(7(1()())(3()()))) Output <sum of values at depth 3>

💡Key Idea

No tree object needed — track the parenthesis depth while scanning. A value always appears right after its own opening bracket, so a value read at paren-depth d sits at tree level d − 1. Parse signed integers as you go and add the ones whose level equals K.

📈Visualization

0 5 7 6 1 3 L0 L1 L2
Depth in the bracket string maps directly to tree level. Level 2 here sums 6 + 1 + 3 (= 10), and so on.
⏱ Time: O(len)
💾 Space: O(1)

33Paper Cutting — Count Colour Pieces (Quadtree)

Divide & Conquer Quadtree RecursionMedium

❓Problem

An N×N sheet (N = 2ᵏ) is coloured with 0 (white) / 1 (blue). Cutting rule: if a square isn't a single colour, cut it into four equal quadrants and repeat on each; stop when a square is uniform. Count how many white and how many blue pieces result.

Input (T; then N; then N×N of 0/1) Output Case #i then whiteCount blueCount

💡Key Idea

Textbook quadtree divide & conquer. For a square, check if it's uniform; if yes it's one piece (tally its colour); if not, recurse into the 4 sub-squares of half the side. The recursion depth is log₂N.

Speed-up: a 2-D prefix sum turns the "is this square uniform?" test into O(1) (sum is 0 ⇒ all white, sum = area ⇒ all blue), dropping total work to O(N²).

📈Visualization

uniform → 1 piece mixed → split into 4 recurse until uniform
⏱ Time: O(N²·logN) naïve / O(N²) with prefix sums
💾 Space: O(N²)

34Wormhole — Min Distance (Floyd–Warshall)

Graph All-Pairs Shortest PathModellingMedium

❓Problem

Same task as problem 12 — get from source to destination using bidirectional wormholes — but solved by modelling it as a weighted graph instead of backtracking. Far cleaner when the number of wormholes grows.

Input (T; then N; sX sY tX tY; then N lines x1 y1 x2 y2 w) Output #t : minimum distance

💡Key Idea

Create 2N + 2 nodes: the source, the destination, and the two mouths of every wormhole. Between any two nodes the base cost is the Manhattan distance (you can always just walk); additionally the two mouths of each wormhole are joined by an edge of weight w (cheaper teleport). Run Floyd–Warshall for all-pairs shortest paths and read off cost[source][dest].

Backtracking (12) vs Floyd (34): identical answers. The DFS is fine for tiny N; the graph model is O((2N)³) but trivially correct and scales — knowing both is the lesson.

📈Visualization

S A1 B1 A2 B2 D solid = wormhole edge (w) · dashed = walk (Manhattan)
⏱ Time: O((2N+2)³)
💾 Space: O((2N+2)²)

35Convex Hull — Gift Wrapping

Geometry Jarvis MarchOrientation TestMedium

❓Problem

Given points in the plane, output the vertices of the smallest convex polygon enclosing them all (the convex hull). Print -1 if a polygon can't be formed (fewer than 3 hull vertices).

Input (T; then n; then n "x y" points) Output hull vertices, or -1

💡Key Idea

Jarvis March (gift wrapping): start at the leftmost point (definitely on the hull) and repeatedly pick the next point that is the most counter-clockwise relative to the current one — that's the point for which every other point lies to its left. Wrap around until you return to the start. The orientation of an ordered triple is found from the sign of a cross product (no floating point needed).

cross = (q.y−p.y)(r.x−q.x) − (q.x−p.x)(r.y−q.y)

📈Visualization

start (leftmost)
Green = hull vertices wrapped counter-clockwise; grey interior points are enclosed.
⏱ Time: O(n·h), h = hull size
💾 Space: O(n)