File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 2D-DP
3
+ * Time O(n^2) | Space O(n^2)
4
+ * https://leetcode.com/problems/freedom-trail/
5
+ * @param {string } ring
6
+ * @param {string } key
7
+ * @return {number }
8
+ */
9
+ var findRotateSteps = function ( ring , key ) {
10
+
11
+ const cache = { } ;
12
+
13
+ const dfs = ( ringIdx , keyIdx ) => {
14
+
15
+ const hash = `${ ringIdx } -${ keyIdx } ` ;
16
+ if ( keyIdx === key . length ) return 0 ;
17
+ if ( cache [ hash ] ) return cache [ hash ] ;
18
+
19
+ let min = Infinity ;
20
+ for ( let i = 0 ; i < ring . length ; i ++ ) {
21
+ if ( ring [ i ] === key [ keyIdx ] ) {
22
+ const clockOrAntiClockStep = Math . abs ( i - ringIdx ) ;
23
+ const complementOfClockOrAntiClockStep = ring . length - clockOrAntiClockStep ;
24
+
25
+ min = Math . min ( min ,
26
+ 1 + clockOrAntiClockStep + dfs ( i , keyIdx + 1 ) ,
27
+ 1 + complementOfClockOrAntiClockStep + dfs ( i , keyIdx + 1 )
28
+ ) ;
29
+ }
30
+ }
31
+
32
+ cache [ hash ] = min ;
33
+ return min ;
34
+ }
35
+
36
+ return dfs ( 0 , 0 ) ;
37
+ } ;
You can’t perform that action at this time.
0 commit comments