Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Count paths from the top-left to the bottom-right of a grid moving only right or down, where 1 marks a blocked cell.
Problem: Count paths from the top-left to the bottom-right of a grid moving only right or down, where 1 marks a blocked cell.
def paths(g):
R, C = len(g), len(g[0])
dp = [0] * C; dp[0] = 1
for r in range(R):
for c in range(C):
if g[r][c]: dp[c] = 0
elif c: dp[c] += dp[c - 1]
return dp[-1]
print(paths([[0, 0, 0], [0, 1, 0], [0, 0, 0]]), paths([[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]))What is printed?- A. 2 10
- B. 6 10
- C. 2 20
- D. 3 10
Correct answer: A. 2 10
dp[c] holds paths to the current cell: from above (old dp[c]) plus from the left (dp[c − 1]). The centre block leaves only the two border routes. A free 3 × 4 grid has C(5, 2) = 10 paths. O(R·C) time, O(C) space.
More Coding Interview Problems questions
- Problem: Find the minimum path sum from the top-left to the bottom-right of a cost grid (moves: right or down). python def minpath(g): R…
- Problem: Count the ways to decode a digit string where 'A' = 1 … 'Z' = 26. python def decode(s): prev2, prev1 = 1, (1 if s[0] != '0' else…
- Problem: Decide whether a string can be split into words from a dictionary. python def wb(s, words): W = set(words); dp = [True] + [False]…
- Problem: Return the maximum product of a contiguous subarray (values may be negative or zero). python def maxprod(a): hi = lo = best =…
- Problem: Can an array be split into two subsets with equal sums? python def cansplit(a): s = sum(a) if s % 2: return False reach = 1 for x…
- Problem: Return the length of the longest palindromic subsequence (not substring). python def lps(s): n = len(s); dp = [[0] n for in…