Python 2 lines easy understand solution

  • 14

    Sort the list and check if it's still the same number in the list.

    def findUnsortedSubarray(self, nums):
            is_same = [a == b for a, b in zip(nums, sorted(nums))]
            return 0 if all(is_same) else len(nums) - is_same.index(False) - is_same[::-1].index(False)

  • 2

    Same idea but a one-liner:
    string.strip() method will strip surrounding spaces by default. So we only need to count how many chars left over.

        def findUnsortedSubarray(self, nums):
            return len(''.join(('.', ' ')[m==n] for m, n in zip(sorted(nums), nums)).strip())

  • 0

    Interesting solution.

  • 0

    Another solution. Similar idea:

    res = [i for (i,(a,b)) in enumerate(zip(nums,sorted(nums))) if a!=b]
    return 0 if not res else res[-1]-res[0]+1

  • 0

    super fancy solution

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.