- Related Questions & Answers
- Program to find longest equivalent sublist after K increments in Python
- Program to find shortest string after removing different adjacent bits in Python
- Program to find number of sublists we can partition so given list is sorted finally in python
- Program to count number of switches that will be on after flipping by n persons in python
- Program to count minimum k length sublist that can be flipped to make all items of list to 0 in Python
- Program to arrange cards so that they can be revealed in ascending order in Python
- Program to merge two sorted list to form larger sorted list in Python
- Program to find length of shortest supersequence in Python
- Program to find length of longest distinct sublist in Python
- Program to check number of requests that will be processed with given conditions in python
- Find the minimum value to be added so that array becomes balanced in C++
- Program to find shortest cycle length holding target in python
- Program to find the number of unique integers in a sorted list in Python
- Program to find length of contiguous strictly increasing sublist in Python
- Program to find the maximum sum of circular sublist in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a list of numbers called nums, we have to find the length of the shortest sublist in num, if the sublist is sorted, then the entire array nums will be sorted in ascending order.

So, if the input is like nums = [1,2,5,4,9,10], then the output will be 2, as Sorting the sublist [4, 3] would get us [0, 1, 3, 4, 8, 9]

To solve this, we will follow these steps −

- f:= -1, l:= -1
- lst:= sort the list nums
- for i in range 0 to size of nums, do
- if nums[i] is not same as lst[i], then
- if f is same as -1, then
- f := i

- otherwise,
- l := i

- if f is same as -1, then

- if nums[i] is not same as lst[i], then
- if l is same as -1 and f is same as -1, then
- return 0

- return l - f + 1

Let us see the following implementation to get better understanding −

class Solution: def solve(self, nums): f=-1 l=-1 lst=sorted(nums) for i in range(len(nums)): if nums[i]!=lst[i]: if f == -1: f=i else: l=i if l == -1 and f == -1: return 0 return l-f+1 ob = Solution() print(ob.solve([1,2,5,4,9,10]))

[1,2,5,4,9,10]

2

Advertisements