Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Move from the top-left to the bottom-right cell of a height grid (4 directions). The effort of a route is the largest absolute height difference between consecutive cells. Find the minimum effort.
Problem: Move from the top-left to the bottom-right cell of a height grid (4 directions). The effort of a route is the largest absolute height difference between consecutive cells. Find the minimum effort.
import heapq
def effort(h):
R, C = len(h), len(h[0]); best = [[float('inf')] * C for _ in range(R)]
best[0][0] = 0; pq = [(0, 0, 0)]
while pq:
e, r, c = heapq.heappop(pq)
if (r, c) == (R - 1, C - 1): return e
if e > best[r][c]: continue
for x, y in ((r+1, c), (r-1, c), (r, c+1), (r, c-1)):
if 0 <= x < R and 0 <= y < C:
ne = max(e, abs(h[x][y] - h[r][c]))
if ne < best[x][y]: best[x][y] = ne; heapq.heappush(pq, (ne, x, y))
print(effort([[1, 3, 8], [6, 4, 2], [7, 9, 3]]))What is printed?- A. 2
- B. 5
- C. 3
- D. 4
Correct answer: A. 2
Dijkstra with 'max of edges' instead of 'sum'. Route 1 → 3 → 4 → 2 → 3 has steps 2, 1, 2, 1, so its effort is 2; effort 1 is impossible because both first moves (to 3 or 6) already cost at least 2.
More Coding Interview Problems questions
- Problem: n computers and a list of cables. You may unplug any cable and reconnect it elsewhere. Find the minimum number of moves to…
- Problem: A tree on nodes 1..n received one extra edge. Return the LAST edge in the input whose removal leaves a tree (union-find). python…
- Problem: Replace each word of a sentence by its shortest root from a dictionary (if any root is a prefix). python def replace(roots…
- Problem: Find the shortest palindrome obtainable by adding characters only in FRONT of s, using the KMP failure function of s + '#' +…
- Problem: Is s made of one substring repeated two or more times? Trick: check whether s occurs in (s + s) with the first and last…
- Problem: Delete the fewest characters so that no two letters have the same (nonzero) frequency. python from collections import Counter def…