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

MockQuestions

Java Beginner Level Implementation Mock Interview

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

Get More Information About Our Java Beginner Level Implementation Interview Questions

Question 2 of 11

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

This question tests that a developer is familiar with Java textual data.

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 of different or the same length. Your task is to format the string 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*/

Given - “abc-def” and K = 2
Expected output - “ab-cd-ef”
//All groups have the same length 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.

class Solution {
	public String licenseKeyFormatting(String s, int k) {
        StringBuilder characters = new StringBuilder();
   	 
        // iterate backwards
        for (int i = s.length() - 1; i >= 0; i--) {
            char ch = s.charAt(i);
 
            // if the current character is a dash skip it
            if (ch == '-') 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 = characters.append('-');
            }
   	 
            // transform and push the character
            characters = characters.append(Character.toUpperCase(ch));
        }
    
        // since we were iterating and pushing chars
        // from backward direction, reverse the array
        // and join it to form a string
        characters.reverse();  
        return characters.toString(); 
    }
    
}

Written by on May 21st, 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 Java Beginner Level Implementation job interview.

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

      This question tests that a developer is familiar with Java textual data.

      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 of different or the same length. Your task is to format the string 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*/
      
      Given - “abc-def” and K = 2
      Expected output - “ab-cd-ef”
      //All groups have the same length 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.

      class Solution {
      	public String licenseKeyFormatting(String s, int k) {
              StringBuilder characters = new StringBuilder();
         	 
              // iterate backwards
              for (int i = s.length() - 1; i >= 0; i--) {
                  char ch = s.charAt(i);
       
                  // if the current character is a dash skip it
                  if (ch == '-') 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 = characters.append('-');
                  }
         	 
                  // transform and push the character
                  characters = characters.append(Character.toUpperCase(ch));
              }
          
              // since we were iterating and pushing chars
              // from backward direction, reverse the array
              // and join it to form a string
              characters.reverse();  
              return characters.toString(); 
          }
          
      }

      Written by S. Kumar on May 21st, 2021