Bird
Raised Fist0
Interview Preptwo-heapshardAmazonGoogleFacebook

Rearrange String k Distance Apart

Choose your preparation mode4 modes available
</>
IDE
def rearrangeString(s: str, k: int) -> str:public String rearrangeString(String s, int k)string rearrangeString(string s, int k)function rearrangeString(s, k)
def rearrangeString(s, k):
    # Write your solution here
    pass
class Solution {
    public String rearrangeString(String s, int k) {
        // Write your solution here
        return "";
    }
}
#include <string>
using namespace std;

string rearrangeString(string s, int k) {
    // Write your solution here
    return "";
}
function rearrangeString(s, k) {
    // Write your solution here
}
Coming soon
0/10
Common Bugs to Avoid
Wrong: Non-empty string when rearrangement is impossibleNot detecting when max frequency characters cannot be spaced k apart✅ Add a check: if max frequency > (n + k - 1) / k, return empty string
Wrong: Original string returned even when k > 0 and rearrangement neededIgnoring k distance constraint or treating k=0 case incorrectly✅ Return original string only if k == 0; otherwise enforce rearrangement
Wrong: Characters repeated too close togetherGreedy approach without cooldown queue allowing reuse before k distance✅ Use a cooldown queue to delay reuse of characters until k positions later
Wrong: Empty string returned for single character inputNot handling single character or empty input base cases✅ Return input string immediately if length is 0 or 1
Wrong: Unnecessary rearrangement when all characters are uniqueNot checking for uniqueness and large k values✅ Return original string if all characters are unique
✓
Test Cases
t1_01basic
Input{"s":"aabbcc","k":3}
Expected"abcabc"

Characters 'a', 'b', and 'c' are spaced at least 3 apart in the rearranged string.

t1_02basic
Input{"s":"aaabc","k":3}
Expected"abaca"

Rearranged string 'abaca' spaces 'a' characters at least 3 apart.

t2_01edge
Input{"s":"","k":2}
Expected""

Empty string input returns empty string output.

t2_02edge
Input{"s":"a","k":1}
Expected"a"

Single character string with k=1 returns the original string.

t2_03edge
Input{"s":"aa","k":2}
Expected""

Impossible to rearrange 'aa' with k=2 since characters must be at least 2 apart.

t2_04edge
Input{"s":"abcdef","k":6}
Expected"abcdef"

All characters unique and k equals string length, so original string is valid.

t3_01corner
Input{"s":"aaabbbcc","k":3}
Expected"abcabcab"

Greedy approach that picks highest frequency first but must maintain cooldown to avoid clustering.

t3_02corner
Input{"s":"aaabc","k":0}
Expected"aaabc"

k=0 means no spacing constraint, original string returned.

t3_03corner
Input{"s":"aaabbc","k":3}
Expected"abacab"

Tests correct handling of 0/1 constraint, ensuring characters are used once per cooldown period.

t4_01performance
Input{"s":"aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd","k":10}
⏱ Performance - must finish in 2000ms

Large input with n=40 and k=10 to test O(n log m) heap-based solution performance within 2 seconds.

Practice

(1/5)
1. You need to find the median of every contiguous subarray of size k in an integer array efficiently. Which approach best guarantees an optimal solution for this problem?
easy
A. Use a dynamic programming approach to precompute medians for all subarrays
B. Sort each window independently and pick the median
C. Maintain two balanced heaps (max-heap and min-heap) with lazy removal to track the median as the window slides
D. Use a sliding window with a simple queue and recompute median by scanning the window each time

Solution

  1. Step 1: Understand the problem constraints

    Finding median in each sliding window requires efficient insertion, deletion, and median retrieval.
  2. Step 2: Evaluate approaches

    Sorting each window (A) is too slow (O(nk log k)). DP (C) doesn't apply well to median. Simple queue (D) can't maintain order efficiently. Balanced two heaps (B) maintain order and allow O(log k) updates.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Two heaps maintain median efficiently [OK]
Hint: Two heaps efficiently maintain median in sliding window [OK]
Common Mistakes:
  • Thinking sorting each window is efficient enough
  • Assuming DP can precompute medians
  • Using simple queue without order maintenance
