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?
  1. A. 3
  2. B. 2
  3. C. 4
  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

Exams that ask this topic