HackerRank Designer PDF Viewer | JS Solution
Problem
Determine the area of the rectangle highlight in mm2
for a word, based on provided array of letter heights and letter width of 1mm.
Input: array of numbers (26 character heights in consecutive alphabetical order / ascii[a-z]), string (a single word consisting of max of 10 lowercase English letters)
Output: number (the area of the rectangle highlight)
Test Case
const testHeights = [1, 3, 1, 3, 1, 4, 1, 3, 2, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 7];
const testWord = 'zebra';
Data Types
Array, string and number.
Pseudo Code
- We need to find out the alphabetic index of the characters in the provided word. Say letter
a
is first in alphabet and therefore would have an index0
and height of1
considering thetestHeights
array above. While letterz
would have an index25
since it is the very last letter of the alphabet and therefore matches the 26th element in the array and has a height of7
- We then need to figure out what is the
tallestCharHeight
in the providedtestWord
. In our case it is letterz
, which has index25
and height of7
- Once we have everything we can multiply the tallest letter height by the word length or number of letters in the word
JavaScript Solution
function designerPdfViewer(heights, word) {
let tallestCharHeight = 0;
let index = 0;
for (let i = 0; i < word.length; i++) {
index = word.charCodeAt(i) - 97;
if (heights[index] > tallestCharHeight) {
tallestCharHeight = heights[index];
}
}
return tallestCharHeight * word.length;
}
Sources:
- Designer PDF Viewer by HackerRank
- PEDAC Algorithm Solving Approach by LaunchSchool