← paper-digest
Applied Scientist / Research Scientist · Coding Practice

從 AI / ML 工作主題
找到下一題練習

28 題演算法練習,依九類工作主題整理。優先開啟 NeetCode 解題,搭配 LeetCode 與既有繁中筆記;每類再接到直接的 ML 實作。

9 工作主題28 不重複 LC 題27 NeetCode 本題解題連結20 既有詳解 · 8 新解法查核 2026-09-08
查找結論:有接近的分類題庫,例如 ML Coding、TensorTonic、Deep-ML;這次未找到完全依這九類「工作主題」整理,且以 NeetCode / LeetCode 為主的完整清單。下方的題目對應是本頁依工作內容做的整理,並非平台官方分類,也不是公司考題頻率榜。

網路上,哪些題庫最接近?

以下依各平台公開頁面整理;題庫、學習路線與理論問答分開看。免費範圍、登入要求與內容供應以平台目前頁面為準。

資源實際分類/內容適合怎麼用
ML CodingRetrieval & Ranking、Metrics、Loss & Training、Data & Features、LLM Components、Debugging。與這份工作主題相當接近;可直接練 BM25、NDCG、Attention、KV cache 等元件。
TensorTonic · RoadmapLoss、Activation、NLP、Linear Algebra、Transformers、Metrics & Evaluation;題庫也有 Value Iteration 與 Q-learning。補模型訓練、RL 與數值實作;可跑測試,並有理論/解法分頁。
Deep-MLLinear Algebra、ML、Deep Learning、NLP、Computer Vision;另有 collections、labs 與 projects。依技術能力練 Python / ML 元件,適合補 NeetCode 題單以外的實作。
NeetCode Roadmap依演算法模式學習;官方 準備指南 也建議先掌握 patterns。本頁演算法題的主要解題入口;再由本頁補上「這題與工作有什麼關聯」。
Machine Learning 150以 ML 概念與面試問答為主;查核時多個章節標示 Under Construction。理論補充。不要把它當作 150 題可立即執行的 coding 題庫。

保留兩個分類角度

01
工作主題

這題服務什麼問題?例如 retrieval 的候選選取、production 的 cache,或 evaluation 的串流統計。

02
解題技術

這題怎麼解?例如 Heap、Binary Search、Graph、DP。一題可以跨工作主題,但只保留一份題目卡片。

03
直接 ML 實作

各主題末尾有延伸資源。Training、RL、Causal、Safety 的完整能力,需要直接做模型、估計流程或評估程式。

題數按主要主題計算,共 28 題;跨主題標籤不重複計數。
工作主題題數LC 覆蓋程度下一步
Retrieval / Ranking / Recommendation5直接基礎較多先練 Top K Frequent Elements → K Closest → Search Suggestions,再比較 Words 的 tie-break 與多路合併。
NLP / LLM Applications5字串處理基礎Encode/Decode → Word Break → Edit Distance;頻率三題可一起複習。
Agentic Workflows / Planning3依賴與搜尋基礎Course Schedule II → Combination Sum → Network Delay Time;再回看 LRU / TimeMap 的狀態管理。
Model Training / Adaptation2LC 僅涵蓋周邊元件Random Pick with Weight → RandomizedSet;若面試要求 ML coding,優先接續 training step。
Reinforcement Learning / Decision Making2DP 類比;需直接練 RL先能說明 DP 的 state/action/transition,再直接做 Value Iteration 與 Q-learning update。
Evaluation / Experimentation / Causal Inference3統計聚合基礎Range Sum → Median → Sliding Window Maximum;ASR / OCR 指標再看 Edit Distance。
Production ML Systems / Efficiency3系統元件直接基礎LRU Cache → TimeMap → Task Scheduler;再用 Median / Sliding Window 練監控資料處理。
Multimodal / Computer Vision / Speech3網格與序列基礎Flood Fill → Number of Islands → Rotate Image;語音評估看 Edit Distance,跨模態檢索看 K Closest。
Safety / Robustness / Interpretability2LC 僅弱相關Valid Parentheses 可作為暖身;Regex 是選做。主要準備分群錯誤分析、對抗擾動與 attribution。
例子:Search Suggestions System 的工作主題是 Retrieval / Ranking,這份解法的技術是 Sorting + Binary Search;換成 Trie 解法時,工作主題不變。題目本身要求字典序建議,個人化排名則是後續延伸。

找一題開始

題目卡預設按主要主題排列;篩選會包含跨主題標籤。NeetCode 連到解題頁;已有的繁中說明可直接跳轉。16 題標為「起步題」,是本頁建議的學習起點。

顯示 28 / 28 題
直接基礎較多

Retrieval / Ranking / Recommendation

01

先把候選找出來,再依分數排序與選取。Top-K、prefix lookup 和多路合併都有清楚的演算法對應;個人化、learning to rank 與 offline metrics 仍需另外實作。

LC 347 · 01 / 28

Top K Frequent Elements

Medium起步題已有詳解

工作主題Retrieval / Ranking · NLP / LLM

解題技術Hash Map · Bucket Sort

頻率排名的直接基礎;熱門 item / query 統計。

題目、例子與複習提示

題目整理

回傳陣列中出現次數最多的 k 個不同數字,結果順序不限。

nums=[4,4,1,1,1,9], k=2 → [1,4]

解法說明

先計數,再依頻率分桶,由高到低收集 k 個元素。

Time
O(n)
Space
O(n)

n 為輸入元素數。

繼續閱讀 Python 解法與既有繁中說明 →

Frequency 家族:Elements 選數字、Words 加字典序 tie-break、Characters 重建全部字元。
LC 692 · 02 / 28

Top K Frequent Words

Medium起步題已有詳解

可先複習 NeetCode:Top K Frequent Elements(相關題),再到本題既有詳解補字典序 tie-break。

工作主題Retrieval / Ranking · NLP / LLM

解題技術Hash Map · Sorting

詞頻榜加上穩定的字典序 tie-break。

題目、例子與複習提示

題目整理

回傳頻率最高的 k 個字,先按頻率降序,再按字典序升序。

words=["ml","ai","ml","ai","data"], k=2 → ["ai","ml"]

解法說明

用 (-frequency, word) 排序;平手規則是本題與 Elements 的主要差異。

Time
O(C + u log u · L)
Space
O(u)

C 為所有輸入字元數,u 為不同單字數,L 為最長單字長度;字串比較最壞 O(L)。

繼續閱讀 Python 解法與既有繁中說明 →

Frequency 家族:Elements 選數字、Words 加字典序 tie-break、Characters 重建全部字元。
LC 973 · 03 / 28

K Closest Points to Origin

Medium起步題已有詳解

工作主題Retrieval / Ranking · Multimodal / CV / Speech

解題技術Heap

練習依距離保留候選;二維原點距離是簡化模型,並非 ANN 索引。

題目、例子與複習提示

題目整理

回傳離原點最近的 k 個二維點,順序不限。

points=[[3,0],[1,1],[-1,0]], k=2 → [[-1,0],[1,1]]

解法說明

維持最多 k 個點的 max-heap;平方距離即可比較遠近。

Time
O(n log(k+1))
Space
O(k)

n 為點數。

繼續閱讀 Python 解法與既有繁中說明 →

LC 1268 · 04 / 28

Search Suggestions System

Medium起步題已有詳解

工作主題Retrieval / Ranking · NLP / LLM

解題技術Sorting · Binary Search

直接對應 prefix autocomplete;排序規則是字典序,並非個人化分數。

題目、例子與複習提示

題目整理

每輸入一個字元,輸出最多三個符合當前 prefix、字典序最小的商品名。

products=["car","cat","cup"], searchWord="ca" → [["car","cat","cup"],["car","cat"]]

解法說明

排序後,對各 prefix 用 lower_bound 找起點,只檢查接下來最多三個商品。

Time
O(nL log(n+1) + m² log(n+1))
Space
O(n + m)

n 為商品數,L 為最長商品名,m 為查詢長度;計入 Python 排序空間與 prefix 字串,結果僅存字串參照。

繼續閱讀 Python 解法與既有繁中說明 →

LC 23 · 05 / 28

Merge k Sorted Lists

Hard已有詳解

工作主題Retrieval / Ranking · Production / Efficiency

解題技術Heap · Linked List

多路有序結果合併;可類比合併各 shard 的排序結果。

題目、例子與複習提示

題目整理

把 k 條已排序 linked lists 合成一條排序串列。

lists=[[1,4],[2,3],[0,5]] → [0,1,2,3,4,5]

解法說明

Heap 只保存每條串列尚未輸出的最小節點;取出後補入該串列下一個。

Time
O(N log(k+1))
Space
O(k)

N 為總節點數,k 為串列數;額外空間不含輸出。

繼續閱讀 Python 解法與既有繁中說明 →

字串處理基礎

NLP / LLM Applications

02

字串題能練資料表示、解析與切分。Word Break 是字典切詞,Edit Distance 是字元編輯成本;兩者都能幫助理解 NLP 管線,但不涵蓋語意建模或 RAG 品質。

LC 49 · 06 / 28

Group Anagrams

Medium已有詳解

工作主題NLP / LLM · Training / Adaptation

解題技術Hash Map

練習以特徵 signature 分組;anagram 不表示語意相同,不能直接當語意去重。

題目、例子與複習提示

題目整理

把字母種類與次數完全相同的單字分為同組。

["tea","eat","tan"] → [["tea","eat"],["tan"]]

解法說明

