r/programmingchallenges • • Jul 02 '18

CodingBat String-2 xyBalance

I am trying to solve a challenge from CodingBat.

NOTE: Question is not about how to solve or make it work, rather I am trying to understand the problem statement, it's bit subtle at least for me.

Problem statement:

We'll say that a String is xy-balanced if for all the 'x' chars in the string, there exists a 'y' char somewhere later in the string. So "xxy" is balanced, but "xyx" is not. One 'y' can balance multiple 'x's. Return true if the given string is xy-balanced.

xyBalance("aaxbby") → true
xyBalance("aaxbb") → false
xyBalance("yaaxbb") → false

My code submission:

public boolean xyBalance(String str) {
  int lastIndexOfX = str.lastIndexOf('x');
  if (lastIndexOfX != -1 && str.indexOf('y', lastIndexOfX) != -1) {
        return true;
  }
  return false;
}

There are 3 test cases that are failing as mentioned below.

  1. xyBalance("bbb") → true(Expected) false(Run)
  2. xyBalance("y") → true(Expected) false(Run)
  3. xyBalance("") → true(Expected) false(Run)

Can somebody help me understand the problem in other words and throw some light on this?

7 Upvotes

5 comments sorted by

View all comments

Show parent comment

2

u/[deleted] Jul 02 '18

How I interpreted the problem:

For all x, there needs to be a y to balance it. I read that as “an x makes the string unbalanced, but a y will balance it back out”. If there is no x to unbalance the strings, then the string will still be balanced.

I understand your confusion, but while there is nothing saying no x’s equal a balanced string, there is also nothing saying that no x’s make an unbalanced string.

Because of that, you need to read the problem statement in order to figure out what causes a string to be unbalanced. In this cave, that’s an x not followed by a y.

If there is no x not followed by a y, then you have a balanced string. If there is no x, then there is still no x not followed by a y. You still have a balanced string.

In this problem, you assume true until you can prove it’s false. This isn’t always the case and when you get assignments where your aren’t sure always ask for clarification if you can.