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
n
is 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++)
class Solution {
public:
int findTarget(vector<int>& arr, int target) {
for(int i = 0; i < arr.size(); ++i)
if(arr[i] == target) return i;
return -1;
}
};
๐งโ๐ป Code (Java)
class Solution {
public int findTarget(int[] arr, int target) {
for(int i=0;i<arr.length;i++) if(arr[i]==target) return i;
return -1;
}
}
๐ Code (Python)
class Solution:
def findTarget(self, arr, target):
for i in range(len(arr)):
if arr[i] == target: return i
return -1
๐ง 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