Competitive ProgrammingEasy

Search in Almost Sorted Array

Detailed guide and Python implementation for the 'Search in Almost Sorted Array' problem.

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?
Consider using Searching & Sorting-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.