🚀 AI-Powered Mock Interviews Launching Soon - Join the Waitlist for Early Access

codingmedium

Implement a function to calculate precision and recall for a binary classification model, given predicted and actual labels as lists. Optimize for time and space complexity.

Interview

How to structure your answer

To calculate precision and recall, first count true positives (TP), false positives (FP), and false negatives (FN) by iterating through predicted and actual labels. Precision is TP/(TP+FP), recall is TP/(TP+FN). Optimize by iterating once through the lists, using O(1) space for counters. Handle edge cases like division by zero by returning 0.0. This ensures O(n) time complexity and O(1) space complexity.

Sample answer

The solution involves a single pass through the predicted and actual labels to count TP, FP, and FN. For each pair, if actual is 1 and predicted is 1, TP increases. If actual is 1 but predicted is 0, FN increases. If actual is 0 but predicted is 1, FP increases. Precision and recall are calculated using these counts. Time complexity is O(n) due to the single loop, and space complexity is O(1) as only counters are stored. Edge cases like zero denominators are handled by returning 0.0 to avoid errors. This approach ensures efficiency and correctness for binary classification metrics.

Key points to mention

  • • Precision and recall definitions
  • • Time complexity O(n) with single traversal
  • • Space complexity O(1) with constant variables

Common mistakes to avoid

  • ✗ Using multiple loops instead of single traversal
  • ✗ Ignoring zero-division errors
  • ✗ Misapplying formula (e.g., using FN instead of FP for precision)