此篇是我重读「14 Patterns to Ace Any Coding Interview Question」后,进行的翻译,借助沉浸式翻译,使用 DeepL 的 API

The process of preparing for coding interviews is anxiety-inducing for many developers. There’s so much material to cover, and often much of it feels irrelevant to what devs are doing in their day jobs, which only adds to the stress.对许多开发人员来说,准备编码面试的过程令人焦虑不安。要涉及的内容太多,而且很多内容往往与开发人员的日常工作无关,这只会增加他们的压力。

One of the outcomes of this is that it’s now common for developers to spend weeks combing through hundreds of interview questions on sites like LeetCode. One of the most common points of anxiety developers that I’ve talked to have before the interview is: *Have I solved enough practice questions? Could I have done more?*这样做的结果之一是,现在开发人员经常要花费数周时间在 LeetCode 等网站上梳理数百道面试题。与我交谈过的开发人员在面试前最常见的焦虑之一是:我解决的练习题够多吗?我还能做得更多?

That’s why I try to focus on helping developers grasp the underlyingpatterns behind each question — so they don’t have to worry about solving hundreds of problems and suffer from Leetcode fatigue. If you understand the generic patterns, you can use them as a template to solve a myriad of other problems with slight variations.这就是为什么我努力把重点放在帮助开发人员掌握每个问题背后的基本模式上–这样他们就不必担心要解决成百上千个问题而患上 Leetcode 疲劳症。如果您了解了通用模式,您就可以将其作为模板,以微小的变化解决无数其他问题。

Here, I’ve laid out the top 14 patterns that can be used to solve any coding interview question, as well as how to identify each pattern, and some example questions for each. This just touches the surface — I strongly recommend checking out Grokking the Coding Interview: Patterns for Coding Questions for comprehensive explanations, examples, and coding practice.在这里,我列出了可用于解决任何编码面试问题的 14 种顶级模式,以及如何识别每种模式和每种模式的一些示例问题。这仅仅是皮毛–我强烈建议你阅读《编码面试模式》(Grokking the Coding Interview)一书:编码问题的模式》,以获得全面的解释、示例和编码练习。

The following patterns assume that you’ve brushed up on Data Structures. If you haven’t, check out these refresher courses on Data Structures.以下模式假定您已经学习过数据结构。如果还没有,请查看这些数据结构复习课程。

Let’s get started!  让我们开始吧!

1. Sliding Window 1.滑动窗口

The Sliding Window pattern is used to perform a required operation on a specific window size of a given array or linked list, such as finding the longest subarray containing all 1s. Sliding Windows start from the 1st element and keep shifting right by one element and adjust the length of the window according to the problem that you are solving. In some cases, the window size remains constant and in other cases the sizes grows or shrinks.滑动窗口模式用于在给定数组或链表的特定窗口大小上执行所需的操作,例如查找包含所有 1 的最长子数组。滑动窗口从第 1 个元素开始向右移动一个元素,并根据要解决的问题调整窗口的长度。在某些情况下,窗口大小保持不变,而在其他情况下,窗口大小则会增大或缩小。

Following are some ways you can identify that the given problem might require a sliding window:以下几种方法可以帮助您确定特定问题可能需要使用滑动窗口:

  • The problem input is a linear data structure such as a linked list, array, or string

    问题输入是线性数据结构,如链表、数组或字符串

  • You’re asked to find the longest/shortest substring, subarray, or a desired value

    要求您找出最长/最短的子串、子数组或所需值

Common problems you use the sliding window pattern with:使用滑动窗口模式的常见问题:

  • Maximum sum subarray of size ‘K’ (easy)

    大小为 “K “的子数组的最大和(简单)

  • Longest substring with ‘K’ distinct characters (medium)

    包含’K’个不同字符的最长子串(中)

  • String anagrams (hard)

    字符串变位(难)

**2. Two Pointers or Iterators****2.两个指针或迭代器**

