Back to articles
Search in Rotated Sorted Array
How-ToTools

Search in Rotated Sorted Array

via Dev.to TutorialJeyaprasad R

In this task, I worked on finding a target element in a rotated sorted array using an efficient approach. A rotated sorted array is one that was originally sorted but then rotated at some pivot point. For example: [4, 5, 6, 7, 0, 1, 2] What I Did I created a function search that: Takes an array nums and a target value Returns the index of the target if found Returns -1 if the target does not exist How I Solved It Instead of using a linear search , I used a modified binary search . Approach I used two pointers: low starting from index 0 high starting from index n - 1 Then I repeatedly calculated the middle index mid . Logic Behind It At each step: 1. Check if Middle is Target If nums[mid] == target , return mid 2. Identify the Sorted Half Case 1: Left Half is Sorted If nums[low] <= nums[mid] Check if target lies between low and mid : YES → move high = mid - 1 NO → move low = mid + 1 Case 2: Right Half is Sorted Otherwise, the right half is sorted Check if target lies between mid and hig

Continue reading on Dev.to Tutorial

Opens in a new tab

Read Full Article
2 views

Related Articles