No results found for the specified position. Format a string by grouping characters fou... Javascript Beginner Level Implementation Mock Interview

MockQuestions

Javascript Beginner Level Implementation Mock Interview

Question 2 of 11 for our Javascript Beginner Level Implementation Mock Interview

Get More Information About Our Javascript Beginner Level Implementation Interview Questions

Question 2 of 11

Format a string by grouping characters found in the string into similar lengths.

You are given a string named string consisting of alphanumeric characters. It contains some dashes - at random places dividing the string into groups. These groups can be different or the same length. Your task is to format the string as such that the dashes divide the string into groups of equal length K. The first group may have a length of less than or equal to K but the rest of the groups must have length K.

/* Example */

#1:  Given - “abc-def” and K = 2
	Expected output - “ab-cd-ef”
	All groups have the same length 2.

#2:  Given - “abc-def-abdj-k” and K = 3
	Expected output - “ab-cde-fab-djk”
	All groups have except the first group has the same length 3.

Solution:

Given string - string
Let, the normal length of groups (except for the first group) be K
Let, the length of the given string be L
Let, the count of alphanumeric characters be N

If K divides N, then there are exactly K / N such groups in the formatted string each of length K.

If K does not divide N, then there are floor(K / N) groups each of length K and one group with remaining characters. The first group will have fewer than K characters and the rest will have exactly K characters. It is guaranteed that its length will be at least 1 because K does not divide N.

Let’s understand the sample inputs.

Given string- “abc-def”
Given K = 2

N = 6
Since K divides N, there will be 6 / 2 = 3 groups in the formatted string.
---

Given string- “abc-def-abdjk”
Given K = 3

N = 11
Since K does not divide N, there will be floor(11 / 3) = 3 groups in the formatted string with length K = 3 viz. cde, fab, djk. The remaining two characters ab will form the first group with length <= K = 3.

It can be seen there will be a dash - after every K places in the given string (with dashes removed). Thus we can iterate on the given string in the backward direction and place a dash after every K alphanumeric character.

/**
 * @param {string} string
 * @param {number} K
 * @return {string}
 */
function formatLicenseKey(string, K) {
    // array to contain the formatted string
    const characters = []
    
    // iterate backwards
    for (let i = string.length - 1; i >= 0; i--) {
        const char = string[i]

        // if the current character is a dash skip it
        if (char === '-') continue
        
        // if the `characters` array contains a group
        // of size `K` in its tail, push a dash
        // marking the start of a new group
        if (characters.length % (K + 1) === K) {
            characters.push('-')
        }
        
        // transform and push the character
        characters.push(char.toUpperCase())
    }
    
    // since we were iterating and pushing chars
    // from backward direction, reverse the array
    // and join it to form a string
    return characters.reverse().join("")
}

Written by on May 4th, 2021

Next Question

How to Answer: Format a string by grouping characters found in the string into similar lengths.

Advice and answer examples written specifically for a Javascript Beginner Level Implementation job interview.

  • 2. Format a string by grouping characters found in the string into similar lengths.

      You are given a string named string consisting of alphanumeric characters. It contains some dashes - at random places dividing the string into groups. These groups can be different or the same length. Your task is to format the string as such that the dashes divide the string into groups of equal length K. The first group may have a length of less than or equal to K but the rest of the groups must have length K.

      /* Example */
      
      #1:  Given - “abc-def” and K = 2
      	Expected output - “ab-cd-ef”
      	All groups have the same length 2.
      
      #2:  Given - “abc-def-abdj-k” and K = 3
      	Expected output - “ab-cde-fab-djk”
      	All groups have except the first group has the same length 3.

      Solution:

      Given string - string
      Let, the normal length of groups (except for the first group) be K
      Let, the length of the given string be L
      Let, the count of alphanumeric characters be N

      If K divides N, then there are exactly K / N such groups in the formatted string each of length K.

      If K does not divide N, then there are floor(K / N) groups each of length K and one group with remaining characters. The first group will have fewer than K characters and the rest will have exactly K characters. It is guaranteed that its length will be at least 1 because K does not divide N.

      Let’s understand the sample inputs.

      Given string- “abc-def”
      Given K = 2

      N = 6
      Since K divides N, there will be 6 / 2 = 3 groups in the formatted string.
      ---

      Given string- “abc-def-abdjk”
      Given K = 3

      N = 11
      Since K does not divide N, there will be floor(11 / 3) = 3 groups in the formatted string with length K = 3 viz. cde, fab, djk. The remaining two characters ab will form the first group with length <= K = 3.

      It can be seen there will be a dash - after every K places in the given string (with dashes removed). Thus we can iterate on the given string in the backward direction and place a dash after every K alphanumeric character.

      /**
       * @param {string} string
       * @param {number} K
       * @return {string}
       */
      function formatLicenseKey(string, K) {
          // array to contain the formatted string
          const characters = []
          
          // iterate backwards
          for (let i = string.length - 1; i >= 0; i--) {
              const char = string[i]
      
              // if the current character is a dash skip it
              if (char === '-') continue
              
              // if the `characters` array contains a group
              // of size `K` in its tail, push a dash
              // marking the start of a new group
              if (characters.length % (K + 1) === K) {
                  characters.push('-')
              }
              
              // transform and push the character
              characters.push(char.toUpperCase())
          }
          
          // since we were iterating and pushing chars
          // from backward direction, reverse the array
          // and join it to form a string
          return characters.reverse().join("")
      }

      Written by S. Kumar on June 27th, 2021