Validate sorted input or fail fast

Validate sorted input or fail fast

Hard Java Exceptions 21 views
Explanation Complexity

Problem Statement

Task: if array is not sorted, throw IllegalStateException. Else return true.

Input Format

An integer n (size of array)
Then n integers (array elements)

Output Format

If array is sorted (non-decreasing) → return true
If not sorted → throw IllegalStateException

Example

4
1 5 3 7
IllegalStateException

Constraints

• n ≥ 0

• Sorted means: a[i] >= a[i-1] for all valid i

Concept Explanation

We check every adjacent pair.
If any element is smaller than the previous one,
array is not sorted.

Step-by-Step Explanation

1.Read n and the array.

2.Loop from i = 1 to n-1:

• If a[i] < a[i-1]:

• Throw new IllegalStateException("Array not sorted").

3.If loop completes without exception:

• Return true.

Concept Explanation

We check every adjacent pair.
If any element is smaller than the previous one,
array is not sorted.

Step-by-Step Explanation

1.Read n and the array.

2.Loop from i = 1 to n-1:

• If a[i] < a[i-1]:

• Throw new IllegalStateException("Array not sorted").

3.If loop completes without exception:

• Return true.

Input / Output Format

Input Format
An integer n (size of array)
Then n integers (array elements)
Output Format
If array is sorted (non-decreasing) → return true
If not sorted → throw IllegalStateException
Constraints
• n ≥ 0

• Sorted means: a[i] >= a[i-1] for all valid i

Examples

Input:
4 1 5 3 7
Output:
IllegalStateException

Example Solution (Public)

Java
static boolean requireSorted(int[] a){for(int i=1;i<a.length;i++) if(a[i]<a[i-1]) throw new IllegalStateException();return true;}

Official Solution Code

static boolean requireSorted(int[] a){for(int i=1;i<a.length;i++) if(a[i]<a[i-1]) throw new IllegalStateException();return true;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.