binarysearch_dsa
binarysearch_dsa
com/problems/find-peak-element/description/
problem:
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.
Example 1:
Constraints:
solution:
Approach: Modified Binary Search
The key insight is that if the middle element of the array is in a descending slope
(middle element is smaller than its left neighbor), then there must be a peak
element to its left. Similarly, if the middle element is in an ascending slope, a
peak exists to its right.
class Solution {
public int findPeakElement(int[] nums) {
int low = 0;
int high = nums.length - 1;
Explanation:
Calculate mid.
Case 1 (Descending Slope): If nums[mid] < nums[mid + 1], the peak must be on the
right side due to the array's properties. Update low to mid + 1.
Case 2 (Ascending Slope): The peak must be on the left side (or even at mid).
Update high to mid.
Termination: The loop continues until low and high converge on a peak element.
Returning either low or high is valid.
Key Points:
######################################################################
url : https://leetcode.com/problems/search-in-rotated-sorted-array/
problem:
There is an integer array nums sorted in ascending order (with distinct values).
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.
Example 1:
solution:
Approach: Binary Search with Pivot Handling
Find the Pivot (Rotation Point): The rotated array essentially consists of two
sorted subarrays. First, find the index where the rotation occurs (the pivot).
Determine Target Subarray: Once you know the pivot, you can determine in which
sorted subarray the target might exist.
Standard Binary Search: Perform a standard binary search within the appropriate
subarray.
Code Implementation:
Java
Explain
class Solution {
public int search(int[] nums, int target) {
int low = 0;
int high = nums.length - 1;
Finding the Pivot: The loop locates the point where the ascending order "breaks" –
this is the point of rotation.
Choosing the Subarray: The if condition after finding the pivot determines which
sorted subarray to search based on the target's potential location.
Standard Binary Search: A regular binary search is performed within the selected
subarray.
Key Points:
Logarithmic Time: The combination of two binary search steps gives us O(log n) time
complexity.
Adaptation: This is a clever adaptation of binary search to a modified sorting
scenario.
########################################################
url: https://leetcode.com/problems/search-a-2d-matrix
problem:
You are given an m x n integer matrix matrix with the following two properties:
Example 1:
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-104 <= matrix[i][j], target <= 104
solution:
Approach: Binary Search with Smart Indexing
The insight is to treat the entire matrix as a single sorted array but access its
elements using row and column calculations. Since each row is sorted, and the first
element of each row is larger than the previous row's last element, we can
effectively perform a binary search over the entire matrix space.
Code Implementation:
Java
Explain
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length;
int n = matrix[0].length;
int low = 0;
int high = m * n - 1;
if (midElement == target) {
return true;
} else if (midElement < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return false;
}
}
Use code with caution.
Explanation:
Flatten the Matrix: While we don't explicitly flatten the matrix, we calculate low,
high, and mid to simulate indexes of a single sorted array.
Retrieving Elements: Within the binary search, we use mid / n to find the row and
mid % n to find the column in the original matrix.
Binary Search Logic: Standard binary search comparison guides our search for the
target.
Key Points:
O(log(m * n)) Time Complexity: We perform binary search over conceptually all m * n
elements.
Clever Indexing: Mapping 2D matrix coordinates into a conceptually linear sequence
is what makes this work.
####################################################
url:https://leetcode.com/problems/find-first-and-last-position-of-element-in-
sorted-array/description/
problem: Given an array of integers nums sorted in non-decreasing order, find the
starting and ending position of a given target value.
Example 1:
Constraints:
solution:
Approach: Two Binary Searches
Find Left Boundary: Use binary search to find the leftmost index where the target
can be inserted while maintaining the array's sorted order. If the target is not
found, it doesn't exist in the array.
Find Right Boundary: Similarly, use binary search to find the rightmost index where
the target can be inserted, which essentially means finding the first position of
the number "larger" than the target. Subtract 1 to arrive at the true 'target's
rightmost index.
Code Implementation:
Java
Explain
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] result = {-1, -1};
return result;
}
findBoundary Helper: This function performs a modified binary search to find the
boundaries. The findLeft flag determines if we're searching for the leftmost or
rightmost boundary.
Search Conditions: The conditions in the binary search are specifically tailored to
locate the appropriate insertion points of the target or an element just larger
than target.
Handling Non-Existence: If the left boundary cannot be found or is out of bounds,
the target doesn't exist.
Key Points:
O(log n) Time Complexity: Two binary searches give us logarithmic time complexity.
Conciseness: Using a helper function keeps the core logic of searchRange clean.
#########################################################
url:https://leetcode.com/problems/search-in-rotated-sorted-array-ii/description/
problem: There is an integer array nums sorted in non-decreasing order (not
necessarily with distinct values).
Before being passed to your function, nums is rotated at an unknown pivot index k
(0 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ...,
nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example,
[0,1,2,4,4,4,5,6,6,7] might be rotated at pivot index 5 and become
[4,5,6,6,7,0,1,2,4,4].
Given the array nums after the rotation and an integer target, return true if
target is in nums, or false if it is not in nums.
Example 1:
Constraints:
Follow up: This problem is similar to Search in Rotated Sorted Array, but nums may
contain duplicates. Would this affect the runtime complexity? How and why?
solution:
The core challenge is that the sorted array has been rotated, making a
straightforward binary search unworkable. Also, due to duplicates, it's harder to
determine which half of the array is guaranteed to be sorted.
Java
Explain
class Solution {
public boolean search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
if (nums[mid] == target) {
return true; // Found the target
}
Worst Case: O(N) due to potential shrinking of the window by just one element in
cases with many duplicates.
Average Case: O(log N), akin to binary search when there are fewer duplicates.
############################################################
url: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
description/
Given the sorted rotated array nums of unique elements, return the minimum element
of this array.
Constraints:
n == nums.length
1 <= n <= 5000
-5000 <= nums[i] <= 5000
All the integers of nums are unique.
nums is sorted and rotated between 1 and n times.
solution:
Logic
The key insight is that in a rotated sorted array, there will always be one half
that remains sorted. Here's how we identify the minimum element:
Java
Explain
class Solution {
public int findMin(int[] nums) {
int left = 0;
int right = nums.length - 1;
##################################################################
url:https://leetcode.com/problems/minimum-size-subarray-sum/
problem:
Given an array of positive integers nums and a positive integer target, return the
minimal length of a
subarray
whose sum is greater than or equal to target. If there is no such subarray, return
0 instead.
Example 1:
Constraints:
Follow up: If you have figured out the O(n) solution, try coding another solution
of which the time complexity is O(n log(n)).
solution:
Here's the code for finding the minimal length of a subarray whose sum is greater
than or equal to the target in an array of positive integers:
Java
Explain
class Solution {
public int minSubArrayLen(int target, int[] nums) {
int minLength = Integer.MAX_VALUE;
int sum = 0;
int left = 0;
Space Complexity: O(1), as we only use constant extra space to store variables like
minLength, sum, and left.
###########################################################################
url: https://leetcode.com/problems/search-a-2d-matrix-ii/description/
problem:
Write an efficient algorithm that searches for a value target in an m x n integer
matrix matrix. This matrix has the following properties:
Example 1:
Constraints:
m == matrix.length
n == matrix[i].length
1 <= n, m <= 300
-109 <= matrix[i][j] <= 109
All the integers in each row are sorted in ascending order.
All the integers in each column are sorted in ascending order.
-109 <= target <= 109
solution:
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int rows = matrix.length;
int cols = matrix[0].length;
Explanation:
Understanding the Matrix Structure: Rows are sorted in ascending order from left to
right and columns in ascending order top to bottom.
Starting Point: Begin at the top-right corner. This element gives us some immediate
knowledge:
If matrix[row][col] is less than the target, all elements in the current row are
too small.
If matrix[row][col] is greater than the target, all elements in the current column
are too large.
Smart Movement:
Target Found: If matrix[row][col] matches the target, return true.
Too Large: If the current element is too large, move left (col--) within the same
row.
Too Small: If the current element is too small, move down (row++) within the same
column.
Efficiency:
Time Complexity: O(m + n), where 'm' is the number of rows and 'n' is the number of
columns. In the worst case, we might traverse one complete row and one complete
column.
Key Insight: By starting from the top-right corner, we strategically eliminate
either an entire row or column in each iteration!
#######################################################
url:https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
problem:
Given an n x n matrix where each of the rows and columns is sorted in ascending
order, return the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct
element.
You must find a solution with a memory complexity better than O(n2).
Example 1:
Constraints:
n == matrix.length == matrix[i].length
1 <= n <= 300
-109 <= matrix[i][j] <= 109
All the rows and columns of matrix are guaranteed to be sorted in non-decreasing
order.
1 <= k <= n2
solution:
Approach
Understanding Value Ranges: The smallest element in the matrix is matrix[0][0], and
the largest is matrix[n-1][n-1]. The kth smallest must lie somewhere between these.
Binary Search on Values: Use binary search on the range of possible values in the
matrix, not on indices. We'll calculate a 'mid' value and count how many elements
in the matrix are less than or equal to this 'mid.'
Counting Elements: To efficiently count elements in the matrix that are less than
or equal to 'mid', start from the top-right corner and traverse the matrix in
reverse sorted order.
Code
Java
Explain
class Solution {
public int kthSmallest(int[][] matrix, int k) {
int n = matrix.length;
int lo = matrix[0][0];
int hi = matrix[n - 1][n - 1];
if (count < k) {
lo = mid + 1; // Need to find a larger value
} else {
hi = mid; // The answer could be 'mid' or a smaller value
}
}
return lo;
}
kthSmallest()
Find the range of potential values using lo and hi.
Iteratively perform binary search within this range.
countLessOrEqual: Helper to count how many elements are less than or equal to a
given 'target'.
countLessOrEqual():
Starts from the top-right corner.
If the current element is larger than the 'target', moves to the left (smaller
numbers).
Otherwise, all elements in the current column are smaller; it adds the count and
moves to the right.
Memory Complexity:
We're not storing the full matrix, using only a constant amount of extra space.
This gives us better memory complexity than O(n²).