Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d5e3b9c

Browse files
authored
Create 0514-freedom-trail.js
Solved freedom-trail
1 parent 3a66f08 commit d5e3b9c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

javascript/0514-freedom-trail.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
};

0 commit comments

Comments
 (0)