KatInterview

Shortest Block to Cut for a Non-Decreasing Remainder

Arrays & HashingAuto-graded · 25 test cases
MediumAuto-gradedArrays & Hashingtwo-pointersarraysprefix-suffix

Last updated

Find the shortest contiguous block whose removal leaves a non-decreasing array, using sorted prefix/suffix boundaries and two pointers, with a smallest-start tie-break.

You are given an integer list nums. You may delete one contiguous block of elements nums[L..R] (both ends inclusive). The elements left over keep their original relative order and are joined together.

Find the shortest block whose deletion leaves a non-decreasing sequence (each element is greater than or equal to the one before it). Return it as the list [L, R].

Rules:

  • If nums is already non-decreasing (this includes an empty list and a single element), nothing needs to be deleted. Return [-1, -1].
  • Otherwise the block must be non-empty, with 0 <= L <= R < len(nums).
  • Deleting the block may leave an empty remainder, or only a prefix, or only a suffix. All of these count as non-decreasing.
  • If several blocks share the minimum length, return the one with the smallest L. This is the same as choosing the lexicographically smallest pair [L, R], because equal lengths mean a smaller L gives a smaller R.
  • Equal neighbours are allowed after the join, so a kept prefix value may equal the first kept suffix value.

Your solution should run in O(n) time with O(1) extra space.

Constraints

  • 0 <= len(nums) <= 2 * 10^5
  • Each element is an integer, and may be negative or large in magnitude.
  • The return value is a list of two integers [L, R], or [-1, -1] if no deletion is needed.

Examples

Example 1

Input: find_shortest_cut([1, 2, 3, 10, 4, 2, 3, 5])

Output: [2, 4]

Example 2

Input: find_shortest_cut([5, 4, 3, 2, 1])

Output: [0, 3]

Example 3

Input: find_shortest_cut([1, 2, 3])

Output: [-1, -1]

Hints

Hint 1

After deleting a block, what remains is a prefix of the array plus a suffix of the array. Both must already be non-decreasing on their own, so find the longest sorted prefix and the longest sorted suffix first.

Hint 2

If you keep the prefix up to index i, the kept suffix must start at some index j inside the sorted suffix with nums[j] >= nums[i]. For a fixed i you want the smallest such j.

Hint 3

As i grows, nums[i] never decreases within the sorted prefix, so the best j never moves left. Use a single pointer for j, and only replace the best answer on a strictly shorter block so the smallest L wins ties. Do not forget i = -1, which means keeping no prefix.