Before attempting this problem, you should be comfortable with:
To type a word efficiently, we need to know where each key is located on the keyboard. By precomputing the position of every letter, we can quickly look up the distance between consecutive characters. The total time is the sum of all these distances as we move from one key to the next.
prev to 0 (starting position) and result to 0.prev to result.prev to the current character's position.result as the total typing time.class Solution:
def calculateTime(self, keyboard: str, word: str) -> int:
key_indices = {}
# Get the index for each key.
for i in range(len(keyboard)):
key_indices[keyboard[i]] = i
# Initialize previous index as starting index = 0.
prev = 0
result = 0
# Calculate the total time.
for c in word:
# Add the distance from previous index
# to current letter's index to the result.
result += abs(prev - key_indices[c])
# Update the previous index to current index for next iteration.
prev = key_indices[c]
return resultWhere is the length of
word.
A common mistake is calculating the distance from a fixed starting point (like index 0) for each character instead of from the previous character's position. The finger moves sequentially through the word, so each distance calculation must be relative to where the finger currently is.
When calculating the distance between two positions, forgetting to take the absolute value leads to negative distances when moving left on the keyboard. The time to move is always the magnitude of the difference, regardless of direction.