小寫英文可用 26 維頻率 tuple 當 key,避免反覆比較字串。

Time
O(C + n)
Space
O(n)

C 為總字元數,n 為單字數;字母表固定 26,輸出持有原字串參照。

繼續閱讀 Python 解法與既有繁中說明 →

LC 271 · 07 / 28

Encode and Decode Strings

Medium起步題已有詳解

工作主題NLP / LLM · Agents / Planning · Production / Efficiency

解題技術String Parsing · Design

練習可靠的文字序列化;內容含分隔符也必須可還原。

題目、例子與複習提示

題目整理

設計字串清單與單一字串之間可無損往返的 encode / decode。

["a#b",""] → "3#a#b0#" → ["a#b",""]

解法說明

為每段寫入長度前綴;decode 讀完長度後,精確消耗該長度的內容。

Time
O(C + n)
Space
O(C + n)

C 為總字元數,n 為字串數;包含輸出與空字串的記錄成本。

繼續閱讀 Python 解法與既有繁中說明 →

LC 139 · 08 / 28

Word Break

Medium起步題已有詳解

工作主題NLP / LLM

解題技術Dynamic Programming

字典切詞的簡化模型;LLM 的 BPE 有不同的合併規則。

題目、例子與複習提示

題目整理

判斷字串能否完全拆成字典中的單字,字典中的字可重複使用。

s="aiml", dict=["ai","ml"] → true

解法說明

dp[i] 表示前 i 個字元可切分;從可達位置嘗試匹配字典單字。

Time
O(n · d · L)
Space
O(n)

n 為字串長度,d 為字典大小,L 為最長單字;以逐詞 startswith 版本為準,不含輸入。

繼續閱讀 Python 解法與既有繁中說明 →

LC 72 · 09 / 28

Edit Distance

Medium起步題

工作主題NLP / LLM · Evaluation / Causal · Multimodal / CV / Speech

解題技術Dynamic Programming

可延伸到 ASR 的 WER、OCR 的 CER;這題先處理字元級編輯次數。

題目、Python 解法與面試講解

題目整理

用插入、刪除、替換,把 word1 變成 word2,回傳最少操作數。

word1="cat", word2="cut" → 1

解法說明

每個 prefix pair 的最佳答案只依賴插入、刪除、替換的較短 prefix;相同字元不需付費。

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        previous = list(range(len(word2) + 1))
        for i, ch1 in enumerate(word1, 1):
            current = [i]
            for j, ch2 in enumerate(word2, 1):
                if ch1 == ch2:
                    current.append(previous[j - 1])
                else:
                    current.append(1 + min(
                        previous[j],      # Delete from word1.
                        current[j - 1],   # Insert into word1.
                        previous[j - 1],  # Replace.
                    ))
            previous = current
        return previous[-1]
Time
O(mn)
Space
O(n)

m、n 為兩字串長度;只保留上一列與目前列。

Interview Explanation Flow

  1. I would confirm that each insertion, deletion, or substitution costs one, and that we need the count rather than the edit sequence.
  2. I define dp[i][j] as the distance between two prefixes. Matching characters keep the diagonal cost; otherwise I add one to the cheapest neighboring state.
  3. As I code, the first row and first column handle empty prefixes. Each row only needs its predecessor, so I keep two rows.
  4. Time is O(mn), space is O(n). I would test two empty strings, one empty string, and identical strings. To return the edits, I would retain predecessor information.
"cat" → "cut": replace a with u → 1
"" → "abc": insert a, b, c → 3

中文:先定義兩個 prefix 的距離,再解釋三種操作各自對應哪個相鄰狀態。

LC 451 · 10 / 28

Sort Characters By Frequency

Medium已有詳解

工作主題NLP / LLM · Retrieval / Ranking

解題技術Hash Map · Sorting

與兩題 Top K 同屬 frequency counting;本題要輸出全部字元。

題目、例子與複習提示

題目整理

依出現次數由多至少重排全部字元;同頻率的字元順序不限。

s="tree" → "eetr"("eert" 也合法)

解法說明

先計數,再按頻率排序不同字元,按次數重複寫回。

Time
O(n + u log u)
Space
O(n + u)

n 為字串長度,u 為不同字元數;計入輸出與暫存字串。

繼續閱讀 Python 解法與既有繁中說明 →

Frequency 家族:Elements 選數字、Words 加字典序 tie-break、Characters 重建全部字元。
依賴與搜尋基礎

Agentic Workflows / Planning

03

固定 workflow 可先用 graph 表示:依賴是否可完成、執行順序是否合法、搜尋成本是多少。真正 agent 的工具回傳、重試、動態規劃與記憶要再用小型系統練習。

LC 210 · 11 / 28

Course Schedule II

Medium起步題已有詳解

工作主題Agents / Planning · Production / Efficiency

解題技術Graph · Topological Sort

固定依賴的 workflow 排序;真實 agent 還需處理動態任務和失敗。

題目、例子與複習提示

題目整理

給先修依賴,輸出可完成全部課程的順序;有 cycle 則回傳空清單。

numCourses=3, prerequisites=[[1,0],[2,1]] → [0,1,2]

解法說明

Kahn:只執行入度為 0 的節點,完成後解除後續依賴;輸出不足代表 cycle。

Time
O(V + E)
Space
O(V + E)

V 為課程數,E 為依賴數。

繼續閱讀 Python 解法與既有繁中說明 →

LC 743 · 12 / 28

Network Delay Time

Medium

工作主題Agents / Planning · Production / Efficiency

解題技術Graph · Heap

練習帶成本的 graph search;本題求所有節點收到訊號的最晚時間。

題目、Python 解法與面試講解

題目整理

有非負邊權的有向圖,從 k 發送訊號,回傳所有節點收到的最短所需時間;有人不可達則 -1。

times=[[1,2,2],[2,3,1],[1,3,5]], n=3, k=1 → 3

解法說明

Dijkstra 每次確認最小暫定距離;答案是所有最短距離的最大值。

from heapq import heappop, heappush


class Solution:
    def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:
        graph = [[] for _ in range(n + 1)]
        for source, target, weight in times:
            graph[source].append((target, weight))

        distance = [float("inf")] * (n + 1)
        distance[k] = 0
        heap = [(0, k)]
        while heap:
            cost, node = heappop(heap)
            if cost != distance[node]:
                continue  # Ignore a superseded candidate.
            for neighbor, weight in graph[node]:
                candidate = cost + weight
                if candidate < distance[neighbor]:
                    distance[neighbor] = candidate
                    heappush(heap, (candidate, neighbor))

        answer = max(distance[1:])
        return -1 if answer == float("inf") else answer
Time
O((V + E) log(V + E + 1))
Space
O(V + E)

以允許 heap 保留過期候選的實作為準。

Interview Explanation Flow

  1. I would confirm directed edges and nonnegative weights. We need the largest shortest-path distance from the source, not the sum of edge costs.
  2. I use Dijkstra: the heap exposes the smallest tentative distance, and relaxing an edge can improve a neighbor's distance.
  3. As I code, I discard outdated heap entries and push a new candidate only on strict improvement. This also avoids looping on zero-cost cycles.
  4. With lazy heap entries, the bound is O((V+E) log(V+E+1)) time and O(V+E) space. I would test a disconnected node, a zero-weight edge, and n=1.
1 → 2 costs 2; 2 → 3 costs 1; 1 → 3 costs 5
After node 1: distances = [0,2,5]
After node 2: distances = [0,2,3]
Return max = 3; the heap's old (5,3) entry is ignored.

中文:區分每個節點的最短到達時間與所有節點都收到訊號的時間。

LC 39 · 13 / 28

Combination Sum

Medium

工作主題Agents / Planning

解題技術Backtracking

練習候選探索、限制檢查與撤銷選擇;用作 planning 的搜尋基礎。

題目、Python 解法與面試講解

題目整理

從不同正整數中選數,可重複使用,列出總和等於 target 的不同組合;順序不產生新組合。

candidates=[2,3], target=6 → [[2,2,2],[3,3]]

解法說明

固定候選 index 的非遞減順序來避免排列重複;剩餘總和不足就剪枝。

class Solution:
    def combinationSum(self, candidates: list[int], target: int) -> list[list[int]]:
        candidates.sort()
        result = []
        path = []

        def search(start: int, remaining: int) -> None:
            if remaining == 0:
                result.append(path.copy())
                return
            for index in range(start, len(candidates)):
                value = candidates[index]
                if value > remaining:
                    break
                path.append(value)
                search(index, remaining - value)
                path.pop()  # Undo this choice before exploring another.

        search(0, target)
        return result
Time
O(c log c + c^(D+1) · D) 保守上界
Space
O(D + R·D)

c 為候選數,D=⌊target/min(candidates)⌋,R 為結果數;包含輸出,排除輸出為 O(D)。

Interview Explanation Flow

  1. I would confirm positive, distinct candidates, unlimited reuse, and that order within a combination does not matter.
  2. I search only in nondecreasing candidate order. Reusing the same index allows repetition, while never moving backward prevents permutation duplicates.
  3. As I code, I append a choice, explore, and pop it. I copy the path when the remaining target reaches zero; sorted values let me stop early.
  4. The search is exponential and output-sensitive. With c candidates and depth D, O(c^(D+1) D) is a conservative bound, plus sorting. Extra search space is O(D), and R results take up to O(RD) space.
[2,3], target=6
choose 2 → 2 → 2: remaining 0 → save [2,2,2]
undo choices; choose 3 → 3 → save [3,3]
No [3,2,...] branch: indices never move backward.

