Program to find shortest subarray to be removed to make array sorted in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array called arr, we have to remove a subarray of arr such that the remaining elements in arr are in non-decreasing order. We have to find the length of the shortest subarray to remove.

So, if the input is like arr = [10,20,30,100,40,20,30,50], then the output will be 3 because we can remove [100, 40, 20] which is smallest subarray of length 3, and by removing these all are in non-decreasing order [10,20,30,30,50].

To solve this, we will follow these steps:

  • n := size of arr
  • arr := insert 0 at the left of arr and infinity at the right of arr
  • A,B := two new empty lists
  • p := 1, q:= size of arr -2
  • M := 0
  • while p <= q, do
    • if arr[p-1] <= arr[p], then
      • insert arr[p] at the end of A
      • p := p + 1
    • otherwise when arr[q] <= arr[q+1], then
      • insert arr[q] at the end of B
      • while A is not empty and last element of A > last element of B, do
        • delete last element from A
      • q := q - 1
    • otherwise,
      • come out from loop
    • M := maximum of M and size of A + size of B
  • return n - M

Let us see the following implementation to get better understanding:

Example

def solve(arr):
   n = len(arr)
   arr = [0] + arr + [float("inf")]
   A,B=[],[]
   p,q=1,len(arr)-2
   M = 0
   while p <= q:
      if arr[p-1] <= arr[p]:
         A.append(arr[p])
         p += 1
      elif arr[q] <= arr[q+1]:
         B.append(arr[q])
         while A and A[-1] > B[-1]:
            A.pop()
         q -= 1
      else:
         break
      M = max(M, len(A)+len(B))
   return n - M
arr = [10,20,30,100,40,20,30,50]
print(solve(arr))

Input

[10,20,30,100,40,20,30,50]

Output

3
raja
Updated on 04-Oct-2021 08:12:57

Advertisements