Minimum Rotations to Dial a Number II Problem
Description
LeetCode Problem 4071.
You are given an integer n and a string s of length n consisting of digits.
The dial contains the digits 0 through 9 in order and is circular, so 0 and 9 are adjacent. The pointer initially points to 0.
To dial each digit of s in order, rotate the pointer until it points to that digit. Each rotation moves the pointer to an adjacent digit, and you may rotate in either direction. Dialing a digit that the pointer already points to requires no rotations.
Before dialing, you may perform the following operation at most once:
- Choose an index
ksuch that0 <= k < nand reverse the suffixs[k..n - 1].
Return the minimum total number of rotations needed to dial the string after optimally choosing whether to perform the operation and which suffix to reverse.
Example 1:
Input: n = 4, s = "1502"
Output: 9
Explanation:
Reverse the suffix starting at k = 1 to obtain "1205", then dial it.
Step From To Rotations
1 0 1 1
2 1 2 1
3 2 0 2
4 0 5 5
The total is 1 + 1 + 2 + 5 = 9, which is the minimum total number of rotations.
Example 2:
Input: n = 4, s = "2916"
Output: 12
Explanation:
Choose not to reverse a suffix and dial "2916".
Step From To Rotations
1 0 2 2
2 2 9 3
3 9 1 2
4 1 6 5
The total is 2 + 3 + 2 + 5 = 12, which is the minimum total number of rotations.
Example 3:
Input: n = 4, s = "4219"
Output: 6
Explanation:
Reverse the suffix starting at k = 0, which reverses the entire string, to obtain "9124", then dial it.
Step From To Rotations
1 0 9 1
2 9 1 2
3 1 2 1
4 2 4 2
The total is 1 + 2 + 1 + 2 = 6, which is the minimum total number of rotations.
Constraints:
1 <= n == s.length <= 10^5sconsists only of digits'0'to'9'
Solution
Approach: Try every suffix start
Let dist(a, b) be the shortest circular distance between two digits and let T be the sum of dist(s[i-1], s[i]) over the whole string (the cost of the moves between consecutive digits, not counting the first move from 0).
- Reversing the whole string (
k = 0) keeps all inner moves, only the first move changes: the answer isT + dist(0, s[n-1]). - Reversing from
k > 0keeps the prefix, so the first move is stilldist(0, s[0]). Inside the reversed suffix the moves are the same set of pairs, so only the edge(s[k-1], s[k])changes into(s[k-1], s[n-1]). The cost isT - dist(s[k-1], s[k]) + dist(0, s[0]) + dist(s[k-1], s[n-1]).
Take the minimum over all k. Not reversing is covered by k = n - 1, which reverses a single character.
Complexity: O(n) time and O(1) extra space.
class Solution:
def minRotations(self, n: int, s: str) -> int:
def dist(a: str, b: str) -> int:
d = abs(ord(a) - ord(b))
return min(d, 10 - d)
total = sum(dist(a, b) for a, b in zip(s, s[1:]))
first = s[0]
last = s[-1]
to_first = dist("0", first)
ans = total + dist("0", last)
for pre, cur in zip(s, s[1:]):
ans = min(ans, total - dist(pre, cur) + to_first + dist(pre, last))
return ans