Two Pointers is a pattern where two pointers iterate through the data structure in tandem until one or both of the pointers hit a certain condition.Two Pointers is often useful when searching pairs in a sorted array or linked list; for example, when you have to compare each element of an array to its other elements.双指针 “是一种模式,其中两个指针在数据结构中串行遍历,直到其中一个或两个指针达到某个条件。”双指针 “通常在搜索排序数组或链接列表中的成对元素时非常有用;例如,当您需要比较数组中的每个元素和其他元素时。

Two pointers are needed because with just pointer, you would have to continually loop back through the array to find the answer. This back and forth with a single iterator is inefficient for time and space complexity — a concept referred to as asymptotic analysis. While the brute force or naive solution with 1 pointer would work, it will produce something along the lines of O(n²). In many cases, two pointers can help you find a solution with better space or runtime complexity.之所以需要两个指针,是因为如果只使用指针,就必须不断地在数组中循环,才能找到答案。从时间和空间复杂性的角度来看,使用单个迭代器来回循环的效率都很低,这就是所谓的渐近分析概念。虽然使用 1 个指针的蛮力或天真解决方案可以奏效,但它将产生类似 O(n²) 的结果。在很多情况下,两个指针可以帮助你找到空间或运行时复杂度更高的解决方案。

Ways to identify when to use the Two Pointer method:识别何时使用双指针法的方法:

  • It will feature problems where you deal with sorted arrays (or Linked Lists) and need to find a set of elements that fulfill certain constraints

    它的特色是处理排序数组(或链接列表)的问题,需要找到满足特定约束条件的元素集

  • The set of elements in the array is a pair, a triplet, or even a subarray

    数组中的元素集是一对、三对,甚至是一个子数组

Here are some problems that feature the Two Pointer pattern:下面是一些以 “双指针 “模式为特征的问题:

  • Squaring a sorted array (easy)

    平方排序数组(简单)

  • Triplets that sum to zero (medium)

    总和为零的三胞胎(中)

  • Comparing strings that contain backspaces (medium)

    比较包含空格的字符串(中)

**3. Fast and Slow pointers**3.快速和慢速指针The Fast and Slow pointer approach, also known as the Hare & Tortoise algorithm, is a pointer algorithm that uses two pointers which move through the array (or sequence/linked list) at different speeds. **This approach is quite useful when dealing with cyclic linked lists or arrays.**快慢指针法又称龟兔算法,是一种指针算法,使用两个指针以不同的速度在数组(或序列/链表)中移动。这种方法在处理循环链表或数组时非常有用。

By moving at different speeds (say, in a cyclic linked list), the algorithm proves that the two pointers are bound to meet. The fast pointer should catch the slow pointer once both the pointers are in a cyclic loop.通过以不同的速度移动(例如,在循环链表中),该算法证明了两个指针一定会相遇。一旦两个指针都进入循环,速度快的指针就会赶上速度慢的指针。

How do you identify when to use the Fast and Slow pattern?如何确定何时使用 “快慢 “模式?

  • The problem will deal with a loop in a linked list or array

    问题将涉及链接列表或数组中的循环

  • When you need to know the position of a certain element or the overall length of the linked list.

    当您需要知道某个元素的位置或链表的总长度时。

When should I use it over the Two Pointer method mentioned above?什么情况下应该使用这种方法,而不是上述的 “两个指针 “方法?

  • There are some cases where you shouldn’t use the Two Pointer approach such as in a singly linked list where you can’t move in a backwards direction. An example of when to use the Fast and Slow pattern is when you’re trying to determine if a linked list is a palindrome.

    在某些情况下,你不应该使用双指针方法,例如在单链表中,你不能向后移动。使用 “快慢 “模式的一个例子是,当你试图确定一个链表是否是回文时。

Problems featuring the fast and slow pointers pattern:以快慢指针模式为特征的问题:

  • Linked List Cycle (easy)

    链接列表循环(简单)

  • Palindrome Linked List (medium)

    回文字符链表(中等)

  • Cycle in a Circular Array (hard)

    在圆形阵列中循环(困难)

4. Merge Intervals  合并区间

The Merge Intervals pattern is an efficient technique to deal with overlapping intervals. In a lot of problems involving intervals, you either need to find overlapping intervals or merge intervals if they overlap. The pattern works like this:合并区间模式是一种处理重叠区间的有效技术。在许多涉及区间的问题中,要么需要找到重叠的区间,要么需要合并重叠的区间。该模式的工作原理如下

Given two intervals (‘a’ and ‘b’), there will be six different ways the two intervals can relate to each other:给定两个区间(”a “和 “b”),这两个区间会有六种不同的关联方式:

Understanding and recognizing these six cases will help you help you solve a wide range of problems from inserting intervals to optimizing interval merges.了解和识别这六种情况将帮助你解决从插入区间到优化区间合并等各种问题。

How do you identify when to use the Merge Intervals pattern?如何确定何时使用合并间隔模式?

  • If you’re asked to produce a list with only mutually exclusive intervals

    如果要求你生成一个只有互斥区间的列表

  • If you hear the term “overlapping intervals”.

    如果你听到 “重叠间隔 “这个词。

Merge interval problem patterns:合并区间问题模式:

  • Intervals Intersection (medium)

    区间交叉口(中等)

  • Maximum CPU Load (hard)

    CPU 最大负载(困难)

5. Cyclic sort 5.循环排序

This pattern describes an interesting approach to deal with problems involving arrays containing numbers in a given range. The Cyclic Sort pattern iterates over the array one number at a time, and if the current number you are iterating is not at the correct index, you swap it with the number at its correct index. You could try placing the number in its correct index, but this will produce a complexity of O(n^2) which is not optimal, hence the Cyclic Sort pattern.该模式描述了一种有趣的方法,用于处理涉及包含给定范围内数字的数组的问题。循环排序模式每次迭代数组中的一个数字,如果当前迭代的数字不在正确的索引中,则将其与正确索引中的数字交换。您可以尝试将数字放在正确的索引中,但这样做的复杂度为 O(n^2),并不是最优的,因此采用了循环排序模式。

How do I identify this pattern?如何识别这种模式?

  • They will be problems involving a sorted array with numbers in a given range

    这些问题涉及在给定范围内对数字进行排序的数组

  • If the problem asks you to find the missing/duplicate/smallest number in an sorted/rotated array

    如果问题要求你找出排序/旋转数组中遗漏/重复/最小的数字

Problems featuring cyclic sort pattern:以循环排序模式为特征的问题:

  • Find the Missing Number (easy)

    查找缺少的数字(简单)

  • Find the Smallest Missing Positive Number (medium)

    找出最小的缺失正数(中)

6. In-place reversal of linked list 链接表的原地反转

In a lot of problems, you may be asked to reverse the links between a set of nodes of a linked list. Often, the constraint is that you need to do this in-place, i.e., using the existing node objects and without using extra memory. This is where the above mentioned pattern is useful.在很多问题中,你可能会被要求反转链表中一组节点之间的链接。通常情况下,限制条件是需要就地反转,即使用现有的节点对象且不占用额外内存。这就是上述模式的用武之地。

This pattern reverses one node at a time starting with one variable (current) pointing to the head of the linked list, and one variable (previous) will point to the previous node that you have processed. In a lock-step manner, you will reverse the current node by pointing it to the previous before moving on to the next node. Also, you will update the variable “previous” to always point to the previous node that you have processed.这种模式每次反转一个节点,从一个变量(当前)指向链表头部开始,一个变量(前一个)将指向已处理的前一个节点。以步调一致的方式,在进入下一个节点前,先将当前节点指向前一个节点,然后再反转当前节点。此外,您还将更新变量 “previous”,使其始终指向您处理过的前一个节点。

How do I identify when to use this pattern:如何确定何时使用这种模式:

  • If you’re asked to reverse a linked list without using extra memory

    如果要求您在不使用额外内存的情况下反转链表

