It finds the element that appears more than n/2 times (if it exists). The idea is to cancel pairs of different elements; the remaining candidate is the majority. It runs in O(n) time and O(1) space.
function majority(nums: number[]): number {
let cand = 0;
let count = 0;
for (const x of nums) {
if (count === 0) cand = x;
count += x === cand ? 1 : -1;
}
return cand;
}
Advanced answer
Deep dive
Expanding on the short answer — what usually matters in practice:
Complexity: compare typical operations (average vs worst-case).
Invariants: what must always hold for correctness.
When the choice is wrong: production symptoms (latency, GC, cache misses).
Explain the "why", not just the "what" (intuition + consequences).
Trade-offs: what you gain/lose (time, memory, complexity, risk).
Edge cases: empty inputs, large inputs, invalid inputs, concurrency.
Examples
Here’s an additional example (building on the short answer):
function majority(nums: number[]): number {
let cand = 0;
let count = 0;
for (const x of nums) {
if (count === 0) cand = x;
count += x === cand ? 1 : -1;
}
return cand;
}
Common pitfalls
Too generic: no concrete trade-offs or examples.
Mixing average-case and worst-case (e.g., complexity).