Construct the Longest New String Solution in Java

Problem Description

Ah, the age-old quest of constructing the longest new string! It’s like trying to make a sandwich with the perfect amount of peanut butter and jelly, but instead, you have a limited supply of letters. The problem is simple: given three integers x, y, and z, representing the counts of three different types of characters, your mission—should you choose to accept it—is to create the longest string possible.

Imagine you’re at a party, and you have a limited number of balloons (x for red, y for blue, and z for green). You want to impress your friends with the longest balloon animal, but you can only use what you have. If you have equal amounts of red and blue balloons, you can make a fabulous alternating pattern, but if one color runs out, you’ll have to get creative.

Code Solution

class Solution {
  public int longestString(int x, int y, int z) {
    final int mn = Math.min(x, y);
    if (x == y)
      return (mn * 2 + z) * 2;
    return (mn * 2 + 1 + z) * 2;
  }
}

Approach

The approach here is quite straightforward. The code first determines the minimum of x and y, which represents the two types of characters that can be paired together. If x and y are equal, it calculates the maximum length of the string by using all characters and adding the remaining characters of type z. If they are not equal, it adds one more character to the string, ensuring that the string remains as long as possible.

Time and Space Complexity

Time Complexity: O(1) – The solution runs in constant time since it only involves a few arithmetic operations.

Space Complexity: O(1) – No additional space is used that scales with input size.

Real-World Example

Let’s say you’re at a birthday party, and you have 5 red balloons, 5 blue balloons, and 3 green balloons. You can create a string of balloons like this: RBRBRBRBRG. You’ve used all your red and blue balloons and one green balloon, resulting in a total of 11 balloons. If you had more green balloons, you could have made it even longer!

Similar Problems

Two Sum Solution in Java