MockQuestions

Java Intermediate Level Greedy Mock Interview

To help you prepare for your Java Intermediate Level Greedy interview, here are 10 interview questions and answer examples.

Get More Information About Our Java Intermediate Level Greedy Interview Questions

Question 1 of 10

How do you reorganize the string?

This question shows the developer's ability to work with Java array frequencies.

You are given string str. Your task is to rearrange the characters of the string so that any two characters that are adjacent are not the same. If it is not possible to rearrange the string, return the empty string “”.
For the ith character of str, adjacent characters to it are (i - 1)st and (i + 1)st characters.

/*Example*/

Given: str = “aab”
Expected output: “aba”

Given: str = “aaa”
Expected output: “”

Solution:

First, we will count the frequencies of each character in the array freq. We will also track the character mostFreqCharCode which is the most frequency, that is, the character that occurs the most number of times in str. Let len be the length of str, which also be the length of the resultant string. We will try to put the most frequent character at even indices because

● countEvenIndices = countOddIndices, for array of even length
● countEvenIndices = countOddIndices + 1, for array of odd length

The frequency of the most frequent character MUST be less than or equal to countEvenIndices, because, otherwise we will not be able to reorganize the string. For example, let len = 5, the most frequent character is “s” with frequency 4,
countEvenIndices = Math.ceil(len / 2) = 3
array indices: 0 1 2 3 4
array: “s” _ “s” _ “s”

We have placed 3 out of 4 the most frequent characters. Now there are two places left:- index 1 and index 3. But we can’t place “s” at those indices because it will make adjacent characters the same. If it does not satisfy the condition, we will return the empty string “”.

After confirming that the solution exists, we will place all the characters in the res array one by one. We will start with the most frequent character and will place it at even indices. After placing the most frequent character we will place other characters first at remaining even indices (if any) then at odd indices.

class Solution {
    public String reorganizeString(String str) {
        int len = str.length();
        Pair<int[], Integer> count = countChars(str);
        int freq[] = count.getKey();
        int mostFreqCharCode = count.getValue();
 
        if (!isPossible(len, freq[mostFreqCharCode])) {
            return "";
        }
    
        char res[] = new char[len];    
        fillMostFreqChar(res, freq, mostFreqCharCode);
        fillRestChars(res, freq);
    
        return String.valueOf(res);
    }
    
    private Pair<int[], Integer> countChars(String str) {
        int freq[] = new int[26];
        Arrays.fill(freq, 0);
        int len = str.length();
        int mostFreqCharCode = 0;
    
        for (Character ch : str.toCharArray()) {
            int code = ch - 97;
            freq[code]++;
 
            if (freq[code] > freq[mostFreqCharCode]) {
                mostFreqCharCode = code;
            }
        }
        
        return new Pair(freq, mostFreqCharCode);
    }
    
    private boolean isPossible(int len, int freqOfMostFreqCharCode) {
        double countEvenIndices = Math.ceil((double)len / 2);
        return freqOfMostFreqCharCode <= countEvenIndices;
    }
    
    private void fillMostFreqChar(char[] res, int[] freq, 
int mostFreqCharCode) {
        int i = 0;
        
        while (freq[mostFreqCharCode] != 0) {
            res[i] = (char)(mostFreqCharCode + 97);
            i += 2;
            freq[mostFreqCharCode]--;
        }
    }

    private void fillRestChars(char[] res, int[] freq) {
        int i = 0;
        // find first even index which is not filled
        while (i < res.length) {
            if(res[i] != '\u0000') i += 2;
            else break;
        }
    
        for (int charCode = 0; charCode < 26; charCode++) {
            while (freq[charCode] > 0) {
                // all even indices are filled
                // start filling at odd indices
                if (i >= res.length) i = 1;
                res[i] = (char)(charCode + 97);
                i += 2;
                freq[charCode]--;
            }
        }
    }

}

Time complexity- O(len)
Space complexity- O(len)

Written by on June 27th, 2021

Next Question

10 Java Intermediate Level Greedy Interview Questions & Answers

Below is a list of our Java Intermediate Level Greedy interview questions. Click on any interview question to view our answer advice and answer examples. You may view 5 answer examples before our paywall loads. Afterwards, you'll be asked to upgrade to view the rest of our answers.

  • 1. How do you reorganize the string?

  • 2. Create the card-power game.

  • 3. Return the consecutive numbers.

  • 4. Remove duplicate letters.

  • 5. Can you partition the string?

  • 6. What are the minimum number of jumps?

  • 7. Find the desired configurations of the bulbs.

  • 8. Minimize the maximum pair sum in an array.

  • 9. What is the score after flipping the matrix?

  • 10. How do you reconstruct the queue by height?