Problem · String
Time to Type a String
Learn this problemProblem statement
Imagine you have a special keyboard with all keys in a single row. The layout of characters on a keyboard is denoted by a string keyboard of length 26. Initially your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index i to index j is abs(j - i).
Given a string keyboard that describe the keyboard layout and a string text, return an integer denoting the time taken to type string text.
Function
calculateTime(keyboard: String, text: String) → int
Complete the function calculateTime in the editor.
calculateTime has the following parameters:
String keyboard: a string that describes the keyboard layoutString text: the text to be typed
Returns
int: the time taken to type the string text
Examples
Example 1
keyboard = "abcdefghijklmnopqrstuvwxy"text = "cba"return = 4Initially your finger is at index 0. First you have to type 'c'. The time taken to type 'c' will be abs(2 - 0) = 2 because character 'c' is at index 2.
The second character is 'b' and your finger is now at index 2. The time taken to type 'b' will be abs(1 - 2) = 1 because character 'b' is at index 1.
The third character is 'a' and your finger is now at index 1. The time taken to type 'a' will be abs(0 - 1) = 1 because character 'a' is at index 0.
The total time will therefore be 2 + 1 + 1 = 4.
Constraints
keyboard will be equal to 26 and all the lowercase letters will occur exactly once;text is within the range [1..100,000];text contains only lowercase letters [a-z].More Google problems
- Deduplicate Logs: Keep FirstONSITE INTERVIEW · Seen Jul 2026
- Deduplicate Logs: Keep LatestONSITE INTERVIEW · Seen Jul 2026
- Find a Template Across Binary-Tree LeavesONSITE INTERVIEW · Seen Jul 2026
- Maximum Programmer-Problem MatchingONSITE INTERVIEW · Seen Jul 2026
- Minimum Direction ViolationsONSITE INTERVIEW · Seen Jul 2026
- Stream Latest Log VersionsONSITE INTERVIEW · Seen Jul 2026
- Stream Unique Logs in Timestamp OrderONSITE INTERVIEW · Seen Jul 2026
- Top-K IP Addresses from File RecordsONSITE INTERVIEW · Seen Jul 2026