Construct the Longest New String — LeetCode 2745 Python Solution

MediumGreedyBrainteaserMathDynamic Programming
Problem
#2745
Pattern
Greedy
Reading time
2 min

The problem

You are given three integers x, y, and z. You have x strings equal to "AA", y strings equal to "BB", and z strings equal to "AB".

Example

Input
x = 2, y = 5, z = 1
Output
12
Explanation
We can concatenate the strings "BB", "AA", "BB", "AA", "BB", and "AB" in that order. Then, our new string is "BBAABBAABBAB".

Python solution

Python
class Solution:
    def longestString(self, x: int, y: int, z: int) -> int:
        if x < y:
            return (x * 2 + z + 1) * 2
        if x > y:
            return (y * 2 + z + 1) * 2
        return (x + y + z) * 2

Complexity

MeasureComplexity
TimeO(1)
SpaceO(1) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2745. Construct the Longest New String is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2745. Construct the Longest New String?
LeetCode 2745. Construct the Longest New String is rated Medium on LeetCode.
What is the time complexity of LeetCode 2745. Construct the Longest New String?
The Python solution on this page runs in O(1).
What is the space complexity of LeetCode 2745. Construct the Longest New String?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2745. Construct the Longest New String cover?
LeetCode 2745. Construct the Longest New String is tagged Greedy, Brainteaser, Math and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview