Searching and sorting are fundamental algorithms in computer science, essential for organizing data and optimizing operations across diverse applications. These techniques form the backbone of efficient data manipulation and retrieval, making them critical for performance in software development and technical interviews. Among these, binary search and merge sort are two of the most likely algorithms you might be asked to implement in a coding challenge
Binary search is an efficient algorithm for finding an item in a sorted list of items. It works by repeatedly dividing the search interval in half. If the value of the search key is less than the item in the middle of the interval, the search continues in the lower half, or if greater, in the upper half. This approach reduces the search time to O(logn), making it highly efficient for large data sets.
Now let’s solve this problem Example Problem: Merge Sorted Array
We are given two integer arrays nums1
and nums2
, both sorted in non-decreasing order. The task is to merge nums2
into nums1
such that nums1
becomes a single sorted array (Do not return anything).
The first m
elements of nums1
are valid elements, and the rest of the nums1
array is filled with zeros to accommodate the elements from nums2
. The length of nums1
is m + n
, where n
is the length of nums2
.
nums2
into nums1
. Binary search is used to find the appropriate index to insert elements from nums2
.nums1
and nums2
are already sorted.nums1
, we can avoid overwriting valid elements.nums1
where each element from nums2
should go.nums2
: If nums2
has no elements (n = 0
), nums1
remains unchanged.nums1
: If nums1
initially contains no valid elements (m = 0
), nums1
should become exactly nums2
.nums2
are smaller/larger than nums1
: Ensure the remaining elements are properly handled.nums2
in nums1
.nums2
, use binary search to find the correct insertion position in nums1
.nums1
to create space for the new element.nums2
into the identified position.class Solution(object):
def merge(self, nums1, m, nums2, n):
def binary_search(nums1, left, right, target):
while left <= right:
mid = (left + right) // 2
if nums1[mid] < target:
left = mid + 1
else:
right = mid - 1
return left
# Process each element in nums2
for i in range(n):
# Find the position to insert nums2[i] into nums1
position = binary_search(nums1, 0, m + i - 1, nums2[i])
# Shift elements in nums1 to make space for nums2[i]
nums1[position + 1:m + i + 1] = nums1[position:m + i]
# Insert nums2[i] into nums1
nums1[position] = nums2[i]