Problem 775

Abstract / Summary

Check if reversing any sublist can sort the list and if any adjacent pair is out of order.

Note

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

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
19 lines | 550 bytes | submitted May 8, 2024 | GitHub   21% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 43% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
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 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.

written by openai gpt

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.

written by google gemini

Code Quality

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

Complexity Analysis

not analyzed yet

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 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
31 links | 19 authors | 8 languages

Videos

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

Solved On The Same Day

4 solutions   May 8, 2024

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