Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vimalvk9/29141773f523861b57c6e07d862b81ad to your computer and use it in GitHub Desktop.
Save vimalvk9/29141773f523861b57c6e07d862b81ad to your computer and use it in GitHub Desktop.
class Solution {
public:
int findUnsortedSubarray(vector<int>& nums) {
vector<int> newNums;
for (int num: nums) {
newNums.push_back(num);
}
sort(newNums.begin(), newNums.end());
int firstMismatchIdx = -1;
int lastMismatchIdx = -1;
for(int i=0; i<nums.size(); i++) {
if (nums[i] != newNums[i]) {
if (firstMismatchIdx == -1) {
firstMismatchIdx = i;
}
lastMismatchIdx = i;
}
}
if (firstMismatchIdx == -1 && lastMismatchIdx == -1) {
return 0;
}
return (lastMismatchIdx - firstMismatchIdx + 1);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment