我喜欢的一道软件工程面试题:计算中位数
A software engineering interview question I like: computing the median

原始链接: https://krisshamloo.com/blog/007

作者主张将“计算中位数”作为高质量的软件工程面试题。相比简单的“Fizz Buzz”测试,该问题能更全面地评估候选人的技术成熟度和思维深度。 这项练习要求候选人在多个实际工程权衡中做出选择,包括 API 设计、副作用(可变性)以及排序的性能考量。同时,由于逻辑中常包含“差一错误”(off-by-one errors)以及针对数组长度奇偶性的分支判断等陷阱,该问题也为观察候选人的调试习惯提供了天然场景。 除了代码实现,该问题还是深入探讨统计概念(例如为何中位数通常比平均数更稳健)以及考察候选人是否能有效利用标准库的绝佳切入点。归根结底,该任务因其简洁性而具备极高的可测试性,同时能清晰揭示候选人是否能审慎地思考其代码所带来的影响。

围绕“中位数计算”这一面试题的讨论,揭示了招聘实践中存在的巨大分歧。 **批评者**认为,此类问题属于“计算机科学入门级的自我陶醉”,对于大多数行业岗位而言毫无意义,因为开发者几乎不需要从零开始计算中位数。他们指出,这些难题忽视了系统设计、沟通能力、错误处理及学习能力等高级职场必备技能。此外,许多面试官往往抱有刻板的预期(例如“必须对数据进行排序”),而忽略了快速选择(Quickselect)或流式算法等更高效的方案。 **支持者**则为该问题辩护,认为这是筛选无法编写基础代码的应聘者所必需的手段。他们认为大规模招聘需要一个“漏斗”来快速剔除不合格者。在验证了基本能力后,他们会转而探讨更深层的问题,如权衡考量(例如内存限制、数据流和时间复杂度)。 最终,业界的共识倾向于将简单易懂的问题作为切入点——其目的不在于考察死记硬背,而在于评估候选人的解决问题的思路、学习意愿以及进行有效技术对话的能力。面试的价值不在于“正确”的代码,而在于对现实约束条件的共同探索。
相关文章

原文

a software engineering interview question I like: computing the median

2026-05-03

I have a number of questions in my quiver when I'm giving technical interviews to candidates. They are all of a similar flavor. I don't ask puzzle questions, I find them low value. Instead, I ask questions that are straightforward but have a few angles with which to explore deeper topics.

Enter the humble median.

Write a function that takes an array of numbers and returns the median.

  • At a minimum: this will give you a "Fizz Buzz"-like signal that the candidate can actually program. Reducing an array of values is table stakes.
  • Right out the gate: the numbers must be sorted. Should the function sort them? Should the caller? If the array was passed in by reference is it ok to mutate? How does the API design influence the performance?
  • It has an off-by-one trap. Mind you I don't care if anyone falls into an off-by-one trap, I fall into them all the time, but you'll often get a chance to watch someone debug a small problem.
  • It has a branch: an even length array versus an odd one.
  • It can lead to some discussion about statistics and why you might prefer a median to a mean in most cases.
  • Gives the candidate a chance for some extra points by being so readily testable.
  • Gives the candidate a chance to display some standard library knowledge via statistics.

Here's a Python implementation with discussion comments.

def median(numbers: list[float]) -> float:
    
    
    if not numbers:
        raise ValueError("median called with empty list")

    
    
    numbers = sorted(numbers)
    length = len(numbers)
    mid = length // 2

    
    
    if length % 2 == 0:
        return (numbers[mid - 1] + numbers[mid]) / 2.0
    else:
        return numbers[mid]
联系我们 contact @ memedata.com