Find and count target-sum subarrays
Company: TikTok
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Given an integer array nums and an integer target, implement:
(
1) a function that returns true if any non-empty contiguous subarray sums to target;
(
2) a function that returns the number of contiguous subarrays whose sum equals target;
(
3) assuming all numbers in nums are non-negative, design an O(n) time, O(
1) extra-space method to find one such subarray (return its start and end indices) and explain how to adapt it to count all such subarrays. For
(
1) and
(
2) also aim for O(n) time. Discuss trade-offs, edge cases (e.g., zeros, negative numbers, large inputs), and prove correctness.
Quick Answer: This question evaluates understanding of contiguous subarray-sum problems, algorithmic techniques for linear-time and constant-extra-space solutions, and the ability to reason about correctness and edge cases such as zeros, negative numbers, and large inputs.