Leetcode 1876: Substrings of Size Three with Distinct Characters

grid47
grid47
Exploring patterns and algorithms
May 3, 2024 4 min read

You are given a string s, and your task is to find the number of substrings of length 3 that contain no repeated characters. A substring is considered ‘good’ if all its characters are unique. Note that if a ‘good’ substring appears more than once, it should be counted multiple times.
Problem
Approach
Steps
Complexity
Input: You are given a string `s` which consists of lowercase English letters.
Example: For s = "abcabc".
Constraints:
• 1 <= s.length <= 100
• s consists of lowercase English letters.
Output: Return the number of 'good' substrings of length 3 in the string `s`.
Example: For the input s = "abcabc", the output is 4.
Constraints:
• The output should be a non-negative integer.
Goal: We need to find all substrings of length 3 and count those that have no repeated characters.
Steps:
• Iterate through the string from index 0 to n - 3.
• For each position, extract the substring of length 3 and check if all characters are unique.
• Count the valid substrings where all characters are distinct.
Goal: The string `s` should be a non-empty string containing only lowercase English letters.
Steps:
• 1 <= s.length <= 100
• s consists of lowercase English letters.
Assumptions:
• The string `s` contains at least one substring of length 3.
Input: For the input s = "abcabc".
Explanation: The substrings of length 3 are: 'abc', 'bca', 'cab', and 'abc'. All of these are 'good' substrings since they contain unique characters.

Input: For the input s = "aababcabc".
Explanation: The substrings of length 3 are: 'aab', 'aba', 'bab', 'abc', 'bca', 'cab', 'abc'. The 'good' substrings are 'abc', 'bca', and 'cab'.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus