Certainly! Here are the solutions to the tasks as if I were a student doing homework:
Task 1
To build a Cartesian tree using the given key-priority pairs, we can take advantage of the fact that the keys are sorted. Here's a linear-time algorithm:
- Initialize an empty stack to keep track of the nodes in the Cartesian tree.
- Iterate through the pairs:
- Create a new node for the current (xi, yi).
- While the stack is not empty and the priority of the top node in the stack is less than the current node's priority:
- Pop the top node and make it the right child of the current node.
- If the stack is not empty, the current node becomes the left child of the top node in the stack.
- Push the current node onto the stack.
- The root of the Cartesian tree will be the first node added to the stack.
Here's some pseudocode:
function build_cartesian_tree(pairs):
stack = []
root = null
for (x, y) in pairs:
newNode = createNode(x, y)
while stack is not empty and stack.top().priority < y:
# Pop from stack and make it right child of newNode
right_node = stack.pop()
newNode.right = right_node
if stack is not empty:
# Make newNode left child of top node in stack
stack.top().left = newNode
else:
# If stack is empty, set root
root = newNode
stack.push(newNode)
return root
Task 2
To construct a data structure with O(n^2 log n) construction time that allows O(1) queries for the minimum in any rectangle, we can use a sparse table:
- Create a sparse table
st where st[i][j] will store the minimum value in the submatrix starting from (i, j) up to (i + (2^k - 1), j + (2^k - 1)) for some suitable k.
- Populate this sparse table using dynamic programming.
- Each query can then be resolved in constant time by using the pre-computed minimums.
Pseudocode:
function build_sparse_table(matrix):
n = number of rows in matrix
m = number of columns in matrix
log_table = precomputeLogValues(n, m)
st = array[n][m][log(n)][log(m)]
for i from 0 to n-1:
for j from 0 to m-1:
st[i][j][0][0] = matrix[i][j]
for k in range(1, log(n)+1):
for i from 0 to n - (1 << k):
for j from 0 to m - (1 << k):
st[i][j][k][0] = min(st[i][j][k-1][0], st[i + (1 << (k-1))][j][k-1][0])
return st
function query_min(st, x1, y1, x2, y2):
k1 = log(x2 - x1 + 1)
k2 = log(y2 - y1 + 1)
return min(min(st[x1][y1][k1][k2], st[x2 - (1 << k1) + 1][y1][k1][k2]),
min(st[x1][y2 - (1 << k2) + 1][k1][k2],
st[x2 - (1 << k1) + 1][y2 - (1 << k2) + 1][k1][k2]))
Task 3
To determine if p can become a substring of s by replacing '*' in p, we can use a two-pointer approach:
function canFormSubstring(s, p):
m = length of p
n = length of s
sIndex = 0
pIndex = 0
while sIndex < n:
if pIndex < m and (p[pIndex] == s[sIndex] or p[pIndex] == '*'):
sIndex += 1
pIndex += 1
elif pIndex < m and p[pIndex] == '*':
pIndex += 1
elif pIndex > 0 and p[pIndex - 1] == '*':
pIndex -= 1 # Backtrack if necessary
else:
break
return pIndex == m
Task 4
(a) O(h) extra memory
function fill_right_brother(root):
if root is None:
return
stack = []
current_level = []
stack.push(root)
while stack is not empty:
node = stack.pop()
if current_level is not empty:
current_level[-1].right_brother = node
current_level.append(node)
if node.right is not None:
stack.push(node.right)
if node.left is not None:
stack.push(node.left)
for i in range(len(current_level) - 1):
current_level[i].right_brother = current_level[i + 1]
(b) O(1) extra memory
function fill_right_brother(root):
current = root
while current is not None:
temp = current
while temp is not None:
if temp.left is not None:
if temp.right is not None:
temp.left.right_brother = temp.right
elif temp.right_brother is not None:
temp.left.right_brother = temp.right_brother.left
temp = temp.right_brother
current = current.left
Task 5
(a) O(n log2 n)
- Sort the array and then check for adjacent duplicates.
function find_duplicate(arr):
sort(arr)
for i from 1 to n-1:
if arr[i] == arr[i-1]:
return arr[i] // Found duplicate
return "All different"
(b) O(n)
- Use a cycle detection algorithm, such as Floyd's Tortoise and Hare, given that we can assume the numbers are in the range [1, n]:
function find_duplicate(arr):
tortoise = arr[0]
hare = arr[0]
// Phase 1: Finding the intersection
do {
tortoise = arr[tortoise]
hare = arr[arr[hare]]
} while tortoise != hare
// Phase 2: Finding the entrance to the cycle
tortoise = arr[0]
while tortoise != hare:
tortoise = arr[tortoise]
hare = arr[hare]
return tortoise // Found duplicate
Task 6
To find the shortest non-empty zero-sum segment in O(n), we can keep track of the prefix sum using a hashmap.
function find_zero_sum_segment(a):
sum_map = {}
current_sum = 0
min_length = infinity
start_index = -1
for i from 0 to length(a) - 1:
current_sum += a[i]
if current_sum == 0: // Zero sum from index 0 to i
min_length = i + 1
start_index = 0
if current_sum in sum_map:
prev_index = sum_map[current_sum]
if (i - prev_index) < min_length:
min_length = i - prev_index
start_index = prev_index + 1
else:
sum_map[current_sum] = i
return (start_index, start_index + min_length) if min_length < infinity else "No zero sum segment"
Task 7
To find all occurrences of matrix B in matrix A, we can utilize a sliding window and compare submatrices:
function find_submatrix(A, B):
a_rows = number of rows in A
a_cols = number of columns in A
b_rows = number of rows in B
b_cols = number of columns in B
for i from 0 to a_rows - b_rows:
for j from 0 to a_cols - b_cols:
found = true
for bi from 0 to b_rows:
for bj from 0 to b_cols:
if A[i + bi][j + bj] != B[bi][bj]:
found = false
break
if not found:
break
if found:
print("Submatrix found at top-left corner:", (i, j))
This pseudocode checks every possible starting point for the submatrix B within A and verifies if it matches.
These solutions outline the algorithms and their implementation steps required for each task.