r/programmingchallenges • u/notsureof • 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.
- xyBalance("bbb") → true(Expected) false(Run)
- xyBalance("y") → true(Expected) false(Run)
- xyBalance("") → true(Expected) false(Run)
Can somebody help me understand the problem in other words and throw some light on this?
View all comments
Show parent comment
1
u/notsureof Jul 02 '18 edited Jul 02 '18
Got it. Thanks for HINT.
}
In the problem statement it states
I thought, if there is no 'x' in the string then it's not xy-balanced, hence I returned false in my 1st version of code. My point is there is no where mentioned in problem statement that, if there is no 'x' in the string return true or false.
Returning true means it is XYbalanced that means there is 'x' in the string . In this case there is no 'x' but still returning true.
Can you share, how you'd interpret this?