中文:把「選擇、探索、撤銷」說清楚,也要解釋如何避免重複組合。

LC 僅涵蓋周邊元件

Model Training / Adaptation

04

加權抽樣、資料池與分組是訓練管線的周邊能力。模型架構、loss、gradient、optimizer、fine-tuning 與蒸餾,應以 NumPy / PyTorch 實作為主要補強。

LC 528 · 14 / 28

Random Pick with Weight

Medium起步題已有詳解

工作主題Training / Adaptation · RL / Decisions

解題技術Prefix Sum · Binary Search · Randomized

訓練資料加權抽樣的基礎;固定權重抽樣本身不會學習 bandit policy。

題目、例子與複習提示

題目整理

每次回傳一個 index,使機率等於該位置權重除以總權重。

w=[1,3] → index 0 機率 1/4,index 1 機率 3/4(單次結果不固定)

解法說明

把權重變成累積區間;均勻抽取票號,再二分找到所屬區間。

Time
初始化 O(n);每次抽樣 O(log n)
Space
O(n)

n 為權重數;這是有放回抽樣。

繼續閱讀 Python 解法與既有繁中說明 →

LC 380 · 15 / 28

Insert Delete GetRandom O(1)

Medium

工作主題Training / Adaptation · RL / Decisions · Production / Efficiency

解題技術Hash Map · Design · Randomized

可類比需要增刪與均勻抽樣的資料池;它是 set,不保留重複 transition。

題目、Python 解法與面試講解

題目整理

設計集合,支援插入、刪除與等機率隨機取值,平均每個操作 O(1)。

insert(8) → true; insert(5) → true; remove(8) → true; getRandom() → 5

解法說明

陣列提供隨機索引,map 記錄位置;刪除時以最後一個元素補洞並更新索引。

from random import choice


class RandomizedSet:
    def __init__(self):
        self.values = []
        self.positions = {}

    def insert(self, val: int) -> bool:
        if val in self.positions:
            return False
        self.positions[val] = len(self.values)
        self.values.append(val)
        return True

    def remove(self, val: int) -> bool:
        if val not in self.positions:
            return False
        index = self.positions[val]
        last = self.values[-1]
        self.values[index] = last
        self.positions[last] = index
        self.values.pop()
        del self.positions[val]
        return True

    def getRandom(self) -> int:
        return choice(self.values)
Time
平均 O(1)/操作
Space
O(n)

n 為目前集合大小;getRandom 僅在非空集合呼叫。

Interview Explanation Flow

  1. I would confirm set semantics and that getRandom is called only when the set is nonempty.
  2. A list gives uniform random indexing, while a hash map finds an element's position. Their invariant is positions[values[i]] = i.
  3. For deletion, I move the last element into the removed slot and update its index before deleting the old key. This also works when the removed element is already last.
  4. Each operation is O(1) on average, with O(n) space. I would test duplicate insertion, missing deletion, deleting the last element, and deleting the only element.
values=[8,5,9], positions={8:0,5:1,9:2}
remove(5): put 9 in slot 1, update positions[9], pop last
values=[8,9], positions={8:0,9:1}

中文:用最後一個元素補洞,避免陣列刪除造成整段搬移。

DP 類比;需直接練 RL

Reinforcement Learning / Decision Making

05

House Robber 與 Minimum Path Sum 練的是已知規則下的最佳子結構。RL 還要從互動資料學習,處理未知結果、探索/利用、reward 與 credit assignment。

LC 198 · 16 / 28

House Robber

Medium起步題已有詳解

工作主題RL / Decisions

解題技術Dynamic Programming

練習 state、action、累積 reward 的定義;這是已知資料的 DP,不是 RL 訓練。

題目、例子與複習提示

題目整理

從非負數列中選取互不相鄰的元素,求最大總和。

nums=[2,7,9,3,1] → 12(2+9+1)

解法說明

每一步比較跳過目前值,或取目前值加上前兩格最佳值。

Time
O(n)
Space
O(1)

n 為元素數。

繼續閱讀 Python 解法與既有繁中說明 →

LC 64 · 17 / 28

Minimum Path Sum

Medium已有詳解

工作主題RL / Decisions · Agents / Planning

解題技術Dynamic Programming

練習已知 transition 與 cost 的最佳決策;延伸才是 MDP / value iteration。

題目、例子與複習提示

題目整理

從非負 grid 左上到右下,每次向右或向下,回傳沿途最小總和。

grid=[[1,3],[2,1]] → 4

解法說明

目前格子的最小成本 = 自身成本 + min(上方最佳, 左方最佳)。

Time
O(r·c)
Space
O(c)

r、c 為列、欄數;選擇不修改輸入的一維 DP 版本。

繼續閱讀 Python 解法與既有繁中說明 →

統計聚合基礎

Evaluation / Experimentation / Causal Inference

06

Prefix Sum、Median 與 Sliding Window Maximum 是統計資料處理基礎;A/B testing、confidence intervals、因果識別與 ablation 的設計不能用它們替代。

LC 303 · 18 / 28

Range Sum Query - Immutable

Easy起步題已有詳解

工作主題Evaluation / Causal · Production / Efficiency

解題技術Prefix Sum

固定資料的區間聚合基礎;不涉及顯著性或因果效果。

題目、例子與複習提示

題目整理

初始化不可變陣列後,多次查詢閉區間 [left,right] 的元素總和。

nums=[2,4,6]; sumRange(1,2) → 10

解法說明

prefix[i] 代表前 i 項總和,用 prefix[right+1] - prefix[left] 回答查詢。

Time
初始化 O(n);查詢 O(1)
Space
O(n)

n 為元素數。

繼續閱讀 Python 解法與既有繁中說明 →

LC 295 · 19 / 28

Find Median from Data Stream

Hard已有詳解

工作主題Evaluation / Causal · Production / Efficiency

解題技術Heap · Design

線上統計摘要;本題維持精確 median,需要保留所有值。

題目、例子與複習提示

題目整理

支援新增數值與查詢目前全部數值的中位數。

addNum(2), addNum(8) → median 5;再 addNum(3) → median 3

解法說明

兩個 heap 分別保留較小半與較大半,維持順序與大小平衡。

Time
加入 O(log n);查詢 O(1)
Space
O(n)

n 為已加入數量;與近似 quantile sketch 不同。

繼續閱讀 Python 解法與既有繁中說明 →

LC 239 · 20 / 28

Sliding Window Maximum

Hard

工作主題Evaluation / Causal · Production / Efficiency

解題技術Sliding Window · Monotonic Queue

時間窗極值、監控尖峰的基礎;最大值不是 p95/p99。

題目、Python 解法與面試講解

題目整理

固定長度 k 的窗口依序向右滑動,回傳每個窗口的最大值。

nums=[1,3,-1,2], k=2 → [3,3,2]

解法說明

Deque 存 index 並保持對應值遞減;更晚且更大的元素會淘汰較早的小值。

from collections import deque


class Solution:
    def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:
        candidates = deque()
        answer = []
        for right, value in enumerate(nums):
            while candidates and candidates[0] <= right - k:
                candidates.popleft()
            while candidates and nums[candidates[-1]] <= value:
                candidates.pop()
            candidates.append(right)
            if right >= k - 1:
                answer.append(nums[candidates[0]])
        return answer
Time
O(n)
Space
O(k) 額外;輸出 O(n-k+1)

n 為陣列長度;每個 index 最多進出 deque 一次。

Interview Explanation Flow

  1. I would confirm that k is between one and the array length. Repeatedly scanning each window would cost O(nk).
  2. An older element no larger than a newer one can never become the maximum again: the newer element is larger and expires later.
  3. As I code, the deque stores indices. I remove expired entries at the front, dominated entries at the back, and read the answer from the front once a full window exists.
  4. Each index is appended once and removed at most once, giving O(n) time and O(k) extra space. I would test k=1, k=n, decreasing values, and equal values.
nums=[1,3,-1,2], k=2
r=0: deque values [1]
r=1: 3 removes 1 → [3] → output 3
r=2: [3,-1] → output 3
r=3: expire 3; 2 removes -1 → [2] → output 2

中文:淘汰較舊又較小的元素是正確性核心,index 則負責判斷過期。

系統元件直接基礎

Production ML Systems / Efficiency

07

快取、版本查詢、排程與串流聚合是很實用的 coding 題型。延伸到 ML serving 時,還要測 batch shape、記憶體與 latency,並區分 cache policy 和模型張量快取。

LC 146 · 21 / 28

LRU Cache

Medium起步題已有詳解

工作主題Production / Efficiency · Agents / Planning

解題技術Hash Map · Linked List · Design

有容量上限的查詢結果快取;LRU 淘汰政策和 transformer KV cache 是不同概念。

題目、例子與複習提示

題目整理

支援 get / put;容量滿時淘汰最久未使用項目,各操作平均 O(1)。

capacity=2; put(1,10), put(2,20), get(1), put(3,30) → key 2 被淘汰

解法說明

Hash map 找 node,doubly linked list 維持新舊次序;讀寫後都移到最新端。

Time
平均 O(1)/操作
Space
O(capacity)

需維護 map 與串列一致性;更新舊 key 不應增加項目數。

繼續閱讀 Python 解法與既有繁中說明 →

LC 981 · 22 / 28

Time Based Key-Value Store

Medium起步題已有詳解

工作主題Production / Efficiency · Evaluation / Causal · Agents / Planning

解題技術Hash Map · Binary Search · Design

