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
Difficulty
and has an acceptance rate of about 61% (400k+ submissions).
Typical patterns to solve this problem:
- Array
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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 |
Videos
Solved On The Same Day
- problem 2363: Merge Similar Items
- problem 2418: Sort the People
- problem 2441: Largest Positive Integer That Exists With Its Negative
- problem 2506: Count Pairs Of Similar Strings
- problem 2716: Minimize String Length
- problem 2744: Find Maximum Number of String Pairs
- problem 2374: Node With Highest Edge Score
- problem 2442: Count Number of Distinct Integers After Reverse Operations
- problem 2491: Divide Players Into Teams of Equal Skill
- problem 2554: Maximum Number of Integers to Choose From a Range I
- problem 2780: Minimum Index of a Valid Split
- problem 2933: High-Access Employees
Extra
- 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