Similar Problems

Similar Problems not available

Smallest K Length Subsequence With Occurrences Of A Letter - Leetcode Solution

Companies:

LeetCode:  Smallest K Length Subsequence With Occurrences Of A Letter Leetcode Solution

Difficulty: Hard

Topics: greedy string stack  

Problem Statement:

Given a string s, an integer k and a lowercase letter letter, return the length of the smallest subsequence of s of length k such that the subsequence contains at least one occurrence of letter. If there is no such subsequence, return -1.

Solution:

We can solve this problem by iterating over the string, identifying all indices at which the letter occurs. Then for each index at which the letter occurs, we can add the k characters surrounding it (with wraparound if necessary) to a set. After processing all occurrences of the letter, we can return the size of the smallest set that we've constructed.

Let's break this down into steps.

  1. Identify all indices at which the letter occurs in the string s.

We can do this by iterating over the string and adding each index at which the letter occurs to a set.

indices = set()
for i in range(len(s)):
    if s[i] == letter:
        indices.add(i)
  1. For each index at which the letter occurs, add the k characters surrounding it (with wraparound) to a set.

We can do this by iterating over the indices at which the letter occurs, and adding the appropriate characters to a set with a helper function add_chars_to_set.

def add_chars_to_set(s, indices, i, k, s_set):
    for j in range(i - k + 1, i + k):
        idx = j % len(s)
        if idx in indices:
            s_set.add(s[idx])
    return s_set

s_set = set()
for i in indices:
    s_set = add_chars_to_set(s, indices, i, k, s_set)
  1. Return the size of the smallest set that we've constructed.
if len(s_set) < k:
    return -1
else:
    return len(s_set)

Putting it all together:

def smallestSubsequence(s: str, k: int, letter: str) -> int:
    indices = set()
    for i in range(len(s)):
        if s[i] == letter:
            indices.add(i)

    def add_chars_to_set(s, indices, i, k, s_set):
        for j in range(i - k + 1, i + k):
            idx = j % len(s)
            if idx in indices:
                s_set.add(s[idx])
        return s_set

    s_set = set()
    for i in indices:
        s_set = add_chars_to_set(s, indices, i, k, s_set)

    if len(s_set) < k:
        return -1
    else:
        return len(s_set)

Complexity Analysis:

  • Time Complexity: O(NK) where N is the length of the input string s. For each index at which the letter occurs, we add k characters to a set. This takes O(K) time, and we do this for each of the O(N) indices at which the letter occurs, giving us a total time complexity of O(NK).
  • Space Complexity: O(K) for the set containing the k characters that we return.

Smallest K Length Subsequence With Occurrences Of A Letter Solution Code

1