File tree Expand file tree Collapse file tree 2 files changed +56
-0
lines changed
longest-increasing-subsequence Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ // Time Complexity: O(n log n)
2+ // Space Complexity: O(n)
3+
4+ var lengthOfLIS = function ( nums ) {
5+ // array to store the smallest tail of all increasing subsequences of various lengths
6+ let subsequence = [ ] ;
7+
8+ for ( let num of nums ) {
9+ // iterate through each number in the input array
10+ let left = 0 ,
11+ right = subsequence . length ;
12+
13+ // use binary search to find the position of the current number in the subsequence array
14+ while ( left < right ) {
15+ // calculate the middle index
16+ let mid = Math . floor ( ( left + right ) / 2 ) ;
17+ if ( subsequence [ mid ] < num ) {
18+ // move the left boundary to the right
19+ left = mid + 1 ;
20+ } else {
21+ // move the right boundary to the left
22+ right = mid ;
23+ }
24+ }
25+
26+ // if left is equal to the length of subsequence, it means num is greater than any element in subsequence
27+ if ( left === subsequence . length ) {
28+ // append num to the end of the subsequence array
29+ subsequence . push ( num ) ;
30+ } else {
31+ // replace the element at the found position with num
32+ subsequence [ left ] = num ;
33+ }
34+ }
35+
36+ // the length of the subsequence array is the length of the longest increasing subsequence
37+ return subsequence . length ;
38+ } ;
Original file line number Diff line number Diff line change 1+ // Time Complexity: O(m * n) m : the number of rows, n : the number of columns
2+ // Space Complexity: O(m * n)
3+
4+ var uniquePaths = function ( m , n ) {
5+ // dp[i][j] will store the number of unique paths to reach the cell (i, j)
6+ let dp = Array . from ( { length : m } , ( ) => Array ( n ) . fill ( 1 ) ) ;
7+
8+ // iterate through the grid starting from (1, 1)
9+ for ( let i = 1 ; i < m ; i ++ ) {
10+ for ( let j = 1 ; j < n ; j ++ ) {
11+ // to reach (i-1, j) and (i, j-1) because the robot can only move down or right
12+ dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] ;
13+ }
14+ }
15+
16+ // the value at the bottom-right corner of the grid is the number of unique paths
17+ return dp [ m - 1 ] [ n - 1 ] ;
18+ } ;
You can’t perform that action at this time.
0 commit comments