Problems featuring in-place reversal of linked list pattern:链接列表模式的就地反转问题:

  • Reverse a Sub-list (medium)

    反转子列表(中等)

  • Reverse every K-element Sub-list (medium)

    反转每个 K 元素子列表(中等)

7. Tree BFS  树状 BFS

This pattern is based on the Breadth First Search (BFS) technique to traverse a tree and uses a queue to keep track of all the nodes of a level before jumping onto the next level. Any problem involving the traversal of a tree in a level-by-level order can be efficiently solved using this approach.这种模式基于广度优先搜索(BFS)技术来遍历树,并在跳转到下一级之前使用队列来跟踪一级的所有节点。任何涉及按逐级顺序遍历树的问题,都可以用这种方法高效解决。

The Tree BFS pattern works by pushing the root node to the queue and then continually iterating until the queue is empty. For each iteration, we remove the node at the head of the queue and “visit” that node. After removing each node from the queue, we also insert all of its children into the queue.树状 BFS 模式的工作原理是将根节点推入队列,然后不断迭代,直到队列为空。每次迭代,我们都会移除队列头部的节点,并 “访问 “该节点。从队列中移除每个节点后,我们还会将其所有子节点插入队列。

How to identify the Tree BFS pattern:如何识别树状 BFS 模式:

  • If you’re asked to traverse a tree in a level-by-level fashion (or level order traversal)

    如果要求以逐级方式遍历一棵树(或按级顺序遍历)

Problems featuring Tree BFS pattern:以树状 BFS 模式为特征的问题:

  • Binary Tree Level Order Traversal (easy)

    二叉树层序遍历(简单)

  • Zigzag Traversal (medium)

    之字形穿越(中等)

8. Tree DFS 8.树状 DFS

Tree DFS is based on the Depth First Search (DFS) technique to traverse a tree.树形 DFS 基于深度优先搜索(DFS)技术来遍历树。

You can use recursion (or a stack for the iterative approach) to keep track of all the previous (parent) nodes while traversing.您可以使用递归(或迭代方法中的堆栈)在遍历时跟踪所有前一个(父节点)节点。

The Tree DFS pattern works by starting at the root of the tree, if the node is not a leaf you need to do three things:树形 DFS 模式从树根开始工作,如果节点不是叶子,则需要做三件事:

  1. Decide whether to process the current node now (pre-order), or between processing two children (in-order) or after processing both children (post-order).

    决定是现在处理当前节点(预排序),还是在处理两个子节点之间(顺序内),或者在处理两个子节点之后(顺序后)。

  2. Make two recursive calls for both the children of the current node to process them.

    对当前节点的两个子节点进行两次递归调用,以处理它们。

How to identify the Tree DFS pattern:如何识别树形 DFS 模式:

  • If you’re asked to traverse a tree with in-order, preorder, or postorder DFS

    如果要求你用顺序内、顺序前或顺序后 DFS 遍历一棵树

  • If the problem requires searching for something where the node is closer to a leaf

    如果问题需要搜索节点更靠近叶子的地方

Problems featuring Tree DFS pattern:以树状 DFS 模式为特征的问题:

  • Sum of Path Numbers (medium)

    路径编号之和(中)

  • All Paths for a Sum (medium)

    求和的所有路径(中)

9. Two heaps 9.两堆

In many problems, we are given a set of elements such that we can divide them into two parts. To solve the problem, we are interested in knowing the smallest element in one part and the biggest element in the other part. This pattern is an efficient approach to solve such problems.在许多问题中,我们会得到一组元素,可以将它们分成两部分。要解决这个问题,我们需要知道一部分中最小的元素和另一部分中最大的元素。这种模式是解决此类问题的有效方法。

