
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Shortest Unsorted Continuous Subarray in Python
Suppose we have an integer array, we need to find one continuous subarray such that, if we only sort that subarray in ascending order, then the whole array will be sorted too. We need to find the shortest such subarray and output its length. So if the array is [2,6,4,8,10,9,15], then the output will be 5. The array 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 the length of res
if nums[i] is not same as res[i], then insert i into the r
if the length of r is 0, then return 0, if the length of r is 1, then return 1
return the last element of r – first element of r + 1
Example (Python)
Let us see the following implementation to get a 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
- Related Articles
- Continuous Subarray Sum in C++
- Length of shortest unsorted array in JavaScript
- Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted in Python
- Program to find shortest subarray to be removed to make array sorted in Python
- Shortest Subarray with Sum at Least K in C++
- JavaScript program for Shortest Un-Ordered SubarrayJavaScript program for Shortest Un-Ordered Subarray
- Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit in C++
- Maximum Subarray in Python
- Shortest Completing Word in Python
- Maximum Product Subarray in Python
- Shortest Path with Alternating Colors in Python
- Program to find length of shortest supersequence in Python
- Find Shortest distance from a guard in a Bankin Python
- Program to find shortest cycle length holding target in python
- Program to find maximum subarray min-product in Python

Advertisements