2. You are given a list of intervals, each with a start and end time. For each interval, you want to find the interval with the smallest start time that is greater than or equal to the end time of the current interval. Which approach guarantees an optimal solution in terms of time complexity?
easy
A. Use two max-heaps: one for interval starts and one for interval ends, to efficiently find the next interval.
B. Use a greedy algorithm that picks the earliest finishing interval first.
C. Sort intervals by start time and use dynamic programming to find the next interval.
D. Use a brute force nested loop to compare each interval with every other interval.

Solution

  1. Step 1: Understand problem requirements

    The problem requires finding, for each interval, the next interval with the smallest start time ≥ current interval's end time.
  2. Step 2: Evaluate approaches

    Brute force (nested loops) is correct but inefficient (O(n²)). Sorting + binary search is efficient but requires extra steps. The two max-heaps approach efficiently tracks max starts and ends to find next intervals in O(n log n) time, guaranteeing optimality.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Two heaps approach matches the problem's need for efficient next interval lookup [OK]
Hint: Two heaps efficiently track max starts and ends [OK]
Common Mistakes:
  • Assuming greedy earliest finish works
  • Using DP unnecessarily
  • Brute force accepted as optimal
3. Consider the following Python code snippet implementing the brute force approach for sliding window median. What is the output of result after processing nums = [1, 3, -1, -3] with k = 3?
easy
A. [1.0, -1.0]
B. [1.0, 3.0]
C. [1.0, -1.0, -3.0]
D. [1.0, 0.0]

Solution

  1. Step 1: Trace first window [1, 3, -1]

    Sorted window is [-1, 1, 3], median is middle element 1.0.
  2. Step 2: Trace second window [3, -1, -3]

    Sorted window is [-3, -1, 3], median is middle element -1.0.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Two medians computed correctly for windows of size 3 [OK]
Hint: Sort each window and pick middle element for odd k [OK]
Common Mistakes:
  • Off-by-one error in window slicing
  • Incorrect median index for odd k
  • Confusing median calculation for even k
4. Consider the following buggy code snippet for the IPO problem. Which line contains the subtle bug that causes incorrect results or inefficiency?
medium
A. Line pushing projects into min_capital_heap without sorting
B. Line popping from min_capital_heap in the while loop
C. Line pushing profits into max_profit_heap with negation
D. Line breaking the loop when max_profit_heap is empty

Solution

  1. Step 1: Identify heap initialization

    Projects are pushed into min_capital_heap without sorting by capital, which is required for efficient affordability checks.
  2. Step 2: Understand impact

    Without sorting, min_capital_heap may not have the smallest capital project at the top, breaking the affordability filtering logic.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Min-heap must be built from sorted projects or pushed in sorted order [OK]
Hint: Min-heap top must be smallest capital project [OK]
Common Mistakes:
  • Assuming heapq.heappush sorts automatically
  • Confusing max-heap and min-heap roles
  • Ignoring early stopping condition
5. Suppose projects can be selected multiple times (reused) in the IPO problem. Which modification to the two-heaps algorithm correctly handles this scenario?
hard
A. Use a max-heap only and pick the top K profitable projects ignoring capital constraints
B. Do not remove projects from min-capital heap; instead, keep all projects always available
C. After selecting a project, reinsert it into the min-capital heap to allow reuse
D. After selecting a project, do not remove it from max-profit heap to allow repeated selection

Solution

  1. Step 1: Understand reuse implication

    Allowing reuse means projects remain available after selection, so they must be reinserted to be considered again.
  2. Step 2: Modify algorithm accordingly

    After popping a project from min-capital heap and selecting it, reinsert it to allow future reuse; otherwise, it disappears from consideration.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Reinserting projects enables multiple selections [OK]
Hint: Reinsert projects after selection to allow reuse [OK]
Common Mistakes:
  • Ignoring reinsertion, losing projects after first pick
  • Keeping all projects always available breaks capital filtering
  • Ignoring capital constraints when reusing projects
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard