Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern
Problem: Set the whole row and column to 0 for every 0 in a matrix.
Problem: Set the whole row and column to 0 for every 0 in a matrix.
def zeroes(m):
R, C = len(m), len(m[0])
rows = {r for r in range(R) for c in range(C) if m[r][c] == 0}
cols = {c for r in range(R) for c in range(C) if m[r][c] == 0}
for r in range(R):
for c in range(C):
if r in rows or c in cols: m[r][c] = 0
return sum(map(sum, m))
print(zeroes([[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]))What is printed?- A. 0
- B. 26
- C. 18
- D. 13
Correct answer: D. 13
Record the zero rows and columns first, then clear – clearing while scanning would spread zeros from cells that were not originally 0 (and could wipe the whole matrix). Row 0 and columns 0 and 3 become zero, leaving 4 + 5 + 3 + 1 = 13. O(R·C) time; the O(1)-space version stores the markers in the first row and column.
More Coding Interview Problems questions
- Problem: Find the element that appears more than n/2 times (guaranteed to exist) using Boyer–Moore voting. java static int majority(int[]…
- Problem: Sort an array of 0s, 1s and 2s in one pass (Dutch national flag). cpp void sort012(vector<int>& a) { int lo = 0, mid = 0, hi =…
- Problem: Find the next lexicographic permutation of a digit list in place. python def nextperm(a): i = len(a) - 2 while i >= 0 and a[i] >=…
- Problem: Count pairs of songs whose total duration is divisible by 60. python def pairs60(t): cnt = [0] 60; res = 0 for x in t: r = x % 60…
- Problem: Find the length of the longest subarray with equal numbers of 0s and 1s. python def longesteq(a): first = {0: -1}; bal = best = 0…
- Problem: Find all elements that appear more than ⌊n/3⌋ times. python def overthird(a): c1 = c2 = None; n1 = n2 = 0 for x in a: if x == c1…