Problem 1287

Abstract / Summary

Find the number that appears more than 25 percent in a sorted array.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1287.py

class Solution:
    def findSpecialInteger(self, arr: List[int]) -> int:
        if len(arr) == 1:
            return arr[0]

        have = 0
        prev = -1
        for a in arr:
            if a == prev:
                have += 1
                if have * 4 > len(arr):
                    return a
            else:
                have  = 1
            prev = a
15 lines | 384 bytes | submitted December 11, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 61% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a class Solution with a method findSpecialInteger that receives a list of integers arr. The method returns the element that appears more than a quarter of the total length of the list. The algorithm assumes that the input list is sorted, which allows it to count consecutive occurrences of the same value efficiently. The code handles the trivial case of a single-element list immediately and then proceeds with a linear scan, maintaining a running count of the current value. When the count exceeds the required threshold, the value is returned without further processing.

Key Steps

Initialization

At the start of the method the code checks whether the list contains only one element. In that situation the sole element is, by definition, the special integer and is returned directly.

if len(arr) == 1:
    return arr[0]

Following this guard clause, two variables are introduced: have to store the current run length of identical numbers, and prev to keep the previous element seen. have is initialized to zero and prev to a sentinel value that cannot appear in the list (-1), ensuring the first comparison treats the first element as a new value.

have = 0
prev = -1

Iteration and Counting

The core of the algorithm is a for loop that iterates over each element a in the input list. For each element the code determines whether it matches the previous element. If it does, the run length have is incremented; otherwise the run length is reset to one because a new value has begun.

for a in arr:
    if a == prev:
        have += 1
        ...
    else:
        have = 1
    prev = a

The reset to one (instead of zero) reflects that the current element itself counts as the first occurrence of the new value.

Early Return

Inside the branch where the current element matches the previous one, the algorithm checks whether the accumulated count have satisfies the condition of being more than a quarter of the total number of elements. The test multiplies have by four and compares it to the length of the array. As soon as the condition is true, the method returns the current element, terminating the scan early.

if have * 4 > len(arr):
    return a

Because the list is sorted, once a value reaches the required frequency it cannot be surpassed by any later value, making the early return both correct and efficient.

Edge Cases Handled

The method explicitly addresses the scenario where the input list consists of a single element. By returning that element immediately, it avoids unnecessary iteration and correctly satisfies the definition of a special integer for the minimal input size.

Another implicit edge case is the presence of duplicate values that are not the special integer. The algorithm continues counting each run, resetting the counter whenever a new value appears, thereby ensuring that only a value that truly exceeds the quarter-length threshold triggers a return.

The sentinel initialization of prev to -1 guarantees that the first element is always treated as the start of a new run, even if the list contains negative numbers (the problem domain typically involves non-negative integers, but the sentinel still works because -1 is distinct from any valid element).

Performance Optimizations

The implementation leverages the sorted nature of the input to achieve a single pass over the data. By maintaining only two integer variables (have and prev) and updating them in constant time per element, the algorithm operates with minimal overhead.

The early return condition eliminates the need to examine the remainder of the list once the special integer is found. In the worst case-when the special integer appears near the end of the array-the algorithm still processes each element exactly once, but in typical cases it stops far earlier, reducing the effective runtime.

Using multiplication (have * 4) instead of division to test the quarter-length condition avoids floating-point operations and potential rounding issues, keeping the comparison in the integer domain and thus faster on most processors.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long line of numbered building blocks sitting on the floor. Some of these blocks have the same number printed on them. This code is a clever helper that walks down the line from the start to the end to find if one number appears very often.

First, it checks if there is only one block in the line. If there is, it knows that block is the special one.

If there are more, the helper starts a game of memory to keep track of the blocks. It looks at the first block and remembers what number is on it. As it moves to the next block, it compares the new number to the one it is holding in its memory.

If the number is the same, it adds one to its counter to show it found a matching block. If the number is different, it tosses the old memory away and starts a new count for the new number.

The helper has a secret rule for winning. It checks if the number it is counting appears more than a quarter of the time in the entire line. If the count times four is bigger than the total number of blocks in the line, the helper has found the winner. It then points to that special number and stops the game.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.59 | σ = 1.23

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python C++ Java TS
WalkCCC Python C++ Java
leetcode.ca Python C++ JS Java Go PHP TS
Progiez Python C++ Java
github BigEggStudy C#
DimitrisJim C
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lkwq007 Python
pruthvikp Python
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, PHP, Python, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
DimitrisJim C
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lkwq007 Python
pruthvikp Python
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
31 links | 18 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

13 solutions   December 11, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality