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.