tinycodinglm / cp /cp-10021.jsonl
winapiadmin's picture
Upload folder using huggingface_hub (part 12)
3c88a0f verified
|
Raw History Blame Contribute Delete
2.89 kB
{"type": "session", "harness": "opencode", "id": "cp-10021", "name": "LeetCode 0514: Freedom Trail"}
{"type": "message", "message": {"role": "system", "content": "You are an expert LeetCode problem solver. You solve problems efficiently with clean code."}}
{"type": "message", "message": {"role": "user", "content": "Problem: Freedom Trail (Difficulty: Hard)\nTags: String, Dynamic Programming, Depth-First Search, Breadth-First Search\n\nIn the video game Fallout 4, the quest \"Road to Freedom\" requires players to reach a metal dial called the \"Freedom Trail Ring\" and use the dial to spell a specific keyword to open the door.\nGiven a string ring that represents the code engraved on the outer ring and another string key that represents the keyword that needs to be spelled, return the minimum number of steps to spell all the characters in the keyword.\nInitially, the first character of the ring is aligned at the \"12:00\" direction. You should spell all the characters in key one by one by rotating ring clockwise or anticlockwise to make each character of the string key aligned at the \"12:00\" direction and then by pressing the center button.\nAt the stage of rotating the ring to spell the key character key[i]:\n\nExample 1:\nInput: ring = \"godding\", key = \"gd\"\nOutput: 4\nExplanation:\nFor the first key character 'g', since it is already in place, we just need 1 step to spell this character. \nFor the second key character 'd', we need to rotate the ring \"godding\" anticlockwise by two steps to make it become \"ddinggo\".\nAlso, we need 1 more step for spelling.\nSo the final output is 4.\n\nExample 2:\nInput: ring = \"godding\", key = \"godding\"\nOutput: 13\n\nConstraints:\n- 1 <= ring.length, key.length <= 100\n- ring and key consist of only lower case English letters.\n- It is guaranteed that key could always be spelled by rotating ring."}}
{"type": "message", "message": {"role": "assistant", "content": "# Time: O(k) ~ O(k * r^2)\n# Space: O(r)\n\nimport collections\n\n\nclass Solution(object):\n def findRotateSteps(self, ring, key):\n \"\"\"\n :type ring: str\n :type key: str\n :rtype: int\n \"\"\"\n lookup = collections.defaultdict(list)\n for i in range(len(ring)):\n lookup[ring[i]].append(i)\n\n dp = [[0] * len(ring) for _ in range(2)]\n prev = [0]\n for i in range(1, len(key)+1):\n dp[i%2] = [float(\"inf\")] * len(ring)\n for j in lookup[key[i-1]]:\n for k in prev:\n dp[i%2][j] = min(dp[i%2][j],\n min((k+len(ring)-j) % len(ring), \\\n (j+len(ring)-k) % len(ring)) + \\\n dp[(i-1) % 2][k])\n prev = lookup[key[i-1]]\n return min(dp[len(key)%2]) + len(key)\n\n"}}