From d14a1a05c8a9304a78242fcdbfa6d2d4d40726b4 Mon Sep 17 00:00:00 2001 From: Dave Dietrick Date: Fri, 10 Jan 2025 15:02:20 -0500 Subject: [PATCH] Added section about binary search in interview prep --- docs/interview/ds/array.md | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/docs/interview/ds/array.md b/docs/interview/ds/array.md index aa386e1..f8c9855 100644 --- a/docs/interview/ds/array.md +++ b/docs/interview/ds/array.md @@ -1,8 +1,8 @@ # Arrays -An array is a linear collection of data values that are accessible at numbered indices, starting at 0. Arrays are stored in continguous memory. There are two types of arrays, **static** and **dynamic**. **Static** arrays are fixed length, meaning they will always take up the same amount of memory. +An array is a linear collection of data values that are accessible at numbered indices, starting at 0. Arrays are stored in continguous memory. There are two types of arrays, **static** and **dynamic**. **Static** arrays are fixed length, meaning they will always take up the same amount of memory. -**Dynamic** arrays can change in size, and in statically typed languages like C++ there are called vectors. **Dynamic** arrays allocate double the amount of memory you have specified to account for adding values to it. When you reach a full array, then it allocates a new array with double the size and copies the values over which is an O(n) operation. +**Dynamic** arrays can change in size, and in statically typed languages like C++ there are called vectors. **Dynamic** arrays allocate double the amount of memory you have specified to account for adding values to it. When you reach a full array, then it allocates a new array with double the size and copies the values over which is an O(n) operation. ## Complexity @@ -15,4 +15,34 @@ An array is a linear collection of data values that are accessible at numbered i - Removing from middle: O(n) - Removing from end: O(1) - Copying: O(n) -- Traversing (including mapping, filtering, etc): O(n) \ No newline at end of file +- Traversing (including mapping, filtering, etc): O(n) + +## Common Algorithms + +### Binary Search + +Binary search is useful when trying to find values in a sorted array. It works by picking a middle point to check, and then dividing the array in half based on whether the value is too big or small. + +```python +def binarySearch(nums, target): + """ + :type nums: List[int] + :type target: int + :rtype: int + """ + if len(nums) == 0: + return -1 + + left, right = 0, len(nums) - 1 + while left <= right: + mid = (left + right) // 2 + if nums[mid] == target: + return mid + elif nums[mid] < target: + left = mid + 1 + else: + right = mid - 1 + + # End Condition: left > right + return -1 +```