#1417

Reformat The String

Easy
StringCounting and groupingTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n!)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach involves counting the number of letters and digits, and then constructing the result based on which type has more characters. This is efficient and avoids unnecessary permutations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the number of letters and digits in the string.
  2. 2Step 2: Check if the absolute difference between counts is greater than 1; if so, return an empty string.
  3. 3Step 3: Create a result array of the appropriate size and fill it by alternating characters from letters and digits.
solution.py16 lines
1def reformat_string(s):
2    letters = [c for c in s if c.isalpha()]
3    digits = [c for c in s if c.isdigit()]
4    if abs(len(letters) - len(digits)) > 1:
5        return ''
6    result = []
7    if len(letters) > len(digits):
8        result.append(letters.pop())
9    for i in range(len(s)):
10        if i % 2 == 0:
11            if digits:
12                result.append(digits.pop())
13        else:
14            if letters:
15                result.append(letters.pop())
16    return ''.join(result)

Complexity note: The time complexity is O(n) because we traverse the string a couple of times (once for counting and once for building the result). The space complexity is O(n) for storing letters and digits separately.

  • 1The difference in counts of letters and digits must not exceed 1 for a valid reformat.
  • 2Always start with the character type that has more characters to maintain the alternating pattern.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.