Single-Row Keyboard in python

A single-row keyboard requires finger movement between keys to type characters. Given a keyboard layout string and a word, we need to calculate the total time to type the word, where time equals the absolute distance between character positions.

Problem Understanding

Consider a keyboard layout "abcdefghijklmnopqrstuvwxyz" and word "hello":

  • Start at index 0 (position 'a')
  • Move to 'h' (index 7): distance = |0 - 7| = 7
  • Move to 'e' (index 4): distance = |7 - 4| = 3
  • Move to 'l' (index 11): distance = |4 - 11| = 7
  • Stay at 'l' (index 11): distance = |11 - 11| = 0
  • Move to 'o' (index 14): distance = |11 - 14| = 3

Total time: 7 + 3 + 7 + 0 + 3 = 20

Algorithm

The solution follows these steps:

  • Create a dictionary mapping each character to its index position
  • Track current finger position (starting at index 0)
  • For each character in the word, calculate distance and update position
  • Sum all distances to get total time

Implementation

def calculate_time(keyboard_layout, word):
    # Create position mapping
    char_positions = {}
    for i in range(len(keyboard_layout)):
        char_positions[keyboard_layout[i]] = i
    
    current_position = 0
    total_time = 0
    
    # Calculate time for each character
    for char in word:
        char_position = char_positions[char]
        total_time += abs(char_position - current_position)
        current_position = char_position
    
    return total_time

# Test the function
keyboard = "abcdefghijklmnopqrstuvwxyz"
word = "hello"
result = calculate_time(keyboard, word)
print(f"Time to type '{word}': {result}")
Time to type 'hello': 20

Alternative Implementation with Class

class SingleRowKeyboard:
    def calculate_time(self, keyboard_layout, word):
        # Map characters to their positions
        positions = {char: idx for idx, char in enumerate(keyboard_layout)}
        
        current_pos = 0
        total_time = 0
        
        for char in word:
            next_pos = positions[char]
            total_time += abs(next_pos - current_pos)
            current_pos = next_pos
            
        return total_time

# Test with different examples
keyboard = SingleRowKeyboard()

# Example 1: Standard layout
print(keyboard.calculate_time("abcdefghijklmnopqrstuvwxyz", "hello"))

# Example 2: Different layout
print(keyboard.calculate_time("pqrstuvwxyzabcdefghijklmno", "hello"))
20
64

Step-by-Step Breakdown

For the word "hello" with standard keyboard layout:

def calculate_time_detailed(keyboard_layout, word):
    positions = {char: idx for idx, char in enumerate(keyboard_layout)}
    
    current_pos = 0
    total_time = 0
    
    print(f"Typing '{word}':")
    print(f"Starting at position: {current_pos}")
    
    for i, char in enumerate(word):
        next_pos = positions[char]
        distance = abs(next_pos - current_pos)
        total_time += distance
        
        print(f"Step {i+1}: '{char}' at position {next_pos}, distance: {distance}")
        current_pos = next_pos
    
    print(f"Total time: {total_time}")
    return total_time

calculate_time_detailed("abcdefghijklmnopqrstuvwxyz", "hello")
Typing 'hello':
Starting at position: 0
Step 1: 'h' at position 7, distance: 7
Step 2: 'e' at position 4, distance: 3
Step 3: 'l' at position 11, distance: 7
Step 4: 'l' at position 11, distance: 0
Step 5: 'o' at position 14, distance: 3
Total time: 20

Time and Space Complexity

  • Time Complexity: O(n + m) where n is keyboard length and m is word length
  • Space Complexity: O(n) for the character position dictionary

Conclusion

The single-row keyboard problem calculates typing time by summing absolute distances between character positions. Use a dictionary to map characters to indices for efficient lookup, then iterate through the word calculating cumulative movement distances.

---
Updated on: 2026-03-25T08:09:16+05:30

470 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements