Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 718 · LCS

Maximum Length of Repeated Subarray

LeetCode 718 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Like LCS, but a mismatch resets to 0 and the answer is the max cell, not the corner.

நடுத்தரம்ArrayBinary SearchDynamic ProgrammingSliding WindowRolling Hash

நான் Maximum Length of Repeated Subarray (LeetCode 718) ஐ இப்படித் தீர்த்தேன் — LCS பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

A common subarray must be contiguous, so a mismatch breaks the run completely. dp[i][j] = length of the common run starting at nums1[i] and nums2[j]: on a match it extends the run starting one step later; on a mismatch it's 0. The best run anywhere is the answer.

Approach

  1. 1

    Fill dp from the ends of both arrays backwards.

  2. 2

    Match: dp[i][j] = 1 + dp[i+1][j+1], and update the best length.

  3. 3

    Mismatch: dp[i][j] = 0.

  4. 4

    Return the best length seen.

நான் எப்படித் தீர்த்தேன்

TabulationPythonO(m·n) time · O(m·n) space
class Solution:
    def findLength(self, nums1: List[int], nums2: List[int]) -> int:
        m=len(nums1)
        n=len(nums2)
        dp=[[0]*(n+1) for _ in range(m+1)]
        max_length = 0
        for i in range(m-1,-1,-1):
            for j in range(n-1,-1,-1):
                if nums1[i]==nums2[j]:
                    dp[i][j]=1+dp[i+1][j+1]
                    max_length=max(max_length,dp[i][j])
                else:
                    dp[i][j]=0
        return max_length
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Maximum Length of Repeated Subarray — அடிக்கடி கேட்கப்படும் கேள்விகள்

Maximum Length of Repeated Subarray பின்னாலுள்ள intuition என்ன?

A common subarray must be contiguous, so a mismatch breaks the run completely. dp[i][j] = length of the common run starting at nums1[i] and nums2[j]: on a match it extends the run starting one step later; on a mismatch it's 0. The best run anywhere is the answer.

Maximum Length of Repeated Subarray (LeetCode 718) ஐ எப்படித் தீர்ப்பது?

1. Fill dp from the ends of both arrays backwards. 2. Match: dp[i][j] = 1 + dp[i+1][j+1], and update the best length. 3. Mismatch: dp[i][j] = 0. 4. Return the best length seen.

Maximum Length of Repeated Subarray இன் time மற்றும் space complexity என்ன?

Time: O(m · n). Space: O(m · n). (Accepted approach: Tabulation.)

Maximum Length of Repeated Subarray இல் பொதுவான தவறுகள் என்ன?

Don't take max of neighbours on a mismatch — that would compute a subsequence instead.