#664
Strange Printer
HardStringDynamic ProgrammingDynamic ProgrammingMemoization
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n²) |
💡
Intuition
Time O(n²)Space O(n²)
The optimal solution uses dynamic programming to minimize the number of turns by considering overlapping subproblems. It builds on previously computed results to efficiently determine the minimum turns needed.
⚙️
Algorithm
3 steps- 1Step 1: Create a 2D array dp where dp[i][j] represents the minimum number of turns needed to print the substring s[i:j].
- 2Step 2: Initialize dp[i][i] to 1 for all i since a single character requires one turn.
- 3Step 3: For each substring length, calculate the minimum turns by checking if the characters at the start and end are the same, and use previously computed results to minimize the current value.
solution.py12 lines
1def strangePrinter(s):
2 n = len(s)
3 dp = [[0] * n for _ in range(n)]
4 for i in range(n):
5 dp[i][i] = 1
6 for length in range(2, n + 1):
7 for i in range(n - length + 1):
8 j = i + length - 1
9 dp[i][j] = dp[i][j - 1] + 1
10 if s[j] == s[i]:
11 dp[i][j] = min(dp[i][j], dp[i][j - 1])
12 return dp[0][n - 1]ℹ
Complexity note: The time complexity is O(n²) due to the nested loops iterating over the string length. The space complexity is O(n²) because we store results in a 2D array.
- 1The printer can cover existing characters, allowing for fewer turns.
- 2Identifying overlapping subproblems helps in optimizing the solution.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.