#2182

Construct String With Repeat Limit

Medium
Hash TableStringGreedyHeap (Priority Queue)CountingGreedy AlgorithmHeap (Priority Queue)Counting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log k)
Space
O(1)
O(k)
💡

Intuition

Time O(n log k)Space O(k)

The optimal approach uses a greedy strategy with a max heap to construct the result string in descending order. This ensures we always pick the largest character available while respecting the repeat limit.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each character in the string.
  2. 2Step 2: Use a max heap to store characters based on their lexicographical order.
  3. 3Step 3: Construct the result string by repeatedly adding characters from the heap, ensuring not to exceed the repeatLimit.
solution.py28 lines
1# Full working Python code
2import heapq
3from collections import Counter
4
5def repeatLimitedString(s, repeatLimit):
6    char_count = Counter(s)
7    max_heap = [-ord(char) for char in char_count]
8    heapq.heapify(max_heap)
9    result = ''
10
11    while max_heap:
12        current_char = -heapq.heappop(max_heap)
13        count = char_count[chr(current_char)]
14        use_count = min(count, repeatLimit)
15        result += chr(current_char) * use_count
16        char_count[chr(current_char)] -= use_count
17
18        if char_count[chr(current_char)] > 0:
19            if max_heap:
20                next_char = -heapq.heappop(max_heap)
21                result += chr(next_char)
22                char_count[chr(next_char)] -= 1
23                if char_count[chr(next_char)] > 0:
24                    heapq.heappush(max_heap, -next_char)
25                heapq.heappush(max_heap, -current_char)
26            else:
27                break
28    return result

Complexity note: The time complexity is O(n log k) where n is the length of the string and k is the number of unique characters. The heap operations take log k time.

  • 1Using a max heap allows us to efficiently access the largest character available.
  • 2Greedy algorithms often yield optimal solutions in string manipulation problems.

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