This pattern uses two heaps; A Min Heap to find the smallest element and a Max Heap to find the biggest element. The pattern works by storing the first half of numbers in a Max Heap, this is because you want to find the largest number in the first half. You then store the second half of numbers in a Min Heap, as you want to find the smallest number in the second half. At any time, the median of the current list of numbers can be calculated from the top element of the two heaps.该模式使用两个堆:最小堆用于查找最小的元素,最大堆用于查找最大的元素。该模式的工作原理是将前半部分的数字存储在最大堆中,这是因为要在前半部分中找到最大的数字。然后将下半部分的数字存储在 Min Heap 中,因为要找出下半部分中最小的数字。在任何时候,当前数字列表的中位数都可以通过这两个堆的顶层元素计算出来。

Ways to identify the Two Heaps pattern:识别 “两堆 “模式的方法:

  • Useful in situations like Priority Queue, Scheduling

    在优先队列、调度等情况下非常有用

  • If the problem states that you need to find the smallest/largest/median elements of a set

    如果问题指出需要找出集合中最小/最大/中值元素

  • Sometimes, useful in problems featuring a binary tree data structure

    有时,在以二叉树数据结构为特征的问题中很有用

Problems featuring  特色问题

  • Find the Median of a Number Stream (medium)

    求数字流的中位数(中)

10. Subsets 10.子集

A huge number of coding interview problems involve dealing with Permutations and Combinations of a given set of elements. The pattern Subsets describes an efficient Breadth First Search (BFS) approach to handle all these problems.大量的编码面试问题都涉及处理给定元素集合的排列和组合。子集模式描述了一种高效的广度优先搜索(BFS)方法来处理所有这些问题。

The pattern looks like this:图案是这样的

Given a set of [1, 5, 3]给定一组 [1, 5, 3] 数据

  1. Start with an empty set: [[]]

    从空集开始:[[]]

  2. Add the first number (1) to all the existing subsets to create new subsets: [[], [1]];

    将第一个数字 (1) 添加到所有现有子集,创建新子集:[[], [1]];

  3. Add the second number (5) to all the existing subsets: [[], [1], [5], [1,5]];

    将第二个数字(5)添加到所有现有子集中:[[], [1], [5], [1,5]];

  4. Add the third number (3) to all the existing subsets: [[], [1], [5], [1,5], [3], [1,3], [5,3], [1,5,3]].

    在所有现有子集上添加第三个数字 (3):[[], [1], [5], [1,5], [3], [1,3], [5,3], [1,5,3]].

Here is a visual representation of the Subsets pattern:下面是 “子集 “模式的直观示意图:

How to identify the Subsets pattern:如何识别子集模式:

  • Problems where you need to find the combinations or permutations of a given set

    需要找出给定集合的组合或排列的问题

Problems featuring Subsets pattern:以子集模式为特征的问题:

  • Subsets With Duplicates (easy)

    有重复的子集(简单)

  • String Permutations by changing case (medium)

    通过改变大小写进行字符串排列(中)

**11. Modified binary search****11.改进的二进制搜索**

Whenever you are given a sorted array, linked list, or matrix, and are asked to find a certain element, the best algorithm you can use is the Binary Search. This pattern describes an efficient way to handle all problems involving Binary Search.每当给你一个排序数组、链表或矩阵,并要求你找到某个元素时,你能使用的最佳算法就是二进制搜索。本模式描述了处理所有涉及二进制搜索问题的有效方法。

The patterns looks like this for an ascending order set:升序排列的模式如下:

  1. First, find the middle of start and end. An easy way to find the middle would be: middle = (start + end) / 2. But this has a good chance of producing an integer overflow so it’s recommended that you represent the middle as: middle = start + (end — start) / 2

    首先,找出起点和终点的中间值。找到中间值的简单方法是:middle = (start + end) / 2。但这样做很有可能导致整数溢出,因此建议将中间值表示为:middle = start + (end - start) / 2

  2. If the key is equal to the number at index middle then return middle

    如果键等于位于索引中间的数字,则返回 middle

  3. If ‘key’ isn’t equal to the index middle:

    如果 “key “不等于中间索引:

  4. Check if key < arr[middle]. If it is reduce your search to end = middle — 1

    检查 key 是否 < arr[middle]。如果是,则将搜索范围缩小为 end = middle - 1

  5. Check if key > arr[middle]. If it is reduce your search to end = middle + 1

    检查 key 是否 > arr[middle]。如果是,则将搜索范围缩小为 end = middle + 1

