Three-Part Drill: Anagram Buckets, One-Swap Max, Sentiment Top-K
StringsModel answerLast updated
A three-part coding set: bucket words by letter makeup, maximize a number with at most one digit swap, and rank hotels by keyword-based review sentiment.
Solve the three problems below, as in a timed assessment of about 90 minutes. For each, give your approach, its complexity and working code.
Problem 1: Bucket words by letter makeup
You get an array strs of lowercase strings, possibly with duplicates and possibly containing empty strings. Partition them into groups so that every group holds strings that are rearrangements of one another.
- Output: a list of groups, each a list of strings. The order of groups and the order inside a group are not important.
- Constraints:
1 <= len(strs) <= 10^4,0 <= len(strs[i]) <= 100.
Problem 2: Best number from at most one digit swap
You get a non-negative integer num. You may exchange the positions of two of its digits once, or leave it alone. Return the largest value you can end up with.
- Constraints:
0 <= num <= 10^8.
Problem 3: Hotel leaderboard from review text
Inputs:
positive_keywordsandnegative_keywords, each given as a string or a list of words.hotel_ids: an integer array parallel toreviews.reviews: an array of strings.k: an integer.
Scoring:
- Break each review into words by treating every non-letter character (punctuation, digits, symbols, whitespace) as a separator.
- Matching ignores case.
- Each word occurrence adds
+1if it is a positive keyword,-1if it is a negative keyword, and0otherwise. - A hotel's total is the sum over all of its reviews.
Return the IDs of the top k hotels, ordered by higher total first and, when totals are equal, by smaller hotel_id first.
- Constraints:
1 <= len(reviews) == len(hotel_ids) <= 10^5, total review length up to about10^6,1 <= k <= number of distinct hotels. If fewer thankhotels exist in some variant, return all of them in the same order.
Be ready to discuss edge cases such as empty strings, repeated digits, hotels with no keyword hits, and negative totals.
Hints
Hint 1
For Problem 1, find a value that is identical for every rearrangement of a string and usable as a dictionary key. Remember that a list is not hashable, but a tuple or a string is.
Hint 2
For Problem 2, the leftmost digit that can be improved matters most. Record the last index of each digit 0-9, then scan left to right and look for a larger digit located further right. Consider why the last occurrence of that larger digit is the right one (think 1993).
Hint 3
For Problem 3, tokenize keywords and reviews with the exact same rule and lowercase both. Add every hotel to the score map even when its score is 0, then sort by (-score, hotel_id) and slice the first k.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Problem 1: Bucket words by letter makeup
Approach. Two strings are rearrangements of each other exactly when they have the same multiset of letters. Compute a canonical key from that multiset and use a hash map from key to list of strings.
- Sorted string key:
"".join(sorted(s)), costing O(L log L) per string. - Count-tuple key: 26 counts as a tuple, costing O(L) per string and better for long strings.
Equal multisets give equal keys and different multisets give different keys, so each bucket is exactly one anagram class. Duplicates share a key and are kept. The empty string gets an all-zero key and forms its own group.
Complexity. Time O(N·L) with count keys. Space O(N·L).
from collections import defaultdict
def group_anagrams(strs):
buckets = defaultdict(list)
for s in strs:
cnt = [0] * 26
for ch in s:
cnt[ord(ch) - 97] += 1
buckets[tuple(cnt)].append(s)
return list(buckets.values())
Common mistakes. Using a list as a dict key (raises TypeError), dropping duplicates by using a set, and forgetting the empty string.
Problem 2: Best number from at most one digit swap
Approach (greedy). Convert to a digit array. Precompute last[d], the last index where digit d occurs. Scan positions left to right. At position i, try digits d from 9 down to digits[i]+1. The first d with last[d] > i is the swap partner. Swap and return. If nothing is found, the digits are non-increasing and num is already optimal.
Why it is right.
- Improving the most significant position always beats any gain further right.
- The largest available larger digit gives the biggest value at that position.
- If that digit repeats, take its last occurrence. The smaller digit moves into that slot, and placing it as far right as possible hurts least. For
1993, swapping with the last 9 gives9913, while the first 9 gives9193.
Complexity. At most 9 digits, so O(D·10), effectively constant. A brute force over all pairs is O(D²) and also passes at these limits, but the greedy is what to present.
def maximum_swap(num):
digits = list(str(num))
last = {int(d): i for i, d in enumerate(digits)}
for i, ch in enumerate(digits):
for d in range(9, int(ch), -1):
j = last.get(d, -1)
if j > i:
digits[i], digits[j] = digits[j], digits[i]
return int("".join(digits))
return num
Edge cases. 0 and single digits return unchanged. 9973 needs no swap. 98368 becomes 98863.
Problem 3: Hotel leaderboard from review text
Approach.
- Normalize the keyword inputs. Accept a string or a list, join if needed, tokenize with the same regex as reviews, lowercase, and store in sets for O(1) lookup.
- Tokenize each review with
re.findall(r"[a-zA-Z]+", text). Every non-letter is a separator, so"clean,quiet!"givesclean,quiet, and"5star"givesstar. - Add each review's score to its hotel in a dict. Always touch the dict entry, so a hotel whose reviews contain no keywords still appears with 0.
- Rank by
(-score, hotel_id)and take the firstk. Slicing also handles the variant with fewer thankhotels.
Correctness. The total is additive over word occurrences, so summing per token and per review matches the definition. The sort key encodes the required order exactly. A word present in both keyword sets contributes +1 and -1, net 0. This follows the rules literally, and it is worth stating that assumption aloud.
Complexity. Time O(T + H log H), where T is the total text length and H the number of distinct hotels. With heapq.nsmallest(k, ...) the ranking step is O(H log k). Space O(H + P + Q) for the score map and keyword sets.
import re
import heapq
from collections import defaultdict
WORD = re.compile(r"[a-zA-Z]+")
def _to_set(words):
text = words if isinstance(words, str) else " ".join(words)
return {w.lower() for w in WORD.findall(text)}
def top_k_hotels(positive_keywords, negative_keywords, hotel_ids, reviews, k):
pos = _to_set(positive_keywords)
neg = _to_set(negative_keywords)
scores = defaultdict(int)
for hid, review in zip(hotel_ids, reviews):
s = 0
for w in WORD.findall(review):
w = w.lower()
if w in pos:
s += 1
if w in neg:
s -= 1
scores[hid] += s
best = heapq.nsmallest(k, scores.items(), key=lambda kv: (-kv[1], kv[0]))
return [hid for hid, _ in best]
Common mistakes.
- Using
split(), which leaves punctuation attached ("great!"fails to match). - Forgetting to lowercase one side.
- Omitting hotels with zero hits, so they are missing from the ranking.
- Sorting ties by score only, or placing negative-score hotels above zero-score ones.
- Hard-coding the keyword input as a list when it may be a string.
Time management
A reasonable split of a 90-minute window is about 15 minutes for Problem 1, 20 for Problem 2, and 35 for Problem 3, leaving time for testing with small hand-made cases such as [""], 1993, and a tie between two hotels.