⚡Flashcard Drill➔
NeetCode #123LC-179MediumArrays & Hashing
← Back to All Problems

#123 · #179 · Largest Number(最大数)

📌 Problem Statement & Constraints

Given a list of non-negative integers nums, arrange them to form the largest possible number and return it as a string. The result may be very large, so return a string rather than an integer. Constraints: 1 <= nums.length <= 100, 0 <= nums[i] <= 10^9.

💡 Core Algorithmic Approaches

  1. Sorting by numeric value is wrong: 9 should precede 34, but so should 34 precede 3? No -- the correct criterion is a pairwise comparison.
  2. Two numbers a and b should be ordered so that a before b if a + b (string concatenation) is lexicographically greater than b + a.
  3. This comparator is a valid total order (it is transitive), so a comparison sort can be used with it.
  4. Finally, handle the all-zeros case: the joined result would be "000...", which must be returned as "0".

💻 Benchmark Python3 Implementation

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        from functools import cmp_to_key

        def cmp(a: str, b: str) -> int:
            # a should come first if a+b > b+a lexicographically
            if a + b > b + a:
                return -1
            if a + b < b + a:
                return 1
            return 0

        parts = sorted(map(str, nums), key=cmp_to_key(cmp))
        res = "".join(parts)
        return "0" if res[0] == "0" else res   # all zeros -> "0"

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n log n * L) where L is the maximum number of digits: the comparator performs string concatenations of length up to 2L.
💾 Space Complexity
O(n * L) for the string list and the result.

⚠️ Interview Pitfalls & Follow-ups

  • Sorting by numeric value: [3, 30, 34] would give "34303", but the correct answer is "34330".
  • Comparing only the first digit: insufficient for multi-digit numbers.
  • Forgetting the all-zeros case: [0, 0] would produce "00", which must be returned as "0".
  • Returning an integer: the result can exceed 64 bits, so a string is required.
  • Assuming the comparator needs to be symmetric: it must return negative/zero/positive, and the direction encodes the ordering.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

最大数

给定一组非负整数 nums,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。注意:输出结果可能非常大,所以你需要返回一个字符串而不是整数。约束:1 ≤ nums.length ≤ 100;0 ≤ nums[i] ≤ 10^9。

核心要点

  • 自定义比较器(标准解) :对两个字符串 a、b,若 a + b &gt; b + a ,则 a 应排在 b 前面。按此规则排序后拼接即可。
  • 为什么 a + b &gt; b + a 是正确的排序准则 :它定义了拼接结果的大小关系,且满足传递性(可证明这是一个合法的全序),因此排序结果全局最优。
  • Python 实现 :用 functools.cmp_to_key 把比较函数转为排序键。
  • 前导零的处理 :若排序后第一个字符是 0 ,说明所有元素都是 0(因为 0 只可能在全部为 0 时排在最前),此时应返回 "0" 而非 "000..." 。

常见陷阱

  • 按字符串字典序直接排序 :会得到错误结果。例如 [3, 30] 按字典序 "30" &lt; "3",拼接为 "303",但正确答案是 "330"。必须用 a + b 与 b + a 比较。
  • 忘记处理全零 :nums = [0, 0] 时排序结果为 "00",应返回 "0"。
  • 用整数拼接后比较 : int(a + b) 在数字很长时会超出常规整数范围(虽 Python 不会溢出但会变慢)。字符串比较更高效。
  • 担心比较器的传递性 : a + b &gt; b + a 定义的关系是可传递的(这是本题的数学基础),因此可以安全地用于排序。

参考实现

from functools import cmp_to_key

class Solution:
    def largestNumber(self, nums: list[int]) -> str:
        strs = [str(x) for x in nums]

        def cmp(a: str, b: str) -> int:
            if a + b > b + a:
                return -1       # a 排在 b 前面
            if a + b < b + a:
                return 1
            return 0

        strs.sort(key=cmp_to_key(cmp))
        res = ''.join(strs)
        return '0' if res[0] == '0' else res   # 处理全零的情况