KatInterview

Three-Part Drill: Anagram Buckets, One-Swap Max, Sentiment Top-K

StringsModel answer
MediumModel answerStringshash-mapanagramsgreedy

Last 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_keywords and negative_keywords, each given as a string or a list of words.
  • hotel_ids: an integer array parallel to reviews.
  • 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 +1 if it is a positive keyword, -1 if it is a negative keyword, and 0 otherwise.
  • 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 about 10^6, 1 <= k <= number of distinct hotels. If fewer than k hotels 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.