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 index 0 and height of 1 considering the testHeights array above. While letter z would have an index 25 since it is the very last letter of the alphabet and therefore matches the 26th element in the array and has a height of 7
  • We then need to figure out what is the tallestCharHeight in the provided testWord. In our case it is letter z, which has index 25 and height of 7
  • 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:

  1. Designer PDF Viewer by HackerRank
  2. PEDAC Algorithm Solving Approach by LaunchSchool