Magicsheet logo

Choose Numbers From Two Arrays in Range

Hard
62.5%
Updated 8/1/2025

Asked by 1 Company

Choose Numbers From Two Arrays in Range

What is this problem about?

You are given two arrays, nums1 and nums2, of the same length nn. For each index ii, you must choose exactly one number: either nums1[i] (which you treat as positive) or nums2[i] (which you treat as negative). You need to find the number of ways to choose one number from each index for a subarray nums[L...R] such that the sum of the chosen numbers is exactly 0.

Why is this asked in interviews?

Adobe uses this "Hard" problem to test your expertise in Dynamic Programming and the "Meet-in-the-middle" or "Target Sum" concepts. It evaluates your ability to handle large search spaces by identifying that the sum of a subarray can be broken down into transitions from previous indices. It’s a test of whether you can optimize O(N3)O(N^3) or O(N2)O(N^2) brute-force logic into a more efficient DP approach.

Algorithmic pattern used

This is a Dynamic Programming problem on subarrays. Since each subarray can start at any index LL, the total number of subarrays is O(N2)O(N^2). For each possible start, you can use DP to track the number of ways to reach a specific sum at each subsequent index. The state dp[i][current_sum] would store the number of ways to reach current_sum using elements from L to i. To avoid O(N2)O(N^2) start points, you can use a single DP that effectively "starts" a new potential sum at every index.

Example explanation

nums1 = [1, 2], nums2 = [1, 2] Possible choices for each index: {+1, -1}, {+2, -2}. Subarrays:

  • [1]: Choices {+1, -1}. Sum 0 occurs for -1? No, we need one from each array. (Actually, for each index ii, you pick nums1[i] or -nums2[i]).
  • Subarray [0...0]: Pick 1 or -1. Sum 0: {(-1)}. (1 way)
  • Subarray [1...1]: Pick 2 or -2. Sum 0: {(-2)}... Wait, the rule is sum of chosen numbers. If choices are {1, -1} and {2, -2}, the combinations for [0, 1] are: (1+2), (1-2), (-1+2), (-1-2). None sum to 0. Total ways: the sum of ways for all possible subarrays.

Common mistakes candidates make

One major mistake is misunderstanding the choice rule—you must pick one number for every index in the chosen range [L,R][L, R]. Another is failing to use a Map for the DP state, which is necessary because the possible sums can be large and sparse. Many candidates also forget to apply a modulo if the number of ways is large.

Interview preparation tip

This is a variation of the "Subset Sum" or "Target Sum" problem. Practice these classic DP problems to become comfortable with "ways to reach sum XX" logic. For subarray problems, remember that you can "reset" the DP or start a new sum at every index.

Similar Questions