423. Check if Array is Sorted and Search

EasyBinary SearchArrayBinary Search

Given an array nums and an integer target, first verify the array is sorted in non-decreasing order. If sorted, use binary search to find target and return its index. If not sorted, return -2. If sorted but target not found, return -1.

Input: An integer array nums and an integer target.

Output: -2 if unsorted, -1 if not found, else index of target.

Examples

Example 1
Input: [1,3,5,7,9], 5
Output: 2
Explanation: Array is sorted. Binary search finds 5 at index 2.
Example 2
Input: [1,3,2,7,9], 3
Output: -2
Explanation: Array is not sorted (3>2), return -2.
Example 3
Input: [2,4,6,8,10], 5
Output: -1
Explanation: Array is sorted but 5 not found, return -1.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →