![]() |
VOOZH | about |
Given an array where difference between adjacent elements is 1, write an algorithm to search for an element in the array and return the position of the element (return the first occurrence).
Examples :
Let element to be searched be x
Input: arr[] = {8, 7, 6, 7, 6, 5, 4, 3, 2, 3, 4, 3}
x = 3
Output: Element 3 found at index 7
Input: arr[] = {1, 2, 3, 4, 5, 4}
x = 5
Output: Element 5 found at index 4
A Simple Approach is to traverse the given array one by one and compare every element with given element 'x'. If matches, then return index.
The above solution can be Optimized using the fact that difference between all adjacent elements is 1. The idea is to start comparing from the leftmost element and find the difference between current array element and x. Let this difference be 'diff'. From the given property of array, we always know that x must be at-least 'diff' away, so instead of searching one by one, we jump 'diff'.
Below is the implementation of above idea.
Element 3 is present at index 7
Time Complexity: O(n)
Auxiliary Space: O(1)
Searching in an array where adjacent differ by at most k
The approach of this code is linear search. It iterates through the array and checks if the current element is equal to the target element. If the target element is found, it returns the index of that element. If the target element is not found, it returns -1.
1. Traverse through the array starting from the first element.
2. Compare each element with the given element x.
3. If the element is found, return its index.
4. If the end of array is reached and the element is not found, return -1
7
Time Complexity: O(n) where n is the length of the array.
Auxiliary Space: O(1)