Skip to content

Commit 50897cf

Browse files
feat: implement unsorted subarray algorithm
1 parent f6b0c1f commit 50897cf

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { findUnsortedSubarray } from '../unsorted-subarray';
2+
3+
describe('findUnsortedSubarray', () => {
4+
test('should return 0 for already sorted array', () => {
5+
expect(findUnsortedSubarray([1, 2, 3, 4, 5])).toBe(0);
6+
});
7+
8+
test('should return 0 for empty array', () => {
9+
expect(findUnsortedSubarray([])).toBe(0);
10+
});
11+
12+
test('should return 0 for single element array', () => {
13+
expect(findUnsortedSubarray([1])).toBe(0);
14+
});
15+
16+
test('should return correct length for partially unsorted array', () => {
17+
expect(findUnsortedSubarray([1, 3, 2, 0, 5])).toBe(4);
18+
});
19+
20+
test('should return array length for completely unsorted array', () => {
21+
expect(findUnsortedSubarray([5, 4, 3, 2, 1])).toBe(5);
22+
});
23+
24+
test('should handle array requiring boundary extension', () => {
25+
expect(findUnsortedSubarray([1, 3, 5, 2, 6, 4, 7])).toBe(5);
26+
});
27+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
export const findUnsortedSubarray = (nums: number[]): number => {
2+
if (nums.length <= 1) return 0;
3+
4+
let left = 0;
5+
let right = nums.length - 1;
6+
7+
// Find left boundary
8+
while (left < nums.length - 1 && nums[left] <= nums[left + 1]) {
9+
left++;
10+
}
11+
12+
// Find right boundary
13+
while (right > 0 && nums[right] >= nums[right - 1]) {
14+
right--;
15+
}
16+
// Array is already sorted
17+
if (left === nums.length - 1) return 0;
18+
19+
// Step 3: Find min and max in the subarray
20+
let subarrayMin = Number.MAX_VALUE;
21+
let subarrayMax = Number.MIN_VALUE;
22+
23+
for (let i = left; i <= right; i++) {
24+
subarrayMin = Math.min(subarrayMin, nums[i]);
25+
subarrayMax = Math.max(subarrayMax, nums[i]);
26+
}
27+
28+
// Step 4: Extend boundaries if needed
29+
while (left > 0 && nums[left - 1] > subarrayMin) {
30+
left--;
31+
}
32+
while (right < nums.length - 1 && nums[right + 1] < subarrayMax) {
33+
right++;
34+
}
35+
36+
// Step 5: Return length
37+
return right - left + 1;
38+
};
39+
40+
console.log(findUnsortedSubarray([1, 3, 2, 0, 5])); // Output: 4
41+
console.log(findUnsortedSubarray([1, 2, 3, 4])); // Output: 0

0 commit comments

Comments
 (0)