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.
Build confidence with an intuition-first walkthrough focused on core interview patterns fundamentals.
You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits).
You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type.
Return the reformatted string or return an empty string if it is impossible to reformat the string.
Example 1:
Input: s = "a0b1c2" Output: "0a1b2c" Explanation: No two adjacent characters have the same type in "0a1b2c". "a0b1c2", "0a1b2c", "0c2a1b" are also valid permutations.
Example 2:
Input: s = "leetcode" Output: "" Explanation: "leetcode" has only characters so we cannot separate them by digits.
Example 3:
Input: s = "1229857369" Output: "" Explanation: "1229857369" has only digits so we cannot separate them by characters.
Constraints:
1 <= s.length <= 500s consists of only lowercase English letters and/or digits.Problem summary: You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Return the reformatted string or return an empty string if it is impossible to reformat the string.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: General problem-solving
"a0b1c2"
"leetcode"
"1229857369"
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1417: Reformat The String
class Solution {
public String reformat(String s) {
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
a.append(c);
} else {
b.append(c);
}
}
int m = a.length(), n = b.length();
if (Math.abs(m - n) > 1) {
return "";
}
StringBuilder ans = new StringBuilder();
for (int i = 0; i < Math.min(m, n); ++i) {
if (m > n) {
ans.append(a.charAt(i));
ans.append(b.charAt(i));
} else {
ans.append(b.charAt(i));
ans.append(a.charAt(i));
}
}
if (m > n) {
ans.append(a.charAt(m - 1));
}
if (m < n) {
ans.append(b.charAt(n - 1));
}
return ans.toString();
}
}
// Accepted solution for LeetCode #1417: Reformat The String
func reformat(s string) string {
a := []byte{}
b := []byte{}
for _, c := range s {
if unicode.IsLetter(c) {
a = append(a, byte(c))
} else {
b = append(b, byte(c))
}
}
if len(a) < len(b) {
a, b = b, a
}
if len(a)-len(b) > 1 {
return ""
}
var ans strings.Builder
for i := range b {
ans.WriteByte(a[i])
ans.WriteByte(b[i])
}
if len(a) > len(b) {
ans.WriteByte(a[len(a)-1])
}
return ans.String()
}
# Accepted solution for LeetCode #1417: Reformat The String
class Solution:
def reformat(self, s: str) -> str:
a = [c for c in s if c.islower()]
b = [c for c in s if c.isdigit()]
if abs(len(a) - len(b)) > 1:
return ''
if len(a) < len(b):
a, b = b, a
ans = []
for x, y in zip(a, b):
ans.append(x + y)
if len(a) > len(b):
ans.append(a[-1])
return ''.join(ans)
// Accepted solution for LeetCode #1417: Reformat The String
struct Solution;
use std::mem::swap;
impl Solution {
fn reformat(s: String) -> String {
let mut chars: Vec<char> = vec![];
let mut digits: Vec<char> = vec![];
let mut res: Vec<char> = vec![];
for c in s.chars() {
if c.is_digit(10) {
digits.push(c);
} else {
chars.push(c);
}
}
let mut iter;
let mut next_iter;
if digits.len() >= chars.len() {
if digits.len() > chars.len() + 1 {
return "".to_string();
} else {
iter = digits.iter();
next_iter = chars.iter();
}
} else {
if chars.len() > digits.len() + 1 {
return "".to_string();
} else {
iter = chars.iter();
next_iter = digits.iter();
}
}
while let Some(c) = iter.next() {
res.push(*c);
swap(&mut iter, &mut next_iter);
}
res.into_iter().collect()
}
}
#[test]
fn test() {
let s = "a0b1c2".to_string();
let res = "0a1b2c".to_string();
assert_eq!(Solution::reformat(s), res);
let s = "leetcode".to_string();
let res = "".to_string();
assert_eq!(Solution::reformat(s), res);
let s = "1229857369".to_string();
let res = "".to_string();
assert_eq!(Solution::reformat(s), res);
let s = "covid2019".to_string();
let res = "c2o0v1i9d".to_string();
assert_eq!(Solution::reformat(s), res);
let s = "ab123".to_string();
let res = "1a2b3".to_string();
assert_eq!(Solution::reformat(s), res);
}
// Accepted solution for LeetCode #1417: Reformat The String
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1417: Reformat The String
// class Solution {
// public String reformat(String s) {
// StringBuilder a = new StringBuilder();
// StringBuilder b = new StringBuilder();
// for (char c : s.toCharArray()) {
// if (Character.isDigit(c)) {
// a.append(c);
// } else {
// b.append(c);
// }
// }
// int m = a.length(), n = b.length();
// if (Math.abs(m - n) > 1) {
// return "";
// }
// StringBuilder ans = new StringBuilder();
// for (int i = 0; i < Math.min(m, n); ++i) {
// if (m > n) {
// ans.append(a.charAt(i));
// ans.append(b.charAt(i));
// } else {
// ans.append(b.charAt(i));
// ans.append(a.charAt(i));
// }
// }
// if (m > n) {
// ans.append(a.charAt(m - 1));
// }
// if (m < n) {
// ans.append(b.charAt(n - 1));
// }
// return ans.toString();
// }
// }
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.