## Similar Problems

Similar Problems not available

# Cracking The Safe - Leetcode Solution

## Companies:

LeetCode: Cracking The Safe Leetcode Solution

Difficulty: Hard

Topics: depth-first-search graph

Problem statement: You have a bomb with an integer keypad and a diffuser to defuse it. The keypad has digits from 1 to 9 and it is now showing a string of n digits. Each key can be pressed any number of times. The diffuser is programmed to decode a sequence c of n digits. You have to determine the number of distinct sequences of c that can be obtained by pressing the keys on the keypad in some order. There are no other restrictions.

Solution: This problem can be solved using dynamic programming. The idea is to consider each digit in the sequence c one by one and determine the number of distinct sequences that can be obtained while considering the current digit. We can use a two-dimensional array dp[n][k] to store the number of distinct sequences of length n that can be obtained using the first k digits of the keypad. We can then use this array to compute the solution for the next digit.

The time complexity of this approach is O(n^3) and the space complexity is O(n^2). However, we can optimize the space complexity to O(n) by using a one-dimensional array instead of a two-dimensional array. The optimized approach is explained below.

Let dp[k] be the number of distinct sequences of length k that can be obtained using the first k digits of the keypad. We can then compute the value of dp[k+1] using the following formula:

dp[k+1] = sum(dp[i]) * (10 - i)

where i ranges from 0 to k. The idea is that we can append any digit to a sequence of length k and obtain a sequence of length k+1. The number of ways to append a digit i to a sequence of length k is dp[k][i]. The total number of ways to append any digit to a sequence of length k is sum(dp[k]). The number of distinct sequences of length k+1 that can be obtained using the first k+1 digits of the keypad is then given by sum(dp[k+1]).

The time complexity of this optimized approach is O(n^2) and the space complexity is O(n).

Here's the Python code for the optimized approach:

def crackSafe(n: int, k: int) -> str: if n == 1: return "".join(str(i) for i in range(k))

```
dp = [0] * (n+1)
dp[1] = k
ans = [0] * n
ans[0] = '0'
for i in range(2, n+1):
dp[i] = dp[i-1] * (k-1) + k
ans[i-1] = '0'
for i in range(n-2, -1, -1):
for j in range(1, k):
if dp[i+1] <= dp[i] * (k-1) + j:
ans[i] = str(j)
dp[i+1] -= j
break
dp[i+1] -= dp[i] * (k-1)
return "".join(ans)
```

## Cracking The Safe Solution Code

`1`