KatInterview

Balanced Character Rewriting and Offline Grid Threshold Queries

Math & Bit ManipulationModel answer
HardModel answerMath & Bit Manipulationbit-manipulation2d-fenwick-treesweep-line

Last updated

Solve parity-based string transformation via bitmasks and handle offline 2D range count queries using dynamic point-update data structures.

This task consists of two independent algorithmic components:

Task 1: Parity Balancing via Letter Replacement

We define a string as balanced if every character occurring in it appears an even number of times. You are given a string s containing characters chosen exclusively from the first 10 lowercase letters of the alphabet ('a' through 'j').

Write a function min_replacements_to_balance(s) that determines the minimum number of character replacements necessary to convert s into a balanced string. If converting s into a balanced string via replacements is impossible, return -1.

Task 2: Threshold-Filtered Subgrid Range Counts

Given an $N \times N$ matrix grid filled with positive integers and a list of $Q$ queries, process each query efficiently. A query is defined by a rectangular bounding box with top-left corner $(r1, c1)$, bottom-right corner $(r2, c2)$, and an integer lower bound $K$.

For each query, return the total count of matrix elements within the specified bounding box (inclusive) whose values are at least $K$.

Input Constraints

  • Alphabet size for Task 1: 10 ('a' through 'j')
  • Length of s $\le 100,000$
  • Grid dimensions: $N \times N$ where $N \le 1,000$
  • Number of queries: $Q \le 100,000$
  • Grid values and query threshold $K$: non-negative integers

Examples

Task 1 Example:

Input: s = "abcabc"
Output: 0
Explanation: Every letter ('a', 'b', 'c') appears exactly twice (even frequency). No replacements are required.

Task 2 Example:

Input: grid = [[1, 5], [2, 8]], query = (r1=0, c1=0, r2=1, c2=1, K=5)
Output: 2
Explanation: In the 2x2 region from (0,0) to (1,1), the elements 5 and 8 are >= 5.

Hints

Hint 1

For Task 1: Notice how replacing a single character changes the parities of exactly two characters (one count decreases by 1, another increases by 1). Can an odd-length string ever be balanced?

Hint 2

For Task 1: Use a 10-bit bitmask where the i-th bit represents whether the i-th letter has an odd count.

Hint 3

For Task 2: Since the queries are given up front, process them offline by sorting both matrix cells and queries by value/threshold in descending order.

Hint 4

For Task 2: A 2D Binary Indexed Tree (Fenwick Tree) allows O(log^2 N) point updates and 2D prefix sum queries.