Leetcode #2143: Choose Numbers From Two Arrays in Range
In this guide, we solve Leetcode #2143 Choose Numbers From Two Arrays in Range in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given two 0-indexed integer arrays nums1 and nums2 of length n. A range [l, r] (inclusive) where 0 <= l <= r < n is balanced if: For every i in the range [l, r], you pick either nums1[i] or nums2[i].
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Array, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: nums1 = [1,2,5], nums2 = [2,6,3]
Output: 3
Explanation: The balanced ranges are:
- [0, 1] where we choose nums2[0], and nums1[1].
The sum of the numbers chosen from nums1 equals the sum of the numbers chosen from nums2: 2 = 2.
- [0, 2] where we choose nums1[0], nums2[1], and nums1[2].
The sum of the numbers chosen from nums1 equals the sum of the numbers chosen from nums2: 1 + 5 = 6.
- [0, 2] where we choose nums1[0], nums1[1], and nums2[2].
The sum of the numbers chosen from nums1 equals the sum of the numbers chosen from nums2: 1 + 2 = 3.
Note that the second and third balanced ranges are different.
In the second balanced range, we choose nums2[1] and in the third balanced range, we choose nums1[1].
Python Solution
class Solution:
def countSubranges(self, nums1: List[int], nums2: List[int]) -> int:
n = len(nums1)
s1, s2 = sum(nums1), sum(nums2)
f = [[0] * (s1 + s2 + 1) for _ in range(n)]
ans = 0
mod = 10**9 + 7
for i, (a, b) in enumerate(zip(nums1, nums2)):
f[i][a + s2] += 1
f[i][-b + s2] += 1
if i:
for j in range(s1 + s2 + 1):
if j >= a:
f[i][j] = (f[i][j] + f[i - 1][j - a]) % mod
if j + b < s1 + s2 + 1:
f[i][j] = (f[i][j] + f[i - 1][j + b]) % mod
ans = (ans + f[i][s2]) % mod
return ans
Complexity
The time complexity is O(n·m) (typical). The space complexity is O(n·m) or optimized.
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.