File: check-if-a-number-is-majority-element-in-a-sorted-array/solution.py

Date: 2026-06-06

Time: 15:35

Purpose

This file solves LeetCode 1150: Check If a Number Is Majority Element in a Sorted Array. Given a sorted array and a target value, it determines whether the target appears more than n/2 times. It owns exactly one responsibility: the ismajorityelement function.

Key Components

ismajorityelement(nums, target) -> bool

The single exported function. It exploits the sorted order of nums to answer the majority question in O(log n) time without counting occurrences.

Contract: nums must be sorted in non-decreasing order. target is the value to check. Returns True iff target appears strictly more than len(nums) // 2 times (integer division — so for n=5, more than 2, i.e., at least 3).

Patterns

Binary search + index arithmetic. Rather than scanning or even doing two binary searches (for the first and last occurrence), the solution does one bisect_left to find the leftmost position of target, then checks whether target still appears n//2 positions to the right. This is a well-known trick for sorted-array frequency queries.

The key insight: if target occupies at least n//2 + 1 consecutive slots starting at index first, then nums[first + n//2] must also equal target. The bounds check first + n // 2 < n prevents an index-out-of-range.

Dependencies

Imports: bisect.bisect_left from the standard library — a C-implemented binary search that returns the leftmost insertion point for target.

Imported by: check-if-a-number-is-majority-element-in-a-sorted-array/test_solution.py directly. The large "Imported By" list in the prompt is an artifact of the test harness structure (shared test infrastructure), not actual runtime dependents.

Flow

1. Compute n = len(nums).

2. bisect_left(nums, target)first: the index where target first appears (or would be inserted if absent).

3. Compute first + n // 2 — the position that must also be target if it's a majority element.

4. Guard: first + n // 2 < n ensures we don't read past the array.

5. Check: nums[first + n // 2] == target confirms the run of target values is long enough.

6. Both conditions are combined with and (short-circuit), so the index access is safe.

Example walkthrough: nums = [2,4,5,5,5,5,5,6,6], target = 5, n = 9.

Invariants

Error Handling

None. The function assumes valid input per the problem constraints. An empty nums would have n = 0, first = 0, and 0 + 0 < 0 is False, so it correctly returns False. If target is absent, bisect_left returns an insertion point where nums[first + n//2] != target (or the bounds check fails), so it returns False.

Topics to Explore

Beliefs