Skip to main content
Back to problems
#3846
Medium Algorithms

Total distance to type a string using one finger

Hash Table String
91.3% acceptance
Apr 3, 2026
4
2
There is a special keyboard where keys are arranged in a rectangular grid as follows. q w e r t y u i o p a s d f g h j k l z x c v b n m You are given a string s that consists of lowercase English letters only. Return an integer denoting the total distance to type s using only one finger. Your finger starts on the key 'a'. The distance between two keys at (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn total_distance(s: String) -> i32 {
    let rows: [&[u8]; 3] = [b"qwertyuiop", b"asdfghjkl", b"zxcvbnm"];
    let mut position = [(0i32, 0i32); 26];

    for (row, keys) in rows.iter().enumerate() {
      for (col, &key) in keys.iter().enumerate() {
        position[(key - b'a') as usize] = (row as i32, col as i32);
      }
    }

    let mut total = 0;
    let mut current = position[0];

    for key in s.bytes() {
      let next = position[(key - b'a') as usize];
      total += (current.0 - next.0).abs() + (current.1 - next.1).abs();
      current = next;
    }

    total
  }
}