5. Search in an Almost Sorted Array
The problem can be found at the following link: 🔗 Question Link
🧩 Problem Description
Given a sorted integer array arr[] consisting of distinct elements, where some elements of the array are moved to either of the adjacent positions, i.e. arr[i] may be present at arr[i-1] or arr[i+1]. Given an integer target. You have to return the index (0-based) of the target in the array. If target is not present return -1.
📘 Examples
Example 1:
Input:
arr[] = [10, 3, 40, 20, 50, 80, 70], target = 40
Output:
2
Explanation:
Index of 40 in the given array is 2.
Example 2:
Input:
arr[] = [10, 3, 40, 20, 50, 80, 70], target = 90
Output:
-1
Explanation:
90 is not present in the array.
Example 3:
Input:
arr[] = [-20], target = -20
Output:
0
Explanation:
-20 is the only element present in the array.
🔒 Constraints
$1 \leq arr.size() \leq 10^5$
$-10^9 \leq arr[i] \leq 10^9$
✅ My Approach
Linear Search
This is the most straightforward searching technique where we iterate through the array from the beginning to the end, comparing each element to the target. The search stops as soon as we find the element, returning its index. If we reach the end of the array without finding the target, we return -1.
Algorithm Steps:
Start from the first element of the array (
i = 0).Compare each element
arr[i]with thetarget.If a match is found, return the index
i.If the loop completes without a match, return
-1.
🧮 Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where
nis the number of elements in the array. In the worst case, we may have to check every element.Expected Auxiliary Space Complexity: O(1), as we do not use any extra space beyond a few variables.
🧠 Code (C++)
🧑💻 Code (Java)
🐍 Code (Python)
🧠 Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: 📬 Any Questions?. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated