#718
Maximum Length of Repeated Subarray
MediumArrayBinary SearchDynamic ProgrammingSliding WindowRolling HashHash FunctionDynamic ProgrammingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * m) |
| Space | O(1) | O(n * m) |
💡
Intuition
Time O(n * m)Space O(n * m)
Using dynamic programming, we can store the lengths of common subarrays in a 2D array. This allows us to build on previously computed results, significantly reducing the number of comparisons needed.
⚙️
Algorithm
3 steps- 1Step 1: Create a 2D array dp where dp[i][j] represents the length of the longest common subarray ending at nums1[i-1] and nums2[j-1].
- 2Step 2: Iterate through both arrays. If nums1[i-1] equals nums2[j-1], set dp[i][j] = dp[i-1][j-1] + 1.
- 3Step 3: Keep track of the maximum value in the dp array as you fill it.
solution.py10 lines
1def findLength(nums1, nums2):
2 m, n = len(nums1), len(nums2)
3 dp = [[0] * (n + 1) for _ in range(m + 1)]
4 max_length = 0
5 for i in range(1, m + 1):
6 for j in range(1, n + 1):
7 if nums1[i - 1] == nums2[j - 1]:
8 dp[i][j] = dp[i - 1][j - 1] + 1
9 max_length = max(max_length, dp[i][j])
10 return max_lengthℹ
Complexity note: The time complexity is O(n * m) because we fill a 2D array of size n by m, where n and m are the lengths of the two arrays. The space complexity is also O(n * m) due to the storage of the dp array.
- 1Dynamic programming can significantly reduce the number of comparisons needed.
- 2Understanding how to build on previous results is crucial in many DSA problems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.