In LeetCode 2529: Maximum Count of Positive Integer and Negative Integer, we are given a non-decreasing integer array nums and asked to return whichever quantity is larger: the count of strictly negative integers or the count of strictly positive integers, ignoring zeros completely. Leveraging dual lower_bound binary searches achieves O(log N) logarithmic runtime and O(1) auxiliary space.
Problem Statement & Boundary Semantics
Given an array nums sorted in non-decreasing order, let neg be the count of elements strictly less than 0 and let pos be the count of elements strictly greater than 0. Return max(neg, pos). Note that 0 is neither positive nor negative and must be excluded from both totals.
Formal Constraints: 1 ≤ nums.length ≤ 2000 and -2000 ≤ nums[i] ≤ 2000, sorted such that nums[i] ≤ nums[i + 1] for every valid index.
Representative Edge Cases
- Balanced Sign Split:
nums = [-2, -1, -1, 1, 2, 3]→neg = 3,pos = 3→ returns3. - Contiguous Zero Plateau:
nums = [-3, -2, -1, 0, 0, 0, 1, 2]→neg = 3, three zeros skipped,pos = 2→ returns3. - All Zeros Degenerate Input:
nums = [0, 0, 0, 0]→neg = 0,pos = 0→ returns0.
Reusing a Single Lower-Bound Primitive Over Integer Domains
Because every element in nums is a discrete integer rather than an arbitrary IEEE-754 floating-point number, we do not even need separate lower_bound and upper_bound helper functions. Define bisectLeft(nums, target) as the smallest index idx in [0, nums.length] where nums[idx] ≥ target:
- Negative Partition End (
target = 0): Every element beforebisectLeft(nums, 0)satisfiesnums[i] < 0. Because indices are zero-based,negCountequalsbisectLeft(nums, 0)directly. - Positive Partition Start (
target = 1): For integers,x > 0is algebraically identical tox ≥ 1. Therefore, the first strictly positive element sits atfirstPos = bisectLeft(nums, 1), andposCount = nums.length - firstPos.
Even if nums contains 1,998 zeros in the middle, two binary searches jump cleanly across the entire zero plateau in at most 2 × 11 = 22 comparisons.
Approach 1: Overflow-Safe Binary Search in TypeScript
Notice how we narrow the second search's lower bound to lo = negCount: since 1 > 0, the first index ≥ 1 can never appear to the left of the first index ≥ 0, shaving redundant probes off the positive search:
function bisectLeft(nums: ReadonlyArray<number>, target: number, startLo = 0): number {
let lo = startLo;
let hi = nums.length;
while (lo < hi) {
// Unsigned right shift prevents 32-bit signed overflow when lo + hi > 2^31 - 1
const mid = (lo + hi) >>> 1;
if (nums[mid] < target) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
export function maximumCount(nums: ReadonlyArray<number>): number {
if (nums.length === 0) return 0;
// Fast O(1) short-circuit when entire sorted array has uniform strict sign
if (nums[0] > 0 || nums[nums.length - 1] < 0) {
return nums.length;
}
const negCount = bisectLeft(nums, 0, 0);
const firstPositive = bisectLeft(nums, 1, negCount);
const posCount = nums.length - firstPositive;
return negCount > posCount ? negCount : posCount;
}
Approach 2: Standard Library std::lower_bound in C++20
In C++20, std::ranges::lower_bound (or iterator-based std::lower_bound) expresses the exact two-partition boundary query in six lines while starting the second search directly at firstNonNeg:
#include <algorithm>
#include <vector>
class Solution {
public:
int maximumCount(const std::vector<int>& nums) const noexcept {
if (nums.empty()) return 0;
if (nums.front() > 0 || nums.back() < 0) {
return static_cast<int>(nums.size());
}
const auto firstNonNeg = std::lower_bound(nums.begin(), nums.end(), 0);
const auto firstPos = std::lower_bound(firstNonNeg, nums.end(), 1);
const int negCount = static_cast<int>(firstNonNeg - nums.begin());
const int posCount = static_cast<int>(nums.end() - firstPos);
return std::max(negCount, posCount);
}
};
Hardware Microarchitecture: Binary Search vs. AVX2 Linear Scans
At N = 2,000 32-bit integers, the entire array occupies exactly 8,000 bytes—fitting comfortably inside a 32 KB L1 data cache on x86-64 and Apple Silicon cores. Why does this matter in systems engineering?
- Data-Dependent Branch Misprediction: Standard binary search branches unpredictably (~50% misprediction rate), incurring ~12–15 pipeline flush cycles per mispredicted jump (~150–200 cycles total for 22 probes).
- Vectorized SIMD Tallying: A branchless C++ loop compiled with
-O3 -mavx2loads eight 32-bit integers per__m256iregister using_mm256_cmpgt_epi32, scanning 2,000 elements in 250 vector instructions (~125 cycles) with zero branch mispredictions. - Asymptotic Crossover Point: Beyond
N ≈ 4,096elements (or whenever data resides in L3 cache, DRAM, or disk-backed B-tree pages),O(log N)binary search wins decisively by touching onlyO(log N)cache lines instead of streaming megabytes over memory buses.
| Search Strategy | Time Complexity | Auxiliary Space | Optimal Workload Regime |
|---|---|---|---|
| Scalar Linear Scan | O(N) |
O(1) |
Unsorted inputs where ordering cannot be assumed. |
| Branchless AVX2 Vector Scan | O(N / 8) |
O(1) |
Tiny L1-resident arrays (N ≤ 2,048) in hot C++ loops. |
Chained bisectLeft Binary Search |
O(log N) |
O(1) |
General sorted arrays, large datasets, and B-tree / SSTable index blocks. |
Real-World Backend & Telemetry Use Cases
- Time-Series Latency Histogram Bucketing: Computing error-budget burn vs. sub-threshold responses over pre-sorted request-latency slices in Prometheus and ClickHouse engines.
- Double-Entry Ledger Reconciliation: Counting debit vs. credit postings in sorted settlement batches while excluding zero-dollar memo adjustments.
- Columnar Parquet Zone-Map Pruning: Skipping null/zero runs in dictionary-encoded sorted column pages without decompressing interior blocks.
