The Maximum Manhattan Distance After K Changes coding problem gives you a string of directional moves (North, South, East, West) and a budget of K changes. You can change any K characters in the string to any direction. After all moves are executed, you want to maximize the Manhattan distance from the origin. This is an optimization problem combining string manipulation with coordinate geometry.
Uber, Microsoft, Meta, and Bloomberg use this problem to test candidates' ability to think about what "optimal" means in a spatial context. The key insight is that Manhattan distance from origin after n moves is maximized when moves are as aligned as possible (all in one axis direction or split optimally). Counting-based analysis and greedy allocation of change budget define the solution approach.
The solution uses counting and greedy allocation. Count the moves in each direction: N, S, E, W counts. The net displacement on the y-axis is |N - S| and on x-axis is |E - W|. Total Manhattan distance is |N-S| + |E-W|. To maximize this, you want to "convert" opposing moves to the dominant direction. With K changes, you can convert opposing moves to the dominant direction, effectively doubling the impact of each change. The optimal strategy converts moves that cancel the dominant axis. Binary search or direct counting gives the maximum distance achievable with exactly K changes.
Moves: "NSEWS", K = 2.
For the Math Hash Table Counting String interview pattern, frame this problem as: "I have cancelling pairs; each change I make eliminates one cancelling pair and adds one to the dominant direction." This +2 per change insight (not +1) is the key to the greedy calculation. Practice similar "maximize net displacement with K flips" problems to internalize this pattern.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count the Number of Good Subsequences | Medium | Solve | |
| Total Characters in String After Transformations I | Medium | Solve | |
| Sum of Beauty of All Substrings | Medium | Solve | |
| Bulls and Cows | Medium | Solve | |
| Fraction to Recurring Decimal | Medium | Solve |