JPMorgan Chase | Glasgow | 2023 Software Engineer Program | Online Coding Round
Anonymous User
2376

Time Given - 1 hrs
Number of Questions - 2

Question 1

No Pairs Allowed

For each word in a list of words, if any two adjacent characters are equal, change one of them. Determine the minimum number of substitutions so final string contains no adjacent equal characters.

Example:

words = ['add','boook','break']

  1. 'add' : change one d (1 change)
  2. 'boook' : change middle o (1 change)
  3. 'break' : no changes necessary (0 changes)

The return array is [1,1,0]

Solution
public static List<Integer> minimalOperations(List<String> words)
{
	List<Integer> res = new ArrayList();
	if(words.isEmpty()) return res;

	for(String word: words)
	{
		int count = 0;
		char prev = word.charAt(0);
		for(int i=1; i<word.length(); i++)
		{
			char curr = word.charAt(i);
			if(curr == prev)
			{
				prev = '-';
				count++;
			}
			else{
				prev = curr;
			}
		}
		res.add(count);
	}
	return res;
}

The above solution passed all test cases.

Question 2

Counting Bits

Given an integer n, determine the following:

  1. How many 1-bits are in its binary representation?
  2. The number n's binary representation has k significant bits indexed from 1 to k. What are the respective positions of each 1-bit, in ascending order?
Example

n = 37

For the value n = 37 Binary representation is 100101
There are three one bits located at the respective 1st, 4th and 6th positions (From left to Right).

The return answer is
3
1
4
6

Solution

public static List<Integer> getOneBits(int n)
{

		StringBuilder str = new StringBuilder();
        while (n > 0) {
            int num = n & 1;
            str.append(num);
            n >>= 1;
        }
        List<Integer> res = new ArrayList();
        int count = 1;
        for(char c : str.reverse().toString().toCharArray())
        {
            if(c == '1') res.add(count);
            count++;
        }
        return res;
}

The above solution passed all test cases too.

Comments (7)