Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Rearrangement String Match and Pattern

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Rearrangement String Match and Pattern. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Betterworks may need to validate whether a selected portion of one goal update can be rearranged to form another phrase. Given two strings, source and target, return True if characters from source can be selected and rearranged to form target; otherwise, return False.

The selected characters do not need to be contiguous, and every character in target must be matched with a distinct occurrence in source. Matching is case-sensitive, and spaces, punctuation, and digits are treated as ordinary characters.

Formal Specification

Implement can_rearrange(source, target).

  • Input: two strings, source and target.
  • Output: a boolean indicating whether source contains at least the required frequency of every character in target.

Constraints

  • 0 <= len(source), len(target) <= 10^5
  • Strings contain printable ASCII characters
  • Character matching is case-sensitive
  • Repeated target characters require repeated source occurrences

Function Signature

def can_rearrange(source, target):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output