Shortest Unsorted Continuous Subarray
Given an integer array nums, you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order.
Return the shortest such subarray and output its length.
class Solution {
public int findUnsortedSubarray(int[] nums) {
int end = -1;
int max = nums[0];
for(int i = 1; i < nums.length; i++){
if(max > nums[i]){ // the left value is greater then current value
end = i; // mark that index with end
}
else{
max = nums[i];
}
}
int start = 0;
int min = nums[nums.length - 1];
for(int i = nums.length - 2; i >= 0; i--){
if(min < nums[i]){ // the right value is smaller then current value
start = i; // mark that index with start
}
else{
min = nums[i];
}
}
return end - start + 1;
}
}
Related Problems
Given a string s, find the length of the longest substring without repeating characters.
Given a string S and an integer K, return the length of the longest substring of S that contains at most K distinct characters.
Given an array of strings strs, group the anagrams together. You can return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.
Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).
Return intervals after the insertion.
Note that you don't need to modify intervals in-place. You can make a new array and return it.