713139. CBA Subsequence
Here is the detailed Markdown blog post for the GeeksforGeeks problem "CBA Subsequence":
CBA Subsequence
Summary
Find the longest subsequence in a given string that contains at most one occurrence of each character 'A', 'B', and 'C'. This problem involves strings, sorting, and data structures.
Detailed Explanation
The key to this problem is understanding what constitutes a valid subsequence. A valid subsequence is any sequence of characters from the original string that does not exceed the maximum number of occurrences for each character ('A', 'B', and 'C'). To solve this problem, we will iterate through the input string and keep track of the current count of each character. When we encounter a character that exceeds its allowed count, we know we have found the longest valid subsequence.
Here is a step-by-step breakdown of the solution:
- Initialize counters for characters 'A', 'B', and 'C' to 0.
- Iterate through the input string:
- For each character:
- If it's 'A', increment the 'A' counter and update the longest valid subsequence if necessary.
- If it's 'B', increment the 'B' counter and update the longest valid subsequence if the 'A' count is 0.
- If it's 'C', increment the 'C' counter and update the longest valid subsequence if both 'A' and 'B' counts are 0.
- For each character:
- Return the longest valid subsequence found.
Time complexity: O(n), where n is the length of the input string, as we only iterate through the string once. Space complexity: O(1), as we use a constant amount of space to store the character counters.
Optimized Solutions
Java
public String longestSubsequence(String s) {
int a = 0, b = 0, c = 0;
StringBuilder sb = new StringBuilder();
for (char ch : s.toCharArray()) {
switch (ch) {
case 'A':
a++;
break;
case 'B':
if (a == 0) {
b++;
} else {
sb.append(ch);
c = 1; // reset C count
}
break;
case 'C':
if (a == 0 && b == 0) {
c++;
} else {
sb.append(ch);
}
}
}
return sb.toString();
}