Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2287: Rearrange Characters to Make Target String

In this guide, we solve Leetcode #2287 Rearrange Characters to Make Target String in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

You are given two 0-indexed strings s and target. You can take some letters from s and rearrange them to form new strings.

Quick Facts

  • Difficulty: Easy
  • Premium: No
  • Tags: Hash Table, String, Counting

Intuition

Fast membership checks and value lookups are the heart of this problem, which makes a hash map the natural choice.

By storing what we have already seen (or counts/indexes), we can answer the question in one pass without backtracking.

Approach

Scan the input once, using the map to detect when the condition is satisfied and to update state as you go.

This keeps the solution linear while remaining easy to explain in an interview setting.

Steps:

  • Initialize a hash map for seen items or counts.
  • Iterate through the input, querying/updating the map.
  • Return the first valid result or the final computed value.

Example

Input: s = "ilovecodingonleetcode", target = "code" Output: 2 Explanation: For the first copy of "code", take the letters at indices 4, 5, 6, and 7. For the second copy of "code", take the letters at indices 17, 18, 19, and 20. The strings that are formed are "ecod" and "code" which can both be rearranged into "code". We can make at most two copies of "code", so we return 2.

Python Solution

class Solution: def rearrangeCharacters(self, s: str, target: str) -> int: cnt1 = Counter(s) cnt2 = Counter(target) return min(cnt1[c] // v for c, v in cnt2.items())

Complexity

The time complexity is O(n+m)O(n + m)O(n+m), and the space complexity is O(∣Σ∣)O(|\Sigma|)O(∣Σ∣). The space complexity is O(∣Σ∣)O(|\Sigma|)O(∣Σ∣).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy