Ctrl K

One-Row Keyboard

Easy
An unusual keyboard has all 26 keys in a single row. The layout is the string layout: the character layout[i] sits at position i (0-based). You type with one finger, which starts at position 0. To type a letter, you move the finger to its key; moving from position i to position j takes |i - j| units of time. Return how long it takes to type the string text.
Example 1
layout='abcdefghijklmnopqrstuvwxyz', text='dad' → 9

The finger moves from 0 to 3 for 'd', back to 0 for 'a', then to 3 again: 3 + 3 + 3 = 9.

Example 2
layout='zyxwvutsrqponmlkjihgfedcba', text='zzz' → 0

'z' sits at position 0, right under the finger, so no movement is needed.

Example 3
layout='qwertyuiopasdfghjklzxcvbnm', text='pay' → 15
Constraints
  • len(layout) = 26, and every lowercase English letter appears in layout exactly once
  • 1 ≤ len(text) ≤ 10⁴
  • text consists of lowercase English letters
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsValue of a Roman Numeral EasySame Letter Cipher EasySame Letters, Reshuffled EasySame When Flipped EasyShuffle Into a Palindrome Easy
loading Python…
Input
layout='abcdefghijklmnopqrstuvwxyz', text='dad'
Expected
9

Run checks the first 3 tests in your browser. Submit checks all 87 tests on the server, hidden ones included.