- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted in Python
Suppose we have a given unsorted array A[0..n-1] of size n, we have to find the minimum length subarray A[s..e] so that by sorting this subarray the whole array will be sorted. So, if the array is like [2,6,4,8,10,9,15], then the output will be 5. The subarray will be [6,4,8,10,9].
To solve this, we will follow these steps −
res := sort the nums as an array
ans := 0
set r as a linked list
for i in range 0 to length of res
if nums[i] is not same as res[i], then insert i into the r
if length of r is 0, then return 0, if length of r is 1, then return 1
return last element of r – first element of r + 1
Example
Let us see the following implementation to get better understanding −
class Solution(object): def findUnsortedSubarray(self, nums): res = sorted(nums) ans = 0 r = [] for i in range(len(res)): if nums[i] != res[i]: r.append(i) if not len(r): return 0 if len(r) == 1: return 1 return r[-1]-r[0]+1 ob1 = Solution() print(ob1.findUnsortedSubarray([2,6,4,8,10,9,15]))
Input
[2,6,4,8,10,9,15]
Output
5
Advertisements