Back to Practice Dashboard
Competitive ProgrammingEasy
Search in Almost Sorted Array
Learn how to solve the 'Search in Almost Sorted Array' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Easy
Write a function search_almost_sorted(arr, target) that searches for a target value in an almost sorted array arr. An almost sorted array is one in which an element that should be at index i in a fully sorted array can instead be at index i-1, i, or i+1. Return the 0-based index of the target if found, otherwise return -1.
Constraints
- •1 <= len(arr) <= 10^5
- •-10^9 <= arr[i], target <= 10^9
- •All elements in arr are unique.
Examples
Example 1
Input
search_almost_sorted([10, 3, 40, 20, 50, 80, 70], 40)
Output
2
Explanation
40 is at index 2 (which is its correct position in a fully sorted version).
Example 2
Input
search_almost_sorted([10, 3, 40, 20, 50, 80, 70], 90)
Output
-1
Explanation
90 does not exist in the array.
Need a Hint?
Analyze the input constraints. Try sorting first (O(n log n)) or using a hash map/set to track seen elements in O(n) time.
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.