Here is a visual representation of the Modified Binary Search pattern:下面是修正二进制搜索模式的直观图:

Problems featuring the Modified Binary Search pattern:以修正二进制搜索模式为特征的问题:

Order-agnostic Binary Search (easy)Search in a Sorted Infinite Array (medium)与顺序无关的二进制搜索(简单)在有序无限阵列中搜索(中等)

12. Top K elements 12.顶级 K 元素

Any problem that asks us to find the top/smallest/frequent ‘K’ elements among a given set falls under this pattern.任何要求我们找出给定集合中最重要/最小/频繁出现的 “K “元素的问题都属于这种模式。

The best data structure to keep track of ‘K’ elements is Heap. This pattern will make use of the Heap to solve multiple problems dealing with ‘K’ elements at a time from a set of given elements. The pattern looks like this:跟踪’K’个元素的最佳数据结构是堆。该模式将利用 Heap 来解决多个问题,一次从一组给定的元素中处理 “K “个元素。该模式如下所示

  1. Insert ‘K’ elements into the min-heap or max-heap based on the problem.

    根据问题,在最小堆或最大堆中插入’K’个元素。

  2. Iterate through the remaining numbers and if you find one that is larger than what you have in the heap, then remove that number and insert the larger one.

    遍历剩余的数字,如果发现一个数字比堆中的数字大,则删除该数字,插入较大的数字。

There is no need for a sorting algorithm because the heap will keep track of the elements for you.不需要排序算法,因为堆会帮你跟踪元素。

How to identify the Top ‘K’ Elements pattern:如何识别顶级 “K “元素图案:

  • If you’re asked to find the top/smallest/frequent ‘K’ elements of a given set

    如果要求你找出给定集合中最大/最小/最常出现的 “K “元素

  • If you’re asked to sort an array to find an exact element

    如果要求对数组进行排序以找到精确的元素

Problems featuring Top ‘K’ Elements pattern:问题的特征是顶部的 “K “元素图案:

  • Top ‘K’ Numbers (easy)

    顶级 “K “数字(简单)

  • Top ‘K’ Frequent Numbers (medium)

    最高’K’频数(中等)

13. K-way Merge 13.K-way 合并

K-way Merge helps you solve problems that involve a set of sorted arrays.K-way Merge 可以帮助你解决涉及一组排序数组的问题。

Whenever you’re given ‘K’ sorted arrays, you can use a Heap to efficiently perform a sorted traversal of all the elements of all arrays. You can push the smallest element of each array in a Min Heap to get the overall minimum. After getting the overall minimum, push the next element from the same array to the heap. Then, repeat this process to make a sorted traversal of all elements.只要给定 “K “个排序数组,就可以使用堆对所有数组的所有元素进行高效的排序遍历。您可以将每个数组中最小的元素推入最小堆,以获得整体最小值。得到整体最小值后,将同一数组中的下一个元素推入堆。然后,重复这一过程,对所有元素进行排序遍历。

The pattern looks like this:图案是这样的

  1. Insert the first element of each array in a Min Heap.

    在最小堆中插入每个数组的第一个元素。

  2. After this, take out the smallest (top) element from the heap and add it to the merged list.

    然后,从堆中取出最小(顶部)的元素,并将其添加到合并列表中。

  3. After removing the smallest element from the heap, insert the next element of the same list into the heap.

    从堆中移除最小的元素后,将同一列表中的下一个元素插入堆中。

  4. Repeat steps 2 and 3 to populate the merged list in sorted order.

    重复步骤 2 和 3,按排序填充合并列表。

How to identify the K-way Merge pattern:如何识别 K-way 合并模式:

  • The problem will feature sorted arrays, lists, or a matrix

    问题将以排序数组、列表或矩阵为特征

  • If the problem asks you to merge sorted lists, find the smallest element in a sorted list.

    如果问题要求您合并排序列表,请找出排序列表中最小的元素。

Problems featuring the K-way Merge pattern:以 K-way Merge 模式为特色的问题:

  • Merge K Sorted Lists (medium)

    合并 K 排序列表(中)

  • K Pairs with Largest Sums (Hard)

    和最大的 K 对(难)

14. Topological sort 14.拓扑排序

Topological Sort is used to find a linear ordering of elements that have dependencies on each other. For example, if event ‘B’ is dependent on event ‘A’, ‘A’ comes before ‘B’ in topological ordering.拓扑排序用于查找相互依赖的元素的线性排序。例如,如果事件 “B “依赖于事件 “A”,那么在拓扑排序中,”A “排在 “B “之前。

This pattern defines an easy way to understand the technique for performing topological sorting of a set of elements.该模式定义了一种简单的方法,用于理解对元素集进行拓扑排序的技术。

The pattern works like this:模式是这样的

  1. Initializationa) Store the graph in adjacency lists by using a HashMapb) To find all sources, use a HashMap to keep the count of in-degreesBuild the graph and find in-degrees of all vertices

    初始化

    a) 使用 HashMap 将图存储在邻接表中

    b) 要查找所有来源,使用 HashMap 保存内度计数。

  2. Build the graph from the input and populate the in-degrees HashMap.

    根据输入建立图形,并填充 in-degrees HashMap。

  3. Find all sourcesa) All vertices with ‘0’ in-degrees will be sources and are stored in a Queue.

    查找所有资料来源

    a) 所有内角为 “0 “的顶点都将是源顶点,并存储在队列中。

  4. Sorta) For each source, do the following things:—i) Add it to the sorted list.— ii)Get all of its children from the graph.— iii)Decrement the in-degree of each child by 1.— iv)If a child’s in-degree becomes ‘0’, add it to the sources Queue.b) Repeat (a), until the source Queue is empty.

    分类

    a) 对每个信息源进行以下操作:

      • i) 将其添加到排序列表中。
      • ii) 从图形中获取其所有子代。
      • iii) 将每个子代的内部度数减 1。
      • iv)如果一个孩子的内部度数变为 “0”,则将其添加到来源队列中。

    b) 重复 (a),直到源队列为空。

How to identify the Topological Sort pattern:如何识别拓扑排序模式:

  • The problem will deal with graphs that have no directed cycles

    该问题将处理没有定向循环的图

  • If you’re asked to update all objects in a sorted order

    如果要求按排序更新所有对象

  • If you have a class of objects that follow a particular order

    如果您有一类遵循特定顺序的对象

Problems featuring the Topological Sort pattern:具有拓扑排序模式的问题:

  • Task scheduling (medium)

    任务调度(中)

  • Minimum height of a tree (hard)

    树木的最低高度(硬质)

What next? 下一步怎么办?

Experiencing LeetCode fatigue? Learn these 14 patterns and you’ll have a more complete picture of how to approach a problem no matter the question.对 LeetCode 感到疲劳?学习这 14 种模式,无论问题是什么,你都能更全面地了解如何解决问题。

If you’re interested in a deeper dive through the above patterns or the example problems under each one, check out Grokking the Coding Interview: Patterns for Coding Questions. It’s the latest course in the Grokking interview series, used by 20,000+ learners to land jobs at top tech companies.如果您想深入了解上述模式或每种模式下的例题,请查阅《Grokking the Coding Interview》:编码问题模式》。这是 Grokking 面试系列的最新课程,已有 20,000 多名学员通过该课程在顶级科技公司找到了工作。

The highest endorsement I can give it is that I really wish it was around when I was still preparing for coding interviews.我能给予它的最高评价是,我真希望在我还在准备编码面试的时候就有这本书。

参考