Data Structures & AlgorithmsHardProduct Company SDE · two pointers OA
Problem: People with weights [3, 2, 2, 1] must cross a river. A boat carries at most 2 people with total weight at most limit = 3, and each boat carries at most two people. What is the minimum number of boats? Run the two-pointer code.
Problem: People with weights [3, 2, 2, 1] must cross a river. A boat carries at most 2 people with total weight at most limit = 3, and each boat carries at most two people. What is the minimum number of boats? Run the two-pointer code.
def boats(p, limit):
p = sorted(p)
i, j = 0, len(p) - 1
cnt = 0
while i <= j:
if p[i] + p[j] <= limit:
i += 1
j -= 1
cnt += 1
return cnt
print(boats([3, 2, 2, 1], 3))What is printed?- A. 3
- B. 2
- C. 4
- D. 5
Correct answer: A. 3
Pairs (1,2) and then 2 alone and 3 alone need three boats, since no two of the heavy people fit together. Pairing the heaviest person with the lightest greedily gives the optimum.
More Coding Interview Problems questions
- Problem: Koko eats bananas from piles [3, 6, 7, 11] and has h = 8 hours. She picks one pile per hour and eats up to k bananas from it…
- Problem: How many primes are there up to 100? Run the sieve. python n = 100 sieve = [True] (n + 1) sieve[0] = sieve[1] = False for i in…
- Problem: How many ways can the digit string '226' be decoded when 1 maps to A, 2 to B, ..., 26 to Z? Run the DP. python s = '226' dp = [1]…
- Problem: Union-find with path compression and union by rank performs m operations on n elements in what amortised time per operation?
- Problem: What is the largest rectangle area that can be formed in a histogram of heights [2, 1, 5, 6, 2, 3]? Use the stack code. python h…
- Problem: What is the minimum number of operations to sort the array [4, 3, 2, 1] using only swaps of adjacent elements? Run the code…