Measure the Smallest Segment that Needs Sorting

Quick Overview

Measure the Smallest Segment that Needs Sorting. Return the minimum length of one contiguous segment whose nondecreasing sort would make all of nums nondecreasing.

Measure the Smallest Segment that Needs Sorting

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Return the minimum length of one contiguous segment whose nondecreasing sort would make all of nums nondecreasing. Return zero when nums is already sorted. ```cpp class Solution { public: int findUnsortedSubarray(vector<int>& nums); }; ``` ### Examples **Example 1:** ```text nums = [1,5,3,4,6] Output: 3 Explanation: Sorting [5,3,4] fixes the whole array. ``` **Example 2:** ```text nums = [2,2,2] Output: 0 Explanation: Equality is allowed in sorted order. ``` ### Constraints - Input length: 1..10000. Every number lies in -100000..100000. ### Clarifying Questions Find inversion boundaries that account for distant values and recognize an already-sorted array. ```hint Read the boundary condition Which values are smaller than something already seen from the left? ``` ### Contract considerations Find inversion boundaries that account for distant values and recognize an already-sorted array. ### Optional follow-up Can you solve the problem in O(n) time?

Overview: Measure the Smallest Segment that Needs Sorting. Return the minimum length of one contiguous segment whose nondecreasing sort would make all of nums nondecreasing.

Google logo
Google
Jul 6, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Return the minimum length of one contiguous segment whose nondecreasing sort would make all of nums nondecreasing. Return zero when nums is already sorted.

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums);
};

Examples

Example 1:

nums = [1,5,3,4,6]
Output: 3
Explanation: Sorting [5,3,4] fixes the whole array.

Example 2:

nums = [2,2,2]
Output: 0
Explanation: Equality is allowed in sorted order.

Constraints

  • Input length: 1..10000. Every number lies in -100000..100000.

Clarifying Questions Guidance

Find inversion boundaries that account for distant values and recognize an already-sorted array.

Contract considerations

Find inversion boundaries that account for distant values and recognize an already-sorted array.

Optional follow-up

Can you solve the problem in O(n) time?