Maximum Length of Repeated Subarray
Maximum Length of Repeated Subarray is a medium dynamic programming problem solved with the strings pattern.
The best approach, optimal (1d dp, right-to-left sweep), runs in O(n · m) time and O(m) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (compare every alignment start) up.
Problem
Given two integer arrays nums1 and nums2, return the length of the longest block of consecutive elements that appears in both arrays, in the same order and without gaps.
For example, [2, 9, 5] is a common block of [4, 7, 2, 9, 5] and [1, 2, 9, 5, 7], while [4, 5] is not, because its elements are not next to each other in the first array. If no value is shared, the answer is 0.
Examples
Example 1
- Input
nums1 = [4, 7, 2, 9, 5], nums2 = [1, 2, 9, 5, 7]- Output
3- Why
- The block [2, 9, 5] appears contiguously in both arrays.
Example 2
- Input
nums1 = [6, 6, 6], nums2 = [6, 6]- Output
2- Why
- nums2 is only two long, and [6, 6] appears in nums1.
Example 3
- Input
nums1 = [1, 2, 3], nums2 = [4, 5]- Output
0- Why
- The arrays share no value at all.
Constraints
1 <= nums1.length, nums2.length <= 10000 <= nums1[i], nums2[i] <= 100
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (compare every alignment start) | O(n · m · min(n, m)) | O(1) |
| Better (2D DP on block endings) | O(n · m) | O(n · m) |
| Optimal (1D DP, right-to-left sweep) | O(n · m) | O(m) |
1Brute force (compare every alignment start)
O(n · m · min(n, m))n · m start pairs, each walk up to min(n, m) steps.O(1)Only counters.For every pair of start positions (i, j) with equal values, walk forward while the arrays keep matching and record the longest walk.
- Loop i over nums1 and j over nums2.
- Set k = 0 and increase it while i + k and j + k are in range and nums1[i + k] == nums2[j + k].
- best = max(best, k).
class Solution {
public int findLength(int[] nums1, int[] nums2) {
int n = nums1.length, m = nums2.length, best = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int k = 0;
while (i + k < n && j + k < m && nums1[i + k] == nums2[j + k]) k++;
best = Math.max(best, k);
}
}
return best;
}
}class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
n, m, best = len(nums1), len(nums2), 0
for i in range(n):
for j in range(m):
k = 0
while i + k < n and j + k < m and nums1[i + k] == nums2[j + k]:
k += 1
best = max(best, k)
return bestclass Solution {
public:
int findLength(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size(), m = nums2.size(), best = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int k = 0;
while (i + k < n && j + k < m && nums1[i + k] == nums2[j + k]) k++;
best = max(best, k);
}
}
return best;
}
};function findLength(nums1, nums2) {
const n = nums1.length, m = nums2.length;
let best = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
let k = 0;
while (i + k < n && j + k < m && nums1[i + k] === nums2[j + k]) k++;
best = Math.max(best, k);
}
}
return best;
}2Better (2D DP on block endings)
O(n · m)Each cell is filled in O(1).O(n · m)The full table is stored.dp[i][j] is the length of the longest common block ending at nums1[i - 1] and nums2[j - 1]. Matching values extend the diagonal neighbour by one; different values break the block. The answer is the largest cell.
- Create dp of size (n + 1) x (m + 1), filled with 0.
- For i in 1..n and j in 1..m: if nums1[i - 1] == nums2[j - 1], dp[i][j] = dp[i - 1][j - 1] + 1 and update best.
- Return best.
class Solution {
public int findLength(int[] nums1, int[] nums2) {
int n = nums1.length, m = nums2.length, best = 0;
int[][] dp = new int[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (nums1[i - 1] == nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
best = Math.max(best, dp[i][j]);
}
}
}
return best;
}
}class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
n, m, best = len(nums1), len(nums2), 0
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
if nums1[i - 1] == nums2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
best = max(best, dp[i][j])
return bestclass Solution {
public:
int findLength(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size(), m = nums2.size(), best = 0;
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (nums1[i - 1] == nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
best = max(best, dp[i][j]);
}
}
}
return best;
}
};function findLength(nums1, nums2) {
const n = nums1.length, m = nums2.length;
let best = 0;
const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= m; j++) {
if (nums1[i - 1] === nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
best = Math.max(best, dp[i][j]);
}
}
}
return best;
}3Optimal (1D DP, right-to-left sweep)
O(n · m)Same n · m cells as the table version.O(m)One row of length m + 1.Row i only needs row i - 1 at column j - 1. Keep one array dp of size m + 1 and fill each row with j going from m down to 1, so dp[j - 1] still holds the previous row's value when dp[j] is computed. Cells with different values must be reset to 0.
- Create dp of size m + 1, filled with 0.
- For i in 1..n, for j from m down to 1: dp[j] = (nums1[i - 1] == nums2[j - 1]) ? dp[j - 1] + 1 : 0, and update best.
- Return best.
class Solution {
public int findLength(int[] nums1, int[] nums2) {
int n = nums1.length, m = nums2.length, best = 0;
int[] dp = new int[m + 1];
for (int i = 1; i <= n; i++) {
for (int j = m; j >= 1; j--) {
dp[j] = nums1[i - 1] == nums2[j - 1] ? dp[j - 1] + 1 : 0;
best = Math.max(best, dp[j]);
}
}
return best;
}
}class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
m, best = len(nums2), 0
dp = [0] * (m + 1)
for a in nums1:
for j in range(m, 0, -1):
if a == nums2[j - 1]:
dp[j] = dp[j - 1] + 1
if dp[j] > best:
best = dp[j]
else:
dp[j] = 0
return bestclass Solution {
public:
int findLength(vector<int>& nums1, vector<int>& nums2) {
int n = nums1.size(), m = nums2.size(), best = 0;
vector<int> dp(m + 1, 0);
for (int i = 1; i <= n; i++) {
for (int j = m; j >= 1; j--) {
dp[j] = nums1[i - 1] == nums2[j - 1] ? dp[j - 1] + 1 : 0;
best = max(best, dp[j]);
}
}
return best;
}
};function findLength(nums1, nums2) {
const n = nums1.length, m = nums2.length;
let best = 0;
const dp = new Array(m + 1).fill(0);
for (let i = 1; i <= n; i++) {
for (let j = m; j >= 1; j--) {
dp[j] = nums1[i - 1] === nums2[j - 1] ? dp[j - 1] + 1 : 0;
if (dp[j] > best) best = dp[j];
}
}
return best;
}Edge cases to test
- No common value: the answer is 0
- One array is entirely contained in the other
- Long runs of the same value, where many alignments match partially
- A common subsequence that is not contiguous must not count
Hints
Hint 1
Fix a start i in nums1 and j in nums2 and count how long the two arrays agree from there. That is correct but slow.
Hint 2
Let dp[i][j] be the length of the longest common block that ends exactly at nums1[i - 1] and nums2[j - 1]. If those two values are equal, it extends dp[i - 1][j - 1] by one; otherwise it is 0.
Hint 3
Each row only reads the previous row, one column to the left. Sweep j from right to left and a single 1D array is enough.
FAQ
What is the best time complexity for Maximum Length of Repeated Subarray?
Optimal (1D DP, right-to-left sweep) runs in O(n · m) time and O(m) extra space. Same n · m cells as the table version.
Which pattern does Maximum Length of Repeated Subarray use?
It is a dynamic programming problem that uses the strings pattern. Other problems with the same pattern: Edit Distance, Longest Common Subsequence, Longest Palindromic Subsequence.
Is there a brute force solution for Maximum Length of Repeated Subarray?
Yes. Brute force (compare every alignment start) takes O(n · m · min(n, m)) time and O(1) space. For every pair of start positions (i, j) with equal values, walk forward while the arrays keep matching and record the longest walk.
Which edge cases should I test for Maximum Length of Repeated Subarray?
No common value: the answer is 0; One array is entirely contained in the other; Long runs of the same value, where many alignments match partially; A common subsequence that is not contiguous must not count.