703126. Sort Unsorted Subarray
Here is a detailed Markdown blog post for the "Sort Unsorted Subarray" problem:
Sort Unsorted Subarray
Slug: length-unsorted-subarray3022
Difficulty: Easy
Id: 703126
Topic Tags: Arrays, Data Structures
Company Tags: Flipkart, Microsoft, MakeMyTrip, Adobe
Summary
Given an array of integers and a subarray (a contiguous portion) within that array, sort the unsorted subarray in-place. The problem does not specify the length of the subarray or if it's already sorted. We will assume we need to find the longest unsorted subarray.
Detailed Explanation
To solve this problem, we can iterate through the array and maintain two pointers: start and end. Initially, both pointers are set to 0. We also keep track of the maximum length of the unsorted subarray.
We start by checking if the subarray from index 0 to end is sorted or not. If it's not sorted (i.e., there's an element that doesn't match the previous one), we update the start pointer to end + 1. We then increment end and repeat the process until start > end.
If at any point, the subarray from start to end is found to be sorted (i.e., all elements are in order), we can safely consider that the unsorted part ends there. We update our maximum length of the unsorted subarray if necessary.
Here's a step-by-step breakdown:
- Initialize
startandendpointers to 0. - Check if the subarray from index 0 to
endis sorted or not. - If it's not sorted, update
starttoend + 1. - Increment
endand repeat step 2 untilstart > end. - If at any point, the subarray from
starttoendis found to be sorted, consider that the unsorted part ends there. - Update our maximum length of the unsorted subarray if necessary.
Time complexity: O(n), where n is the length of the array. Space complexity: O(1) as we're not using any extra space.
Optimized Solutions
Java
public int findLengthUnsortedSubarray(int[] arr) {
int start = 0, end = 0;
for (int i = 1; i < arr.length; i++) {
if (!isSorted(arr, start, i)) {
end = i - 1;
start = i;
}
}
return Math.max(0, end - start + 1);
}
private boolean isSorted(int[] arr, int start, int end) {
for (int i = start; i < end; i++) {
if (arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}