Python 0775.py
class Solution:
def isIdealPermutation(self, nums: List[int]) -> bool:
# count local inversions
loc = 0
for a, b in zip(nums, nums[1 :]):
loc += a > b
# count global inversions
glo = 0
seen = []
for n in nums:
bigger = bisect_left(seen, n)
glo += len(seen) - bigger
if glo > loc:
break
insort(seen, n) # happens most likely at the end, which should be quite fast
return loc == glo
Difficulty
and has an acceptance rate of about 43% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
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 Solution.isIdealPermutation method determines whether a given integer sequence has the same number of global inversions as local inversions. A local inversion is a pair of adjacent elements that are out of order, while a global inversion is any pair of indices i < j where nums[i] > nums[j]. The method returns True when the two counts match, indicating that every global inversion is also a local one.
Key Steps
Counting Local Inversions
The first phase walks through the array once, comparing each element with its immediate successor. For each adjacent pair where the left element exceeds the right, the local inversion counter is incremented.
loc = 0
for a, b in zip(nums, nums[1:]):
loc += a > b
The use of zip creates an iterator over consecutive pairs without allocating an intermediate list, keeping the operation memory-efficient.
Counting Global Inversions
The second phase builds a sorted view of the elements seen so far. For each new element n, the code finds the insertion point using binary search (bisect_left). The number of previously seen elements larger than n equals the total size of the seen list minus the insertion index. This quantity is added to the global inversion counter.
glo = 0
seen = []
for n in nums:
bigger = bisect_left(seen, n)
glo += len(seen) - bigger
if glo > loc:
break
insort(seen, n)
The loop stops early if the global count exceeds the local count, because the final equality can no longer be achieved. After processing all elements (or breaking early), the method returns the comparison of the two counters.
Edge Cases Handled
When the input list is empty or contains a single element, the zip in the local-inversion loop produces no pairs, leaving loc at zero. The global-inversion loop iterates over the empty or single-element list, and seen remains empty or receives one element, resulting in glo also being zero. Consequently, the method correctly returns True.
If the array is already sorted in ascending order, every adjacent comparison yields False, so loc stays zero. The binary-search insertion always finds the insertion point at the end of seen, meaning len(seen) - bigger is zero for each element; glo remains zero and the early-break condition never triggers. The final equality holds.
For a completely reversed permutation, each adjacent pair contributes to loc, and each new element is smaller than all previously seen elements, causing len(seen) - bigger to equal the current size of seen. The global counter grows rapidly, and the early-break condition (glo > loc) will be met after a few iterations, terminating the loop early without processing the entire list.
The algorithm also works correctly when the input contains duplicate values, even though a true permutation would not. The binary search correctly identifies the leftmost insertion point, and the calculation of larger elements (len(seen) - bigger) still reflects the number of prior elements greater than the current one.
Performance Optimizations
The implementation leverages Python’s built-in bisect_left and insort functions, which are written in C and provide fast binary-search insertion into a sorted list. Because the list seen is maintained in sorted order, locating the count of larger preceding elements is a logarithmic-time operation per element.
The early-exit check if glo > loc: break prevents unnecessary work when the global count already surpasses the local count, which can happen early for many non-ideal permutations. This short-circuiting reduces the number of binary-search insertions and keeps the algorithm efficient on inputs that quickly violate the equality condition.
The local-inversion count uses a simple generator expression over adjacent pairs, avoiding extra data structures and keeping the overhead minimal. The combination of a single pass for local inversions and an incremental, early-terminating pass for global inversions yields a solution that scales well with input size while staying within the constraints of pure Python.
ELI5 - Simplified Explanation
Imagine a long row of numbered blocks sitting on the floor. Sometimes a bigger block sits right before a smaller one, which is like a little hiccup in the line. This code goes through the row to count those little hiccups where two blocks sitting next to each other are in the wrong order.
After counting those neighbors, the code looks for bigger hiccups where any high number sits anywhere before a lower number, even if they are far apart. It keeps a special box to remember the numbers it has already seen so it can quickly figure out how many bigger blocks are hiding behind the ones it is looking at.
By comparing the number of small hiccups between neighbors to the number of all possible hiccups, the code checks if the total count stays exactly the same. It is like seeing if the only messy spots in the whole room are just those small ones between neighbors.
Code Quality
Complexity Analysis
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 | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | |||||
| LeetcodeHelp | C++ | Python | Java | ||||||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| gouthampradhan | Java | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| wisdompeak | C++ | ||||||||
| YuriSpiridonov | Python | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| gouthampradhan | Java | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| ruoru | Rust | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| wisdompeak | C++ | ||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 777: Swap Adjacent in LR String
- problem 1157: Online Majority Element In Subarray
- problem 1163: Last Substring in Lexicographical Order
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