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 array fundamentals.
You are given an array of strings words and a string chars.
A string is good if it can be formed by characters from chars (each character can only be used once for each word in words).
Return the sum of lengths of all good strings in words.
Example 1:
Input: words = ["cat","bt","hat","tree"], chars = "atach" Output: 6 Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.
Example 2:
Input: words = ["hello","world","leetcode"], chars = "welldonehoneyr" Output: 10 Explanation: The strings that can be formed are "hello" and "world" so the answer is 5 + 5 = 10.
Constraints:
1 <= words.length <= 10001 <= words[i].length, chars.length <= 100words[i] and chars consist of lowercase English letters.Problem summary: You are given an array of strings words and a string chars. A string is good if it can be formed by characters from chars (each character can only be used once for each word in words). Return the sum of lengths of all good strings in words.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map
["cat","bt","hat","tree"] "atach"
["hello","world","leetcode"] "welldonehoneyr"
ransom-note)rearrange-characters-to-make-target-string)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1160: Find Words That Can Be Formed by Characters
class Solution {
public int countCharacters(String[] words, String chars) {
int[] cnt = new int[26];
for (int i = 0; i < chars.length(); ++i) {
++cnt[chars.charAt(i) - 'a'];
}
int ans = 0;
for (String w : words) {
int[] wc = new int[26];
boolean ok = true;
for (int i = 0; i < w.length(); ++i) {
int j = w.charAt(i) - 'a';
if (++wc[j] > cnt[j]) {
ok = false;
break;
}
}
if (ok) {
ans += w.length();
}
}
return ans;
}
}
// Accepted solution for LeetCode #1160: Find Words That Can Be Formed by Characters
func countCharacters(words []string, chars string) (ans int) {
cnt := [26]int{}
for _, c := range chars {
cnt[c-'a']++
}
for _, w := range words {
wc := [26]int{}
ok := true
for _, c := range w {
c -= 'a'
wc[c]++
if wc[c] > cnt[c] {
ok = false
break
}
}
if ok {
ans += len(w)
}
}
return
}
# Accepted solution for LeetCode #1160: Find Words That Can Be Formed by Characters
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
cnt = Counter(chars)
ans = 0
for w in words:
wc = Counter(w)
if all(cnt[c] >= v for c, v in wc.items()):
ans += len(w)
return ans
// Accepted solution for LeetCode #1160: Find Words That Can Be Formed by Characters
struct Solution;
use std::collections::HashMap;
impl Solution {
fn str_2_hs(s: &str) -> HashMap<char, i32> {
let mut hs: HashMap<char, i32> = HashMap::new();
for c in s.chars() {
*hs.entry(c).or_default() += 1;
}
hs
}
fn count_characters(words: Vec<String>, chars: String) -> i32 {
let chars = Self::str_2_hs(&chars);
let mut sum = 0;
for w in words {
let mut chars = chars.clone();
let mut valid = true;
for c in w.chars() {
let count = chars.entry(c).or_default();
*count -= 1;
if *count < 0 {
valid = false;
break;
}
}
if valid {
sum += w.len();
}
}
sum as i32
}
}
#[test]
fn test() {
let words = vec_string!["cat", "bt", "hat", "tree"];
let chars = "atach".to_string();
assert_eq!(Solution::count_characters(words, chars), 6);
let words = vec_string!["hello", "world", "leetcode"];
let chars = "welldonehoneyr".to_string();
assert_eq!(Solution::count_characters(words, chars), 10);
}
// Accepted solution for LeetCode #1160: Find Words That Can Be Formed by Characters
function countCharacters(words: string[], chars: string): number {
const idx = (c: string) => c.charCodeAt(0) - 'a'.charCodeAt(0);
const cnt = new Array(26).fill(0);
for (const c of chars) {
cnt[idx(c)]++;
}
let ans = 0;
for (const w of words) {
const wc = new Array(26).fill(0);
let ok = true;
for (const c of w) {
if (++wc[idx(c)] > cnt[idx(c)]) {
ok = false;
break;
}
}
if (ok) {
ans += w.length;
}
}
return ans;
}
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.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.