Ctrl K

Disorder Only Between Neighbors

Medium
You are given an array perm of length n, a permutation of the numbers 0 to n - 1. A pair of positions i < j is out of order when perm[i] > perm[j]. Count two things: - how many such pairs the array has in total; - how many of them are neighbors, that is j = i + 1. Return True if the two counts are equal (in other words, every out-of-order pair is a pair of neighbors), and False otherwise.
Example 1
perm=[1, 0, 3, 2] → True

The out-of-order pairs are (1, 0) and (3, 2), and both are neighbors. There are 2 disordered pairs in total and 2 adjacent ones.

Example 2
perm=[0, 2, 3, 1] → False

The pairs (2, 1) and (3, 1) are out of order, 2 in total, but only (3, 1) are neighbors.

Example 3
perm=[0] → True
Constraints
  • 1 ≤ n ≤ 10⁵
  • perm is a permutation of 0, 1, …, n - 1
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsTurn a Square Clockwise MediumPostfix Calculator MediumRoll an Array to the Right MediumPrimes Below a Bound MediumNth Number Built From Given Primes Medium
loading Python…
Input
perm=[1, 0, 3, 2]
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 110 tests on the server, hidden ones included.