版本查詢與 point-in-time lookup 基礎;資料可用時間仍需另行建模。

題目、例子與複習提示

題目整理

保存 key 的多個時間版本,查詢不晚於給定時間的最新值,沒有則回傳空字串。

set("x","old",2), set("x","new",5); get("x",4) → "old"

解法說明

每個 key 的版本按時間 append;二分找最後一個 timestamp ≤ query 的版本。

Time
set 均攤 O(1);get O(log v)
Space
O(N)

v 為該 key 的版本數,N 為總寫入數;前提是寫入時間遞增。

繼續閱讀 Python 解法與既有繁中說明 →

LC 621 · 23 / 28

Task Scheduler

Medium起步題已有詳解

工作主題Production / Efficiency · Agents / Planning

解題技術Greedy · Hash Map

冷卻限制下的排程;是 rate-limit / throughput 思考的簡化模型。

題目、例子與複習提示

題目整理

同字母任務之間需至少隔 n 個時間單位,任務各花一單位,求含 idle 的最短完成時間。

tasks=["A","A","B"], n=2 → 4(A,B,idle,A)

解法說明

最高頻率 f 決定 (f-1)(n+1)+t 的框架,t 是同最高頻種類數;與任務總數取 max。

Time
O(T)
Space
O(1)

T 為任務數;題目字母種類固定 26。

繼續閱讀 Python 解法與既有繁中說明 →

網格與序列基礎

Multimodal / Computer Vision / Speech

08

影像部分先練座標、矩陣與連通區塊;speech 可以用 Edit Distance 延伸到 WER / CER。跨模態對齊、特徵抽取與生成模型需要另行練習。

LC 733 · 24 / 28

Flood Fill

Easy起步題已有詳解

工作主題Multimodal / CV / Speech

解題技術Graph

像素連通區域操作;是 image processing 基礎,不是訓練 segmentation model。

題目、例子與複習提示

題目整理

由起點把四方向連通、與起點原色相同的區域全部改色。

image=[[1,1],[1,0]], sr=0, sc=0, color=2 → [[2,2],[2,0]]

解法說明

BFS 入隊時改色當作 visited;原色等於新色時直接結束。

Time
O(r·c)
Space
O(r·c)

r、c 為影像尺寸;BFS queue 最壞可佔相同量級。

繼續閱讀 Python 解法與既有繁中說明 →

LC 200 · 25 / 28

Number of Islands

Medium

工作主題Multimodal / CV / Speech

解題技術Graph

二值 mask 的 connected-component 計數基礎。

題目、Python 解法與面試講解

題目整理

在字元 '1' / '0' 的網格中,計算四方向相連的陸地群數。

grid=[["1","0"],["0","1"]] → 2

解法說明

掃到未訪問陸地就建立一座島,再用 BFS 標記整個連通塊。

from collections import deque


class Solution:
    def numIslands(self, grid: list[list[str]]) -> int:
        if not grid or not grid[0]:
            return 0
        rows, cols = len(grid), len(grid[0])
        seen = set()
        count = 0
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] != "1" or (r, c) in seen:
                    continue
                count += 1
                seen.add((r, c))
                queue = deque([(r, c)])
                while queue:
                    x, y = queue.popleft()
                    for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                        nx, ny = x + dx, y + dy
                        if (0 <= nx < rows and 0 <= ny < cols
                                and grid[nx][ny] == "1"
                                and (nx, ny) not in seen):
                            seen.add((nx, ny))
                            queue.append((nx, ny))
        return count
Time
O(r·c)
Space
O(r·c)

r、c 為網格尺寸;這份解法以 seen 保存訪問記錄,保留輸入。

Interview Explanation Flow

  1. I would confirm that connectivity is only horizontal and vertical, and that the grid contains string values.
  2. Every previously unseen land cell starts a new connected component. BFS marks all cells belonging to that island.
  3. I mark cells when enqueuing them, so two neighbors cannot enqueue the same cell twice. A separate seen set preserves the input.
  4. Time and space are O(rows times columns). I would test all water, all land, and diagonal land cells, which must count as separate islands.
grid=[["1","0"],["0","1"]]
Start at (0,0): island 1, no adjacent land
Start at (1,1): island 2 → return 2

中文:每次從未走過的陸地啟動 BFS,就找到一個新的連通區塊。

LC 48 · 26 / 28

Rotate Image

Medium

工作主題Multimodal / CV / Speech

解題技術Matrix

影像幾何操作的基礎;檢查座標映射與 in-place 約束。

題目、Python 解法與面試講解

題目整理

將 n×n 矩陣原地順時針旋轉 90 度。

matrix=[[1,2],[3,4]] → [[3,1],[4,2]]

解法說明

先轉置,再反轉每列;對應 (r,c) → (c,n-1-r)。

class Solution:
    def rotate(self, matrix: list[list[int]]) -> None:
        n = len(matrix)
        for r in range(n):
            for c in range(r + 1, n):
                matrix[r][c], matrix[c][r] = matrix[c][r], matrix[r][c]
        for row in matrix:
            row.reverse()
Time
O(n²)
Space
O(1)

n 為正方形邊長;使用交換,不建立新矩陣。

Interview Explanation Flow

  1. I would confirm a square matrix, clockwise rotation, and the requirement to modify the original matrix without allocating another one.
  2. The coordinate map is (r,c) to (c,n-1-r). A transpose followed by reversing every row implements that map.
  3. While transposing, I visit only the upper triangle so each pair swaps once. Then I reverse each row in place.
  4. Time is O(n squared) and extra space is O(1). I would test a one-cell matrix and a two-by-two matrix. A rectangular matrix needs different handling.
[[1,2],[3,4]]
transpose → [[1,3],[2,4]]
reverse rows → [[3,1],[4,2]]

中文:先用座標映射說明正確性,再拆成轉置與反轉每列。

LC 僅弱相關

Safety / Robustness / Interpretability

09

括號與 regex 題只練結構/格式驗證。它們無法評估 hallucination、fairness、adversarial robustness 或 interpretability;這類職缺應提高下方直接實作的優先度。

LC 20 · 27 / 28

Valid Parentheses

Easy起步題

工作主題Safety / Interpretability · NLP / LLM

解題技術Stack

只練結構合法性檢查;括號正確不能證明輸出安全或事實正確。

題目、Python 解法與面試講解

題目整理

判斷只含 ()[]{} 的字串,括號類型與巢狀配對順序是否正確。

"([])" → true;"([)]" → false

解法說明

Stack 記錄尚未關閉的左括號;每個右括號必須匹配最後開啟的括號。

class Solution:
    def isValid(self, s: str) -> bool:
        matching = {")": "(", "]": "[", "}": "{"}
        stack = []
        for char in s:
            if char in matching:
                if not stack or stack.pop() != matching[char]:
                    return False
            else:
                stack.append(char)
        return not stack
Time
O(n)
Space
O(n)

n 為字串長度。

Interview Explanation Flow

  1. I would confirm the input contains only the six bracket characters. Equal opening and closing counts alone do not prove validity.
  2. A stack represents the openings still waiting to close. Each closing bracket must match the most recently opened one.
  3. I check for an empty stack before popping, and require the stack to be empty at the end.
  4. The scan takes O(n) time and O(n) space. I would test a leading closing bracket, unmatched openings, and cross-nested brackets.
"([])": push (, push [, match ], match ) → true
"([)]": ) does not match the top [ → false

中文:配對需要最後開、最先關,因此使用 stack,而不是只計數。

LC 10 · 28 / 28

Regular Expression Matching

Hard已有詳解

工作主題Safety / Interpretability · NLP / LLM

解題技術Dynamic Programming · String Parsing

有限格式規則的匹配;regex 不是 prompt-injection 或幻覺防線。

題目、例子與複習提示

題目整理

判斷字串是否整段符合 pattern:'.' 代表任一字元,'*' 使前一元素重複零次以上。

s="aab", p="c*a*b" → true

解法說明

Memoized DP(i,j):遇 x* 可跳過該組,或匹配一個字元後繼續留在同組。

Time
O(mn)
Space
O(mn)

m、n 為字串與 pattern 長度;需記憶化避免重複子問題。

繼續閱讀 Python 解法與既有繁中說明 →

依面試內容安排練習

若是一般 coding round,先做起步題並計時;若明確要求 NumPy / PyTorch / ML coding,從相應主題的直接實作開始。Applied / Research Scientist 的實際面試內容以該團隊提供的資訊為準。

  1. Retrieval / LLM 應用:Top K → Search Suggestions → Word Break → Edit Distance,再做 BM25、NDCG、BPE 或 Attention。
  2. Agent / Production:Course Schedule II → LRU → TimeMap → Task Scheduler,再做 mock workflow 與 batching。
  3. Training / RL:加權抽樣 → DP 狀態,再做 training step、Value Iteration 與 Q-learning update。
  4. Evaluation / Safety / Multimodal:選一題對應的演算法暖身,再直接實作分群 metrics、paired bootstrap、對抗評估、影像/語音資料處理。
每題的面試練習流程:確認輸入/輸出 → 手走小例子 → 說明資料結構與 invariant → 分析 complexity → 邊寫邊講 → 檢查邊界。完成 coding 後,再用一句話說明它對工作主題的用途與限制。

題目描述與延伸練習皆為原創摘要/整理。8 題新解法放在可展開區塊中;20 題重複內容連回既有 HTML。新解法採 Python 3;LeetCode 271 的題面需要 Premium,可先閱讀 NeetCode 對應頁。