And it’s Done.
You now can enroll to our interview prep platform.
Choose a plan that suites you and get started with your interview prep
https://t.co/OKSvy75KI5
✅ Iterative Approach
⚬ Create a function that takes the array & target, and returns [first_index, last_index].
⚬ Init result array: [-1, -1].
⚬ Loop through the array (i from 0 to n-1)
⚬ If arr[i] == target & result[0] == -1: Set result[0] = i (first occurrence).
⚬ If arr[i] == target & result[0] != -1: Set result[1] = i (update last occurrence).
⚬ Return the result by the loop's end.
⏳Time Complexity: O(n) – Loops over all n elements.
💾 Space Complexity: O(1) – Just a fixed 2-element array
Binary search for peak:
1⃣Calculate the middle.
2⃣If value at the middle is bigger than middle+1 index value, the peak will be anywhere to the left, continue in that range.
3⃣else peak value will be somewhere on right.
4⃣Narrow range till found.
Time: O(log n), Space: O(1).
1⃣ The iterative approach to finding a peak element in an array involves scanning through each element one by one.
2⃣If you find a larger element, you update the index. By the end, you have the index of a peak element.
👉Time complexity is O(n), and space complexity is O(1).