Day 11
Day 11
Problem: Given an m×nm \times nm×n binary matrix mat, return the distance of the nearest
0 for each cell. The distance between two adjacent cells is 1.
Solution: To solve this, we can use a multi-source Breadth-First Search (BFS). The BFS will
start from all 0's in the matrix and propagate the distance to 1's. Here's the implementation in
Python:
python
Copy code
from collections import deque
def updateMatrix(mat):
m, n = len(mat), len(mat[0])
dist = [[float('inf')] * n for _ in range(m)]
queue = deque()
return dist
# Test Cases
print(updateMatrix([[0,0,0],[0,1,0],[0,0,0]])) # [[0,0,0],[0,1,0],[0,0,0]]
print(updateMatrix([[0,0,0],[0,1,0],[1,1,1]])) # [[0,0,0],[0,1,0],[1,2,1]]
Problem: Merge k sorted linked-lists into one sorted linked-list and return it.
Solution: To solve this, we can use a Min-Heap to efficiently merge the linked lists. Here is
the implementation:
python
Copy code
import heapq
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeKLists(lists):
heap = []
dummy = ListNode()
curr = dummy
while heap:
val, node = heapq.heappop(heap)
curr.next = ListNode(val)
curr = curr.next
if node.next:
heapq.heappush(heap, (node.next.val, node.next))
return dummy.next
# Test Case
list1 = build_list([1,4,5])
list2 = build_list([1,3,4])
list3 = build_list([2,6])
result = mergeKLists([list1, list2, list3])
print_list(result) # 1->1->2->3->4->4->5->6->None
Problem: Given two integer arrays arr1 and arr2, return the minimum number of
operations needed to make arr1 strictly increasing by replacing elements in arr1 with
elements from arr2.
Solution: This problem can be solved using Dynamic Programming with Binary Search.
Here is the implementation:
python
Copy code
from bisect import bisect_right
def makeArrayIncreasing(arr1, arr2):
arr2.sort()
dp = {-1: 0}
# Test Case
print(makeArrayIncreasing([1,5,3,6,7], [1,3,2,4])) # 1
Problem: Given two sorted arrays nums1 and nums2, return the median of the two sorted
arrays with an overall run time complexity of O(log(m+n))O(\log (m+n))O(log(m+n)).
Solution: We can solve this problem using a binary search approach. Here is the
implementation:
python
Copy code
def findMedianSortedArrays(nums1, nums2):
A, B = nums1, nums2
if len(A) > len(B):
A, B = B, A
m, n = len(A), len(B)
Problem: Given two strings a and b, return the minimum number of times you should repeat
string a so that string b is a substring of it.
Solution: To solve this, we can repeatedly append a to itself and check if b becomes a
substring of it. Here is the implementation:
python
Copy code
def repeatedStringMatch(a, b):
count = 1
repeated_a = a
while len(repeated_a) < len(b):
repeated_a += a
count += 1
if b in repeated_a:
return count
if b in (repeated_a + a):
return count + 1
return -1
# Test Case
print(repeatedStringMatch("abcd", "cdabcdab")) # 3
6. Four Sum
Problem: Given an array nums of n integers, return an array of all unique quadruplets
[nums[a], nums[b], nums[c], nums[d]] such that nums[a] + nums[b] + nums[c] +
nums[d] == target.
Solution: To solve this, we can use a combination of two-pointer technique with sorting.
Here is the implementation:
python
Copy code
def fourSum(nums, target):
nums.sort()
result = []
n = len(nums)
return result
# Test Cases
print(fourSum([1,0,-1,0,-2,2], 0)) # [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
print(fourSum([2,2,2,2,2], 8)) # [[2,2,2,2]]
7. Missing Number
Problem: Given an array nums containing n distinct numbers in the range [0, n], return the
only number in the range that is missing from the array.
Solution: To solve this, we can use the formula for the sum of the first n natural numbers.
Here is the implementation:
python
Copy code
def missingNumber(nums):
n = len(nums)
total_sum = n * (n + 1) // 2
array_sum = sum(nums)
return total_sum - array_sum
# Test Case
print(missingNumber([3,0,1])) # 2
8. Majority Element
Solution: This problem can be solved using the Boyer-Moore Voting Algorithm. Here is the
implementation:
python
Copy code
def majorityElement(nums):
count = 0
candidate = None
return candidate
# Test Case
print(majorityElement([3,2,3])) # 3
print(majorityElement([2,2,1,1,1,2,2])) # 2
Problem: Given an n x n integer matrix grid, generate an integer matrix maxLocal of size
(n - 2) x (n - 2) such that maxLocal[i][j] is equal to the largest value of the 3 x 3
matrix in grid centered around row i + 1 and column j + 1.
Solution: To solve this, we can iterate through the grid and compute the maximum value for
each 3 x 3 subgrid. Here is the implementation:
python
Copy code
def largestLocal(grid):
n = len(grid)
maxLocal = [[0] * (n - 2) for _ in range(n - 2)]
return maxLocal
# Test Case
print(largestLocal([[9,9,8,1],[5,6,2,6],[8,2,6,4],[6,2,2,2]])) #
[[9,9],[8,6]]
Problem: Given the head of a linked list, return the list after sorting it in ascending order.
Solution: To solve this, we can use the merge sort algorithm for linked lists. Here is the
implementation:
python
Copy code
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def sortList(head):
if not head or not head.next:
return head
mid = getMid(head)
left = sortList(head)
right = sortList(mid)
def getMid(head):
slow, fast = head, head.next
while fast and fast.next:
slow = slow.next
fast = fast.next.next
mid = slow.next
slow.next = None
return mid
# Test Case
head = build_list([4,2,1,3])
sorted_head = sortList(head)
print_list(sorted_head) # 1->2->3->4->None