Reformat The String — LeetCode 1417 Python Solution

EasyString
Problem
#1417
Pattern
Hash Map
Reading time
3 min

The problem

You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).

Example

Input
s = "a0b1c2"
Output
"0a1b2c"
Explanation
No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.

Python solution

Python
class Solution:
    def reformat(self, s: str) -> str:
        a = [c for c in s if c.islower()]
        b = [c for c in s if c.isdigit()]
        if abs(len(a) - len(b)) > 1:
            return ''
        if len(a) < len(b):
            a, b = b, a
        ans = []
        for x, y in zip(a, b):
            ans.append(x + y)
        if len(a) > len(b):
            ans.append(a[-1])
        return ''.join(ans)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1417. Reformat The String is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1417. Reformat The String?
LeetCode 1417. Reformat The String is rated Easy on LeetCode.
What topics does LeetCode 1417. Reformat The String cover?
LeetCode 1417. Reformat The String is tagged String 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