Data Structures & AlgorithmsHardTCS NQT · Infosys pattern
Matrix chain order for dimensions 5 × 10, 10 × 3, 3 × 12, 12 × 5, 5 × 50, 50 × 6. What is the minimum number of scalar multiplications?
Matrix chain order for dimensions 5 × 10, 10 × 3, 3 × 12, 12 × 5, 5 × 50, 50 × 6. What is the minimum number of scalar multiplications?
p = [5, 10, 3, 12, 5, 50, 6]
n = len(p) - 1
m = [[0] * n for _ in range(n)]
for L in range(2, n + 1):
for i in range(n - L + 1):
j = i + L - 1
m[i][j] = min(m[i][k] + m[k+1][j] + p[i] * p[k+1] * p[j+1] for k in range(i, j))
print(m[0][n - 1], m[0][1])- A. 2010 150
- B. 2010 600
- C. 2110 150
- D. 1800 150
Correct answer: A. 2010 150
m[0][1] = 5·10·3 = 150 for the first pair. Filling the table by chain length gives 2010 for the whole chain. Trying all parenthesisations is Catalan(n − 1) – exponential – while the DP is O(n³).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- What is printed? (level-order traversal of the BST built from these keys) python def insert(t, k): if t is None: return [k, None, None] i…
- What is printed? (inorder successor in a BST) python def insert(t, k): if t is None: return [k, None, None] i = 1 if k < t[0] else 2 t[i]…
- What is printed? (heap sort on a small array, showing the array after the first extraction) python def sift(a, i, n): while 2 i + 1 < n: c…
- What is printed? (trie: count distinct prefixes / nodes) python words = ["tea", "ten", "to", "inn", "in", "i"] root, nodes = {}, 0 for w…
- What is printed? (count connected components with DFS on an adjacency list) python n = 8 edges = [(0, 1), (1, 2), (3, 4), (5, 6), (6, 7)…
- Floyd–Warshall on 4 vertices. What is the shortest distance from 0 to 3, and from 3 to 1? python INF = float('inf') d = [[0, 3, INF, 7]…