Binary Search
Binary Search is an algorithm that repeatedly divides the search space in half. This searching technique follows the divide and conquer strategy. The search space always reduces to half in every iteration.resulting in a time complexity of O(log(n)), where n is the number of elements.
Condition: Array should be sorted but they can also be applied on monotonic functions where we need to find the monotonically increasing or decreasing.
It works when we need to narrow down the search space in logarithmic time.
We use two pointers, left and right. Take the average of left and right to find the mid element.
Now, we check where we should move our left and right pointers based on the condition.
Mainly, three steps are required to solve a problem:
- Pre-processing: Sort the input if it is not sorted.
- Binary Search: Use two pointers and find the mid to divide the search space, then choose the correct half accordingly.
- Post-processing: Determine the output.
Advantages of Binary Search Algorithm - Binary search is faster than linear search for large data because it cuts the array in half each time, instead of checking each element one by one. This makes it quicker and more efficient.
Limitations: Binary search only works on sorted arrays, so it's not efficient for small unsorted arrays because sorting takes extra time. It also doesn't work as well as linear search for small, in-memory searches.
Applications: It is used to search element in a sorted array with O(log(n)) time complexity and it can also be used to find the smallest or largest element in the array.
Basic Binary Search Code -
Code
def binarySearch(nums, target): if len(nums) == 0: return -1 left, right = 0, len(nums) - 1 while left right return -1
33. Search in Rotated Sorted Array
Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
Example 3:
Input: nums = [1], target = 0
Output: -1
Code
def binarySearch(nums, target): if len(nums) == 0: return -1 left, right = 0, len(nums) - 1 while left right return -1
- Use two pointers, left and right, and iterate until they overlap.
- Find the mid element.
- Since the array is sorted but rotated, we can’t simply compare the left or right elements with the mid.
- First, determine which part left or right is sorted by comparing the mid pointer with the left or right pointer.
- Based on this conclusion, adjust the pointers accordingly.
Time Complexity - O(log(n)) as the search space is getting divided into half in each iteration.
Space Complexity - O(1)
Monotonically Increasing
162. Find Peak Element
A peak element is an element that is strictly greater than its neighbors.
Given a 0-indexed integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in O(log n) time.
Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 5
Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
Code
class Solution: def search(self, nums: List[int], target: int) -> int: left = 0 right = len(nums)-1 while left = nums[left]: # if nums[mid]= nums[left]: if nums[left] <ol> <li>In this type of problem, we need to check for the peak by comparing the left or right element of the mid.</li> <li>This helps determine whether the graph is trending upward or downward.</li> <li>To find the maximum, search the upward slope and explore the right subspace.</li> <li>To find the minimum, search the left subspace</li> </ol> <p><strong>Time Complexity - O(log(n))</strong> as the search space is getting divided into half in each iteration.<br> <strong>Space Complexity - O(1)</strong></p>
The above is the detailed content of Binary Search || Python || Data Structures and Algorithms. For more information, please follow other related articles on the PHP Chinese website!

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

ListsandNumPyarraysinPythonhavedifferentmemoryfootprints:listsaremoreflexiblebutlessmemory-efficient,whileNumPyarraysareoptimizedfornumericaldata.1)Listsstorereferencestoobjects,withoverheadaround64byteson64-bitsystems.2)NumPyarraysstoredatacontiguou

ToensurePythonscriptsbehavecorrectlyacrossdevelopment,staging,andproduction,usethesestrategies:1)Environmentvariablesforsimplesettings,2)Configurationfilesforcomplexsetups,and3)Dynamicloadingforadaptability.Eachmethodoffersuniquebenefitsandrequiresca

The basic syntax for Python list slicing is list[start:stop:step]. 1.start is the first element index included, 2.stop is the first element index excluded, and 3.step determines the step size between elements. Slices are not only used to extract data, but also to modify and invert lists.

Listsoutperformarraysin:1)dynamicsizingandfrequentinsertions/deletions,2)storingheterogeneousdata,and3)memoryefficiencyforsparsedata,butmayhaveslightperformancecostsincertainoperations.

ToconvertaPythonarraytoalist,usethelist()constructororageneratorexpression.1)Importthearraymoduleandcreateanarray.2)Uselist(arr)or[xforxinarr]toconvertittoalist,consideringperformanceandmemoryefficiencyforlargedatasets.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1
Easy-to-use and free code editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
