OAmaster
— / 2已做

You are given a list of module names and a list of dependency pairs. Each dependency [a, b] means module a depends on module b, so b must be compiled before a. Return one valid compilation order that includes every module exactly once. If multiple modules are currently available to compile, choose the lexicographically smallest available module first so the result is deterministic. If the dependency graph contains a cycle, return a single-element array ["IMPOSSIBLE"]. Function Description Complete the function compilationOrder in the editor below. compilationOrder has the following parameters:

  • String[] modules: all module names
  • String[][] dependencies: dependency pairs [module, prerequisite] Returns String[]: a valid compilation order, or ["IMPOSSIBLE"] if the dependencies contain a cycle.

Constraints

  • 1 ≤ modules.length ≤ 2 * 10⁵
  • 0 ≤ dependencies.length ≤ 2 * 10⁵
  • All module names are distinct.

解法

Kahn 拓扑排序 + 字典序最小堆:把 b -> a 视为边。计算入度,将入度为 0 的模块放入最小堆,每次取出最小名字、加入答案,删边、入度归零的入堆。若最终未覆盖所有模块说明有环,返回 ["IMPOSSIBLE"]。时间 O((V+E) log V)。

import heapq
from collections import defaultdict
from typing import List

def compilation_order(modules: List[str], dependencies: List[List[str]]) -> List[str]:
    graph = defaultdict(list)
    indeg = {m: 0 for m in modules}
    for a, b in dependencies:
        graph[b].append(a)
        indeg[a] = indeg.get(a, 0) + 1
        indeg.setdefault(b, indeg.get(b, 0))
    heap = [m for m, d in indeg.items() if d == 0]
    heapq.heapify(heap)
    out = []
    while heap:
        m = heapq.heappop(heap)
        out.append(m)
        for nxt in graph[m]:
            indeg[nxt] -= 1
            if indeg[nxt] == 0:
                heapq.heappush(heap, nxt)
    if len(out) != len(indeg):
        return ["IMPOSSIBLE"]
    return out
import java.util.*;

class Solution {
    public String[] compilationOrder(String[] modules, String[][] dependencies) {
        Map<String, List<String>> g = new HashMap<>();
        Map<String, Integer> indeg = new HashMap<>();
        for (String m : modules) indeg.put(m, 0);
        for (String[] d : dependencies) {
            g.computeIfAbsent(d[1], k -> new ArrayList<>()).add(d[0]);
            indeg.merge(d[0], 1, Integer::sum);
        }
        PriorityQueue<String> pq = new PriorityQueue<>();
        for (var e : indeg.entrySet()) if (e.getValue() == 0) pq.add(e.getKey());
        List<String> out = new ArrayList<>();
        while (!pq.isEmpty()) {
            String m = pq.poll();
            out.add(m);
            for (String nxt : g.getOrDefault(m, List.of())) {
                indeg.merge(nxt, -1, Integer::sum);
                if (indeg.get(nxt) == 0) pq.add(nxt);
            }
        }
        if (out.size() != indeg.size()) return new String[]{"IMPOSSIBLE"};
        return out.toArray(new String[0]);
    }
}
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
    vector<string> compilationOrder(vector<string>& modules, vector<vector<string>>& dependencies) {
        unordered_map<string, vector<string>> g;
        unordered_map<string, int> indeg;
        for (auto& m : modules) indeg[m] = 0;
        for (auto& d : dependencies) {
            g[d[1]].push_back(d[0]);
            indeg[d[0]]++;
        }
        priority_queue<string, vector<string>, greater<string>> pq;
        for (auto& [k, v] : indeg) if (v == 0) pq.push(k);
        vector<string> out;
        while (!pq.empty()) {
            string m = pq.top(); pq.pop();
            out.push_back(m);
            for (auto& nxt : g[m]) if (--indeg[nxt] == 0) pq.push(nxt);
        }
        if ((int)out.size() != (int)indeg.size()) return {"IMPOSSIBLE"};
        return out;
    }
};

Implement an in-memory key-value store that supports nested transactions. Commands are executed in order, one command per line. Supported commands are:

  • SET <key> <value>
  • GET <key>
  • DELETE <key>
  • BEGIN
  • ROLLBACK
  • COMMIT GET returns the current value of a key, or NULL if it does not exist. ROLLBACK and COMMIT print NO TRANSACTION when there is no active transaction. Return the lines that would be printed while processing the command batch. Function Description Complete the function runNestedTransactions in the editor below. runNestedTransactions has the following parameter:
  • String[] commands: the command batch, one command per element Returns String[]: the output lines produced by the batch in order.

Constraints

  • 1 ≤ commands.length ≤ 200000
  • Keys and values are non-empty strings without spaces.
  • Transactions may be nested arbitrarily deeply.
  • A near-linear total runtime is expected for large command batches.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁
Pro 会员

解锁全部 1 道题的解法

题面你已经看到了 — 解法 + 三语代码 + 复杂度推导 + 边界讨论, Pro 解锁.

Pro 解锁全部
  • 📚1000+ 道真实北美 OA, Python / Java / C++ 三语题解
  • 📊个人 dashboard + 进度可视化 + 14 天活跃图
  • 📝题目笔记跨设备同步 + 个人复盘库
  • 🔓随时取消下次续费, Stripe Customer Portal 自助管理
$12/月($98/年, 一次付清省 32%)

≈ 北美 SWE 工资 10 分钟 · LeetCode Premium $35/月 的 23%