Ctrl K

Closed Pieces of a String

Medium
Call a piece (a contiguous substring) of text **closed** when: - every letter that occurs in it occurs nowhere else in text, outside this piece; - the piece is not the whole of text. You are given a number need. Is it possible to choose need closed pieces that pairwise do not overlap? Return True or False. When need = 0 the answer is always True.
Example 1
text="xyxpqrzz", need=3 → True

Pieces like "xyx", "p", "q", "r" and "zz" work: their letters appear nowhere else. For instance "xyx", "p" and "q" are three non-overlapping pieces.

Example 2
text="abba", need=1 → True

The piece "bb" is closed: the letter b occurs only inside it. So one piece can be cut.

Example 3
text="abab", need=1 → False

Any piece with a or b must contain every copy of both letters, which is the whole string, and that is not allowed.

Constraints
  • 2 ≤ len(text) ≤ 5·10⁴
  • text consists of lowercase English letters
  • 0 ≤ need ≤ 26
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsNo Twin Letters Side by Side MediumWords Hidden in a Text MediumWord Growth Chain MediumDistinct Letter Counts MediumNine-Button Layout Medium
loading Python…
Input
text="xyxpqrzz", need=3
Expected
True

Run checks the first 3 tests in your browser. Submit checks all 98 tests on the server, hidden ones included.