Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the 2D slice for dynamic programming.
DSA Go
dp := make([][]int, len(s1)+1) for i := range dp { dp[i] = make([]int, [1]) }
Attempts:
3 left
💡 Hint
Common Mistakes
Using len(s1)+1 for columns instead of len(s2)+1
Forgetting the +1 for base case initialization
✗ Incorrect
We create a 2D slice with rows for s1 and columns for s2, so each row has length len(s2)+1.
2fill in blank
mediumComplete the code to check if characters match in the LCS logic.
DSA Go
if s1[i-1] == [1][j-1] { dp[i][j] = dp[i-1][j-1] + 1 }
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing s1[i-1] with s1[j-1]
Using dp or lcs instead of s2
✗ Incorrect
We compare characters from s1 and s2 at positions i-1 and j-1 respectively.
3fill in blank
hardFix the error in updating dp when characters do not match.
DSA Go
else { dp[i][j] = [1](dp[i-1][j], dp[i][j-1]) }
Attempts:
3 left
💡 Hint
Common Mistakes
Using min instead of max
Using sum which is incorrect for LCS
✗ Incorrect
When characters don't match, we take the maximum of the two possible subsequences.
4fill in blank
hardFill both blanks to correctly backtrack the LCS string.
DSA Go
if s1[i-1] == s2[j-1] { lcs = string(s1[i-1]) + lcs i = i [1] 1 } else if dp[i-1][j] [2] dp[i][j-1] { i = i - 1 } else { j = j - 1 }
Attempts:
3 left
💡 Hint
Common Mistakes
Using + instead of - for i decrement
Using < instead of > in comparison
✗ Incorrect
We move i back by 1 when characters match, and compare dp[i-1][j] > dp[i][j-1] to decide direction.
5fill in blank
hardFill all three blanks to complete the LCS function return statement and helper function call.
DSA Go
func longestCommonSubsequence(s1, s2 string) string {
dp := make([][]int, len(s1)+1)
for i := range dp {
dp[i] = make([]int, len(s2)+1)
}
for i := 1; i <= len(s1); i++ {
for j := 1; j <= len(s2); j++ {
if s1[i-1] == s2[j-1] {
dp[i][j] = dp[i-1][j-1] + 1
} else {
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
}
}
}
return [1](s1, s2, dp, len(s1), len(s2))
}
func [2](s1, s2 string, dp [][]int, i, j int) string {
if i == 0 || j == 0 {
return ""
}
if s1[i-1] == s2[j-1] {
return [3](s1, s2, dp, i-1, j-1) + string(s1[i-1])
}
if dp[i-1][j] > dp[i][j-1] {
return lcsHelper(s1, s2, dp, i-1, j)
}
return lcsHelper(s1, s2, dp, i, j-1)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using longestCommonSubsequence instead of helper function
Using max instead of recursive call
✗ Incorrect
The main function calls lcsHelper to build the LCS string recursively.
