@@ -56,6 +56,50 @@ fun findLength(nums1: IntArray, nums2: IntArray): Int {
56
56
* ** Space Complexity** : ` O(m * n) ` for 2D dp array.
57
57
58
58
### Dynamic Programming (Space Optimization)
59
- > TODO: to implement when reviewing.
59
+ Since every ` dp[i][j] ` depends only on ` dp[i - 1][j - 1] ` , we can store as ` dp[2][j] ` for space optimization.
60
+
61
+
62
+ ``` js
63
+ j, j+ 1
64
+ i X
65
+ \
66
+ i+ 1 Y
67
+
68
+ n1 = " 23"
69
+ n2 = " 123"
70
+
71
+ 0 , 1 , 2 , 3 // index
72
+ 0 0 X
73
+ 1 Y // Y depends on X
74
+ 2 Z // Z depends on Y
75
+
76
+ // So we store for X, Y row, then shift to Y, Z row.
77
+ ```
78
+
79
+ ``` kotlin
80
+ fun findLength (nums1 : IntArray , nums2 : IntArray ): Int {
81
+ // TODO: Here we should use the shorter array as the first array to reduce the space complexity.
82
+ val dp = Array (2 ) { IntArray (nums2.size + 1 ) { 0 }
83
+ val max = 0
84
+ for (i in 1 .. nums1.size) {
85
+ for (j in 1 .. nums2.size) {
86
+ if (nums1[i - 1 ] == nums2[j - 1 ]) {
87
+ dp[0 ][j] = 1 + dp[1 ][j - 1 ]
88
+ }
89
+ max = maxOf(max, dp[0 ][j])
90
+ }
91
+
92
+ // shift dp[1] to dp[0]
93
+ for (j in 0 .. nums2.size) {
94
+ dp[1 ][j] = dp[0 ][j]
95
+ // This is nessary to clean up the value of dp[0][j] for next iteration.
96
+ dp[0 ][j] = 0
97
+ }
98
+ }
99
+ return max
100
+ }
101
+ ```
102
+
103
+ * ** Time Complexity ** : `O (m * n)` where `m` and `n` are the length of two strings, respectively.
104
+ * ** Space Complexity ** : `O (min(n, n)`.
60
105
61
- > TODO: There are some different optimal solution, try to practice.
0 commit comments