Sponsored
Sponsored
We can sort a copy of the array and compare it with the original array to determine the boundaries of the subarray that needs to be sorted.
Sort the array and compare with the original array from the start and end to find the first and last mismatch. These mismatches will give the boundaries of the subarray.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(n) for storing a copy of the array.
1#include <stdio.h>
2#include <stdlib.h>
3
4int findUnsortedSubarray(int* nums, int numsSize) {
5 int* sorted = (int*)malloc(numsSize * sizeof(int));
6 for (int i = 0; i < numsSize; i++) {
7 sorted[i] = nums[i];
8 }
9 qsort(sorted, numsSize, sizeof(int), compare);
10 int start = 0, end = numsSize - 1;
11 while (start < numsSize && nums[start] == sorted[start]) {
12 start++;
13 }
14 while (end > start && nums[end] == sorted[end]) {
15 end--;
16 }
17 free(sorted);
18 return start < end ? end - start + 1 : 0;
19}
20
21int compare(const void* a, const void* b) {
22 return (*(int*)a - *(int*)b);
23}
24
25int main() {
26 int arr[] = {2, 6, 4, 8, 10, 9, 15};
27 int length = findUnsortedSubarray(arr, 7);
28 printf("%d\n", length); // Output: 5
29 return 0;
30}
The function makes a copy of the array, sorts it, and then compares it with the original array. It finds the first and last indices where the two arrays differ. If such indices are found, the length of the subarray is returned; otherwise, it's zero.
In this approach, we aim to find the shortest unsorted subarray by utilizing two passes to find the minimum and maximum deviations from the sorted order.
The range between these two boundaries produces the result.
Time Complexity: O(n) as it processes the array twice.
Space Complexity: O(1) since no additional space is used apart from basic variables.
JavaScript code uses two variables to track the maximum and minimum indices whenever a deviation is detected during array traversal. Hence the difference gives the result.