You are given a string named digits made of digits '1' and/or '2'. It represents a positive integer. Remove zero or more digits from it, so that each remaining digit occurs an even number of times and the value of the resulting integer is as large as possible.
Write a function:
class Solution { public String solution(String digits);
}
that, given a string named digits of length N, representing the integer, returns a string representing the largest obtainable integer after performing the removals.
Examples:
Given digits = "121212", the function should return "2121".
Given digits = "2121122", the function should return "221122".
Given digits = "1111", the function should return "1111".
Write an efficient algorithm for the following assumptions:
N is an integer within the range [3..200,000];
string digits is made only of the characters '1' and/or '2'. with main method, thoroughly analysis and provide
Assistant
To solve this problem, the goal is to remove the minimum number of digits ('1' and '2') from the input string digits such that each remaining digit appears an even number of times. The challenge is to achieve this while ensuring that the resulting number is as large as possible.
Approach:
Count the Digits:
First, count the number of '1's and '2's in the input string digits. This will help determine which digits (if any) need to be removed to satisfy the evenness condition.
Determine Parity:
Check the parity (odd or even) of the counts for '1' and '2'.
There are four possible cases based on the parity:
Both Even: No removals are needed. The original string is already valid.
Only '1' Odd: Remove the leftmost '1' to make the count of '1's even.
Only '2' Odd: Remove the rightmost '2' to make the count of '2's even.
Both Odd: Remove the leftmost '1' and the rightmost '2' to make both counts even.
Remove Necessary Digits:
Identify the indices of the digits to be removed based on the determined parity.
Use a boolean array to mark these indices for removal.
Reconstruct the Result:
Iterate through the original string and build the resulting string by skipping the marked indices.
Ensure that the resulting string maintains the original order of the remaining digits.
Edge Cases:
If removing the required digits results in an empty string, it means that it's impossible to meet the conditions (though the problem statement implies that a solution always exists).
Implementation:
Below is the Java implementation of the above approach, including a main method to demonstrate the solution with the provided test cases.
java
import java.util.*;
public class Solution {
public String solution(String digits) {
int count1 = 0;
int count2 = 0;
int n = digits.length();
char[] chars = digits.toCharArray();
// Step 1: Count '1's and '2's
for(char c : chars){
if(c == '1') count1++;
else if(c == '2') count2++;
}
// Step 2: Determine parity
boolean is1Odd = (count1 % 2) == 1;
boolean is2Odd = (count2 % 2) == 1;
// If both are even, return the whole string
if(!is1Odd && !is2Odd){
return digits;
}
// To mark indices to remove
boolean[] remove = new boolean[n];
// Step 3: If '1's are odd, remove leftmost '1'
if(is1Odd){
for(int i=0; i<n; i++){
if(chars[i] == '1'){
remove[i] = true;
break;
}
}
}
// Step 4: If '2's are odd, remove rightmost '2'
if(is2Odd){
for(int i=n-1; i>=0; i--){
if(chars[i] == '2'){
remove[i] = true;
break;
}
}
}
// Step 5: Reconstruct the result by skipping removed digits
StringBuilder sb = new StringBuilder();
for(int i=0; i<n; i++){
if(!remove[i]){
sb.append(chars[i]);
}
}
// After removal, check if counts are even
// Re-count '1's and '2's in the result
int finalCount1 = 0;
int finalCount2 = 0;
for(int i=0; i<sb.length(); i++){
if(sb.charAt(i) == '1') finalCount1++;
else if(sb.charAt(i) == '2') finalCount2++;
}
// If after removal, counts are not even, it's invalid
// But according to problem statement, it should always be possible
// So we assume the result is valid
// If the resulting string is empty, which shouldn't happen as per problem statement,
// but to handle it gracefully, we can return an empty string or a specific value.
// Here, we'll return an empty string.
return sb.toString();
}
// Main method for demonstration and testing
public static void main(String[] args) {
Solution sol = new Solution();
// Test Case 1
String digits1 = "121212";
String result1 = sol.solution(digits1);
System.out.println("Test Case 1:");
System.out.println("Input: " + digits1);
System.out.println("Expected Output: 2121");
System.out.println("Actual Output: " + result1);
System.out.println(result1.equals("2121") ? "PASS\n" : "FAIL\n");
// Test Case 2
String digits2 = "2121122";
String result2 = sol.solution(digits2);
System.out.println("Test Case 2:");
System.out.println("Input: " + digits2);
System.out.println("Expected Output: 221122");
System.out.println("Actual Output: " + result2);
System.out.println(result2.equals("221122") ? "PASS\n" : "FAIL\n");
// Test Case 3
String digits3 = "1111";
String result3 = sol.solution(digits3);
System.out.println("Test Case 3:");
System.out.println("Input: " + digits3);
System.out.println("Expected Output: 1111");
System.out.println("Actual Output: " + result3);
System.out.println(result3.equals("1111") ? "PASS\n" : "FAIL\n");
// Additional Test Case 4
String digits4 = "12121";
String result4 = sol.solution(digits4);
System.out.println("Test Case 4:");
System.out.println("Input: " + digits4);
System.out.println("Expected Output: 2121");
System.out.println("Actual Output: " + result4);
System.out.println(result4.equals("2121") ? "PASS\n" : "FAIL\n");
// Additional Test Case 5
String digits5 = "21121";
String result5 = sol.solution(digits5);
System.out.println("Test Case 5:");
System.out.println("Input: " + digits5);
System.out.println("Expected Output: 2121");
System.out.println("Actual Output: " + result5);
System.out.println(result5.equals("2121") ? "PASS\n" : "FAIL\n");
// Additional Test Case 6
String digits6 = "121221";
String result6 = sol.solution(digits6);
System.out.println("Test Case 6:");
System.out.println("Input: " + digits6);
System.out.println("Expected Output: 2121");
System.out.println("Actual Output: " + result6);
System.out.println(result6.equals("2121") ? "PASS\n" : "FAIL\n");
// Edge Test Case 7: All '1's even and all '2's even
String digits7 = "1122";
String result7 = sol.solution(digits7);
System.out.println("Test Case 7:");
System.out.println("Input: " + digits7);
System.out.println("Expected Output: 1122");
System.out.println("Actual Output: " + result7);
System.out.println(result7.equals("1122") ? "PASS\n" : "FAIL\n");
// Edge Test Case 8: Only '1's and '2's odd
String digits8 = "1212212";
String result8 = sol.solution(digits8);
System.out.println("Test Case 8:");
System.out.println("Input: " + digits8);
System.out.println("Expected Output: 212212"); // Removing first '1' and last '2'
System.out.println("Actual Output: " + result8);
System.out.println(result8.equals("212212") ? "PASS\n" : "FAIL\n");
}
}
Explanation of the Code:
Counting Digits:
Iterate through the input string and count the number of '1's and '2's.
Determining Parity:
Check if the counts of '1' and '2' are odd or even.
Marking Digits for Removal:
If the count of '1's is odd, find the first occurrence (leftmost) of '1' and mark it for removal.
If the count of '2's is odd, find the last occurrence (rightmost) of '2' and mark it for removal.
Reconstructing the Result:
Build a new string by skipping the marked indices.
This ensures that the resulting string has even counts of both '1' and '2' and is as large as possible.
Handling Edge Cases:
The code assumes that it's always possible to achieve the desired condition based on the problem statement.
If the resulting string is empty (which shouldn't happen as per the problem's constraints), it returns an empty string.
Testing:
The main method includes several test cases, including the ones provided in the problem statement and additional edge cases to ensure the robustness of the solution.
Time and Space Complexity:
Time Complexity: O(N), where N is the length of the input string. The algorithm makes a few passes through the string but does not perform any nested iterations that depend on N.
Space Complexity: O(N), primarily due to the remove boolean array and the StringBuilder used to construct the result.
Conclusion:
This solution efficiently ensures that the resulting number has even counts of each digit while maximizing its value by strategically removing the necessary digits. The approach is optimal for large input sizes, adhering to the problem's constraints.