- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Single-Row Keyboard in python

Suppose, there is a special keyboard with all keys in a single row. So if we have a string of length 26 indicating the layout of the keyboard (indexed from 0 to 25), initially our finger is at index 0. To type a character, we have to move your finger to the index of the next character. The time taken to move your finger from index i to index j is denoted as |i - j|. So if we want to type a string. we have to define a function to calculate how much time it takes to type it with one finger. So if the input sequences are “abcdefghijklmnopqrstuvwxyz” and the word is “hello”, then the output will be 20, as from a to h, it will be 7, then h to e is 3, then e to l is 7, then l to l is 0, and l to o is 3, so the total is 7 + 3 + 7 + 3 = 20

To solve this, we will follow these steps −

- Create one map called d, and z := 0
- for i in range 0 to length of keyboard format string k
- d[k[i]] := i

- ans := 0
- for each character i in word −
- ans := ans + |d[i] – z|
- z := d[i]

- return ans

## Example(Python)

Let us see the following implementation to get a better understanding −

class Solution(object): def calculateTime(self, k, w): d = {} z = 0 for i in range(len(k)): d[k[i]]=i ans= 0 for i in w: ans += abs(d[i]-z) z = d[i] return ans ob1 = Solution() print(ob1.calculateTime("abcdefghijklmnopqrstuvwxyz", "hello"))

## Input

"abcdefghijklmnopqrstuvwxyz" "hello"

## Output

20

- Related Questions & Answers
- Keyboard Row in C++
- Keyboard module in Python
- What are single row and multiple row subqueries?
- Reading Keyboard Input in Python
- Selecting a single row in MySQL?
- Sum values of a single row in MySQL?
- Keyboard shortcuts with Tkinter in Python 3
- MySQL LIMIT to select a single row
- Mouse and keyboard automation using Python?
- Update multiple columns of a single row MySQL?
- How to multiply corresponding row values in a matrix with single row matrix in R?
- Get the Average of Average in a single MySQL row?
- MySQL query to return all items in a single row
- Single Number in Python
- How to multiply corresponding row values in a data.table object with single row data.table object in R?