Created
November 12, 2024 19:24
-
-
Save SuryaPratapK/7151033b38a37ddeaf97cb9dfd130210 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int findLengthOfShortestSubarray(vector<int>& arr) { | |
int n=arr.size(); | |
int l=0; | |
int r=n-1; | |
//Skip from right | |
while(r>0 and arr[r]>=arr[r-1]) | |
r--; | |
int shortest=r;//Case-1: Remove all elements to the left of r | |
while(l<r){ | |
while(r<n and arr[l]>arr[r]) | |
r++; | |
shortest = min(shortest,r-l-1);//r-l-1: means removing both r & l elements | |
l++; | |
if(arr[l]<arr[l-1]) | |
break; | |
} | |
return shortest; | |
} | |
}; | |
/* | |
//JAVA | |
class Solution { | |
public int findLengthOfShortestSubarray(int[] arr) { | |
int n = arr.length; | |
int l = 0; | |
int r = n - 1; | |
// Skip from right | |
while (r > 0 && arr[r] >= arr[r - 1]) { | |
r--; | |
} | |
int shortest = r; // Case-1: Remove all elements to the left of r | |
while (l < r) { | |
while (r < n && arr[l] > arr[r]) { | |
r++; | |
} | |
shortest = Math.min(shortest, r - l - 1); // r-l-1: means removing both r & l elements | |
l++; | |
if (arr[l] < arr[l - 1]) { | |
break; | |
} | |
} | |
return shortest; | |
} | |
} | |
#Python | |
class Solution: | |
def findLengthOfShortestSubarray(self, arr: list[int]) -> int: | |
n = len(arr) | |
l, r = 0, n - 1 | |
# Skip from right | |
while r > 0 and arr[r] >= arr[r - 1]: | |
r -= 1 | |
shortest = r # Case-1: Remove all elements to the left of r | |
while l < r: | |
while r < n and arr[l] > arr[r]: | |
r += 1 | |
shortest = min(shortest, r - l - 1) # r-l-1: means removing both r & l elements | |
l += 1 | |
if arr[l] < arr[l - 1]: | |
break | |
return shortest | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment