- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Search in Rotated Sorted Array II in Python
Consider we have an array sorted in ascending order. That is rotated at some pivot unknown to us beforehand. For example, if the array is like [0,0,1,2,2,5,6], this might become [2,5,6,0,0,1,2]. We have a target value to search. If that is found in the array, then return true, otherwise return false. So if the array is like [2,5,6,0,0,1,2], and target is 0, then the output will be 0
Let us see the steps −
- low := 0 and high := size of array
- while low < high
- mid := low + (high - low)/2
- if nums[mid] = target, then return true
- if nums[low] = nums[mid] and nums[high - 1] = nums[mid], then
- increase low by 1 and decrease high by 1, and continue for the next iteration
- if nums[low] <= nums[mid], then
- if target >= nums[low] and target &miinus; nums[mid], then high := mid, otherwise low := mid + 1
- Otherwise
- if target <= nums[high - 1] and target > nums[mid], then low := mid + 1, otherwise high := mid
- return false
Let us see the following implementation to get better understanding −
Example
class Solution(object): def search(self, nums, target): low = 0 high = len(nums) while low<high: mid = low + (high-low)//2 if nums[mid] == target: return True if nums[low] == nums[mid] and nums[high-1] == nums[mid]: low +=1 high -=1 continue if nums[low]<=nums[mid]: if target >=nums[low] and target <nums[mid]: high = mid else: low = mid+1 else: if target<=nums[high-1] and target>nums[mid]: low = mid+1 else: high = mid return False ob1 = Solution() print(ob1.search([2,5,6,0,0,1,2], 0))
Input
[2,5,6,0,0,1,2] 0
Output
True
- Related Articles
- Search in Rotated Sorted Array II in C++
- Search in Rotated Sorted Array in Python
- Find Minimum in Rotated Sorted Array II in C++
- C++ program to search an element in a sorted rotated array
- Check if an array is sorted and rotated in Python
- Find Minimum in Rotated Sorted Array in C++
- Program to check whether an array Is sorted and rotated in Python
- Find the Rotation Count in Rotated Sorted array in C++
- Maximum element in a sorted and rotated array in C++
- Check if an array is sorted and rotated in C++
- Convert Sorted Array to Binary Search Tree in Python
- Finding smallest element in a sorted array which is rotated in JavaScript
- Search elements in a sorted object array in Java
- Search in a Sorted Array of Unknown Size in C++
- Count rotations in sorted and rotated linked list in C++

Advertisements