LeetCode 581. Shortest Unsorted Continuous Subarray (Algorithm Explained)

preview_player
Показать описание


Preparing For Your Coding Interviews? Use These Resources
————————————————————

Other Social Media
----------------------------------------------

Show Support
------------------------------------------------------------------------------

#coding #programming #softwareengineering
Рекомендации по теме
Комментарии
Автор

I see, in 2020 this was a leetcode easy, with time it became medium.

sasageyo
Автор

Hi Nick, nice video. You do not have to code all the time. Walking through the solution is equally good, like in this video. You can save typing time and use it to explain various approaches.

anoopm
Автор

Thanks for doing 24/7 stream. You are the man Nick!

tonidezman
Автор

What if there is a number smaller than the first unsorted number left to right in the unsorted subarray.

shreyasirao
Автор

Haven't gone through video, need to try binary search based solution

vk
Автор

I think I found a solution which only iterates over the array twice.

public class Solution {
public static int findUnsortedSubarray(int[] nums) {
int end = 0;
int max = nums[end];

for (int i=0; i<nums.length; i++) {
if (max <= nums[i]) max = nums[i];
else end = i + 1;
}

int start = nums.length - 1;
int min = nums[start];

for (int i=end-1; i>=0; i--) {
if (min >= nums[i]) min = nums[i];
else start = i;
}

System.out.println("[" + start + ", " + end + "[");

return end - start;
}
}

AaronTheGerman
Автор

I used the first method, damn the second method was also easy but missed it.

nrico
Автор

This code will not work for input [-1, -1, -1, -1]

biharitravelgirl
Автор

actually the flag thing is unnecessary

JasonJasonJasonJason-ps
Автор

Your explanation is incorrect. Read the leetcode explanation given for this solution.

nikhilgupta