Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1].
The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit.
"345" and you enter in "012345":
0, the most recent 3 digits is "0", which is incorrect.1, the most recent 3 digits is "01", which is incorrect.2, the most recent 3 digits is "012", which is incorrect.3, the most recent 3 digits is "123", which is incorrect.4, the most recent 3 digits is "234", which is incorrect.5, the most recent 3 digits is "345", which is correct and the safe unlocks.Return any string of minimum length that will unlock the safe at some point of entering it.
Example 1:
Input: n = 1, k = 2 Output: "10" Explanation: The password is a single digit, so enter each digit. "01" would also unlock the safe.
Example 2:
Input: n = 2, k = 2 Output: "01100" Explanation: For each possible password: - "00" is typed in starting from the 4th digit. - "01" is typed in starting from the 1st digit. - "10" is typed in starting from the 3rd digit. - "11" is typed in starting from the 2nd digit. Thus "01100" will unlock the safe. "10011", and "11001" would also unlock the safe.
Constraints:
1 <= n <= 41 <= k <= 101 <= kn <= 4096Problem summary: There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1]. The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit. For example, the correct password is "345" and you enter in "012345": After typing 0, the most recent 3 digits is "0", which is incorrect. After typing 1, the most recent 3 digits is "01", which is incorrect. After typing 2, the most recent 3 digits is "012", which is incorrect. After typing 3, the most recent 3 digits is "123", which is incorrect. After typing 4, the most recent 3 digits is "234", which is incorrect. After typing 5, the most recent 3 digits is "345", which is correct and the safe unlocks. Return any string of minimum length that will unlock the safe at some point of entering it.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: General problem-solving
1 2
2 2
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #753: Cracking the Safe
class Solution {
private Set<Integer> vis = new HashSet<>();
private StringBuilder ans = new StringBuilder();
private int mod;
public String crackSafe(int n, int k) {
mod = (int) Math.pow(10, n - 1);
dfs(0, k);
ans.append("0".repeat(n - 1));
return ans.toString();
}
private void dfs(int u, int k) {
for (int x = 0; x < k; ++x) {
int e = u * 10 + x;
if (vis.add(e)) {
int v = e % mod;
dfs(v, k);
ans.append(x);
}
}
}
}
// Accepted solution for LeetCode #753: Cracking the Safe
func crackSafe(n int, k int) string {
mod := int(math.Pow(10, float64(n-1)))
vis := map[int]bool{}
ans := &strings.Builder{}
var dfs func(int)
dfs = func(u int) {
for x := 0; x < k; x++ {
e := u*10 + x
if !vis[e] {
vis[e] = true
v := e % mod
dfs(v)
ans.WriteByte(byte('0' + x))
}
}
}
dfs(0)
ans.WriteString(strings.Repeat("0", n-1))
return ans.String()
}
# Accepted solution for LeetCode #753: Cracking the Safe
class Solution:
def crackSafe(self, n: int, k: int) -> str:
def dfs(u):
for x in range(k):
e = u * 10 + x
if e not in vis:
vis.add(e)
v = e % mod
dfs(v)
ans.append(str(x))
mod = 10 ** (n - 1)
vis = set()
ans = []
dfs(0)
ans.append("0" * (n - 1))
return "".join(ans)
// Accepted solution for LeetCode #753: Cracking the Safe
struct Solution;
use std::collections::HashSet;
impl Solution {
fn crack_safe(n: i32, k: i32) -> String {
let n = n as usize;
let k = k as usize;
let mut seq = vec![0; n];
let mut visited: HashSet<Vec<u8>> = HashSet::new();
visited.insert(seq.clone());
let size = k.pow(n as u32);
Self::dfs(1, &mut visited, &mut seq, k, n, size);
seq.into_iter().map(|b| (b'0' + b) as char).collect()
}
fn dfs(
start: usize,
visited: &mut HashSet<Vec<u8>>,
seq: &mut Vec<u8>,
k: usize,
n: usize,
size: usize,
) -> bool {
if visited.len() == size {
return true;
}
for i in 0..k {
let mut suffix = seq[start..].to_vec();
suffix.push(i as u8);
if visited.insert(suffix.clone()) {
seq.push(i as u8);
if Self::dfs(start + 1, visited, seq, k, n, size) {
return true;
};
seq.pop();
visited.remove(&suffix);
}
}
false
}
}
#[test]
fn test() {
let n = 1;
let k = 2;
let res = "01".to_string();
assert_eq!(Solution::crack_safe(n, k), res);
let n = 2;
let k = 2;
let res = "00110".to_string();
assert_eq!(Solution::crack_safe(n, k), res);
}
// Accepted solution for LeetCode #753: Cracking the Safe
function crackSafe(n: number, k: number): string {
function dfs(u: number): void {
for (let x = 0; x < k; x++) {
const e = u * 10 + x;
if (!vis.has(e)) {
vis.add(e);
const v = e % mod;
dfs(v);
ans.push(x.toString());
}
}
}
const mod = Math.pow(10, n - 1);
const vis = new Set<number>();
const ans: string[] = [];
dfs(0);
ans.push('0'.repeat(n - 1));
return ans.join('');
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.