Skip to content

ORIGINAL CODING QUESTION

Smallest sorting repair span

Return the length of the smallest contiguous segment whose sorting makes the whole array nondecreasing. Return 0 if already sorted.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

n, then n integer values. Print one integer as described.

Constraints

1 ≤ n ≤ 200; -100 ≤ value ≤ 100. Inputs contain exactly the stated values.

Example 1

Input

5 1 4 3 2 5

Output

3

Sorting positions 1..3 repairs the array.

Example 2

Input

3 1 2 3

Output

0

No repair is needed.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Compare with where values belong in sorted order.

Hint 2

Locate the first and last mismatched positions.

Hint 3

A linear approach can use running extrema from both ends.

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →