Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Calculating time taken to type words in JavaScript
In JavaScript, we can calculate the time taken to type words on a custom keyboard where keys are arranged alphabetically (a-z) instead of the traditional QWERTY layout.
Problem Setup
We make two key assumptions:
The fingertip starts at index 0 (key 'a')
Time to move between keys equals the absolute difference of their positions. For example, moving from 'a' (index 0) to 'k' (index 10) takes |0 - 10| = 10 time units
Example Walkthrough
For the string 'dab', the movements are:
'a' -> 'd' = |0 - 3| = 3 'd' -> 'a' = |3 - 0| = 3 'a' -> 'b' = |0 - 1| = 1 Total time = 3 + 3 + 1 = 7
Implementation
const str = 'dab';
const findTimeTaken = (str = '') => {
let timeSpent = 0;
const keyboard = 'abcdefghijklmnopqrstuvwxyz';
let curr = 'a';
for(let i = 0; i
7
How It Works
The algorithm tracks the current finger position and calculates the distance to each target character:
- Initialize time counter and current position at 'a'
- For each character in the input string:
- Find current position index
- Find target character index
- Calculate absolute difference as movement time
- Update current position to target character
- Return total accumulated time
Testing with Different Inputs
// Test various strings
console.log("'abc':", findTimeTaken('abc'));
console.log("'hello':", findTimeTaken('hello'));
console.log("'z':", findTimeTaken('z'));
'abc': 2
'hello': 46
'z': 25
Conclusion
This solution efficiently calculates typing time by tracking finger movement between alphabetically ordered keys. The algorithm has O(n) time complexity where n is the string length.
