Skip to content

LeetCode - Find K-Length Substrings#223

Merged
pertrai1 merged 1 commit into
mainfrom
leetcode-222026
Feb 3, 2026
Merged

LeetCode - Find K-Length Substrings#223
pertrai1 merged 1 commit into
mainfrom
leetcode-222026

Conversation

@pertrai1

@pertrai1 pertrai1 commented Feb 2, 2026

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Added problem 1084 - Find K-Length Substrings With No Repeated Characters to the collection.
  • Documentation

    • Added complete problem documentation including description, examples, and constraints.
    • Updated overview to reflect 173 total problems (up from 172).

@pertrai1 pertrai1 requested a review from Copilot February 2, 2026 14:29
@pertrai1 pertrai1 added the code challenge this is a coding challenge label Feb 2, 2026
@github-actions

github-actions Bot commented Feb 2, 2026

Copy link
Copy Markdown

Claude finished @pertrai1's task in 1m 29s —— View job


Code Review - LeetCode #1084: Find K-Length Substrings With No Repeated Characters

Great work on this solution! This is a clean implementation of the fixed-size sliding window pattern. Let me provide educational feedback to help reinforce the concepts.


✅ Algorithm Correctness

The solution is correct and handles all edge cases properly:

  • ✅ Correctly handles k > n (returns 0)
  • ✅ Properly initializes the first window of size k
  • ✅ Slides the window correctly by adding new character and removing old character
  • ✅ Counts valid windows when window.size === k (meaning all k characters are distinct)

Mental trace with Example 1:

s = "havefunonleetcode", k = 5

Initial window: "havef" → {h:1, a:1, v:1, e:1, f:1} → size=5 ✓ count=1
Slide: "avefu" → {a:1, v:1, e:1, f:1, u:1} → size=5 ✓ count=2
Slide: "vefun" → {v:1, e:1, f:1, u:1, n:1} → size=5 ✓ count=3
...continues correctly

📊 Complexity Analysis

Time Complexity: The documented O(n) is correct.

Why? Each character is:

  • Added to the map exactly once (line 27)
  • Removed from the map exactly once (lines 30-36)
  • All map operations (.get(), .set(), .delete()) are O(1)

Total: O(n) + O(n) = O(n) where n is s.length.

Space Complexity: The documented O(n) is slightly imprecise but acceptable.

More accurately: O(min(k, 26)) = O(k) in practice

  • The map stores at most k characters (the window size)
  • Since s consists only of lowercase letters (26 possibilities), the map never exceeds size 26
  • For this problem: O(min(k, 26)) which simplifies to O(k) or O(1) depending on perspective

This is a minor point—your O(n) answer is acceptable since k could theoretically equal n.


🎯 Algorithmic Pattern: Fixed-Size Sliding Window

Pattern Name: Fixed-Size Sliding Window

Why this pattern?
This problem requires examining every contiguous substring of exactly length k, making it a perfect fit for the fixed-size sliding window pattern. The "no repeated characters" constraint is efficiently tracked using a frequency map.

Pattern Characteristics:

  1. ✅ Fixed window size (k)
  2. ✅ Maintain state (frequency map) as window slides
  3. ✅ Add new element to the right
  4. ✅ Remove old element from the left
  5. ✅ Check validity condition (window.size === k)

💡 Key Insight

The key insight: Instead of checking all characters in each substring for duplicates (which would be O(k) per window), we maintain a frequency map that allows us to check for uniqueness in O(1) time by simply comparing map.size === k.

If the map size equals k, it means all k characters in the window are distinct. If map size < k, at least one character appears more than once.


🐛 Minor Issue Found

Typo in comment (line 29):

leetcode/medium/1084-find-k-length-substrings-with-no-repeated-characters/find-k-length-substrings-with-no-repeated-characters.ts:29

// remove olde character

Should be: // remove old character (typo: "olde" → "old")


💻 Code Quality

Strengths:

  • ✅ Clear variable names (window, count, oldChar, oldCount)
  • ✅ Good comments explaining major steps
  • ✅ Proper use of const and let
  • ✅ Modern ES6+ syntax (Map, arrow function would work but function declaration is fine for LeetCode)
  • ✅ Clean separation: initialize window, then slide window

Suggestions:

  • Minor: Consider const charCount = window.get(s[i]) || 0 for slightly cleaner increment logic
  • Minor: The space complexity comment could be more precise (O(k) or O(min(k, 26)))

🔗 Related Problems (Same Pattern)

Practice these to reinforce the fixed-size sliding window pattern:

  1. LeetCode 438 - Find All Anagrams in a String (Medium)

    • Fixed window of size p.length, check if window is an anagram
    • Same pattern: maintain frequency map, slide window, check condition
  2. LeetCode 567 - Permutation in String (Medium)

    • Fixed window matching character frequencies
    • Very similar: frequency map + fixed-size sliding window
  3. LeetCode 219 - Contains Duplicate II (Easy)

    • Fixed window of size k + 1, check for duplicates
    • Same pattern but using Set instead of Map

⚠️ Common Mistakes with This Pattern

  1. Forgetting to remove old elements: A common mistake is adding new elements but forgetting to remove elements that leave the window, causing the window to grow indefinitely.

  2. Off-by-one errors: Be careful with window boundaries. In this solution, the old character is at index i - k when adding character at index i.

  3. Not handling frequency properly: When decrementing frequency, must delete from map when count reaches 0, otherwise map.size doesn't reflect distinct characters.

  4. Checking size incorrectly: Comparing window.size === k only works because we properly delete entries when count hits 0.


🎓 Learning Summary

Pattern Mastered: Fixed-Size Sliding Window with Frequency Tracking

Key Takeaways:

  1. Fixed-size sliding windows maintain exactly k elements at all times (after initialization)
  2. Frequency maps enable O(1) duplicate checking via .size property
  3. Always maintain map correctness: delete entries when frequency reaches 0
  4. This pattern is optimal: O(n) time, O(k) space

When to use this pattern:

  • Problem mentions "substring/subarray of size k"
  • Need to check properties of all fixed-size windows
  • Can maintain state incrementally (don't need to recompute from scratch)

Next Steps:


📝 Summary

This is an excellent solution demonstrating strong understanding of the fixed-size sliding window pattern! The algorithm is correct, efficient, and well-structured. The only issue is a minor typo in a comment. The complexity analysis is correct (though could be slightly more precise on space complexity). Great work organizing this solution into the proper directory structure! 🎉


@coderabbitai

coderabbitai Bot commented Feb 2, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Added LeetCode problem #1084 (Find K-Length Substrings With No Repeated Characters) to the repository, including problem documentation, solution code, and updates to the main problem index. Converted the solution function from private to public export.

Changes

Cohort / File(s) Summary
Documentation Updates
README.md
Incremented total problem count from 172 to 173 and added new problem entry for #1084 under String Manipulation pattern and Sliding Window subsection.
Problem Documentation
leetcode/medium/1084-find-k-length-substrings-with-no-repeated-characters/README.md
Created new documentation file with problem statement, two worked examples, and constraints section.
Solution Code
leetcode/medium/1084-find-k-length-substrings-with-no-repeated-characters/find-k-length-substrings-with-no-repeated-characters.ts
Exported the numKLenSubstrNoRepeats function to make it publicly accessible; minor formatting adjustments to align with TS module standards.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 A problem new, now added to our store,
Problem eleven-hundred eighty-four,
With substrings of length k dancing without fear,
No repeated characters shall appear,
Our sliding window solution shines bright and clear! 🪟✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main change: adding a new LeetCode problem solution for finding K-length substrings with no repeated characters.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch leetcode-222026

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Feb 2, 2026

Copy link
Copy Markdown

🤖 Gemini Code Review (Model: gemini-2.5-flash)

Here's a detailed review of your LeetCode solution for "Find K-Length Substrings With No Repeated Characters":


1. Pattern Identification

This solution clearly uses the Sliding Window pattern. Specifically, it employs a variable-size sliding window which is then adjusted to a fixed size k once the window contains k unique characters. The window expands by moving the right pointer and shrinks by moving the left pointer.

2. Complexity Verification

  • Stated Time Complexity: O(n) where n is the length of s

    • Verification: Accurate. The right pointer iterates through the string s exactly once, performing n increments. The left pointer also iterates through the string at most once. Operations on the Set (add, has, delete) take O(1) time on average. Each character is added to the set and removed from the set at most once. Therefore, the total time complexity is linear, O(n).
  • Stated Space Complexity: O(n) where n is the length of s

    • Verification: Incorrect. The charSet stores characters within the current window. Since the problem states s consists of lowercase English letters, the maximum number of unique characters that can ever be stored in the charSet is 26 (the size of the English alphabet). This is a constant value, regardless of the input string's length n.
    • Correct Complexity: O(1) because the size of the character set is bounded by the alphabet size (26).

3. Key Insight

The key insight for this solution is to efficiently maintain a window of characters and check if all characters within that window are unique. This is achieved by:

  1. Sliding Window: Using two pointers, left and right, to define the current substring (window).
  2. Hash Set for Uniqueness: Employing a Set (or a frequency map/array) to keep track of the characters currently present within the window. The Set provides O(1) average time complexity for checking existence (has), adding (add), and removing (delete) characters.
  3. Dynamic Window Adjustment:
    • When the right pointer expands the window and encounters a character already present in the charSet, it means a repetition exists.
    • To resolve this, the left pointer must advance, removing characters from the left end of the window (and from the charSet) until the repeating character is no longer in the set.
    • Once the window size reaches k and all characters within it are unique (charSet.size === k), we count it as a valid substring.
    • After counting, the window is immediately "slid" forward by removing s[left] from the set and incrementing left to prepare for the next potential valid substring.

This dynamic adjustment allows for processing the string in a single pass, leading to optimal time complexity.

4. Edge Case Analysis

The current solution handles several edge cases correctly:

  • k > s.length: The solution correctly returns 0 if k is greater than the string length, as no substring of length k can be formed. (Example 2: s = "home", k = 5 -> Output: 0)
  • k = 1: If k is 1, every character is a valid substring of length 1 with no repeats. The logic handles this: charSet.size will always be 1 when a character is added, count will increment, and then the character is removed, and left advances. For s = "abc", k = 1, it would correctly return 3.
  • s contains all unique characters (e.g., s = "abcde", k = 3):
    • "abc" -> count = 1
    • "bcd" -> count = 2
    • "cde" -> count = 3
    • Correctly returns 3.
  • s contains all repeated characters (e.g., s = "aaaaa", k = 3):
    • right adds 'a'. charSet has {'a'}.
    • right tries to add next 'a'. charSet.has('a') is true.
    • while loop runs: charSet.delete('a'), left increments. charSet is empty.
    • charSet.add('a').
    • This continues. charSet.size will never reach k (which is 3) because any duplicate 'a' will cause the window to shrink, keeping charSet.size at 1. Correctly returns 0.
  • Minimum constraints: s.length = 1, k = 1. s = "a", k = 1.
    • right = 0: charSet.add('a'). charSet.size is 1. k is 1. count becomes 1. charSet.delete('a'), left becomes 1.
    • Loop ends. Returns 1. Correct.

The solution robustly handles these scenarios.

5. Learning Points

  • Similar Problems Using This Pattern:

  • Common Mistakes People Make with This Pattern:

    • Off-by-one errors: Incorrectly calculating window size or loop bounds (e.g., right - left + 1 vs right - left).
    • Incorrectly updating frequency map/set: Forgetting to remove characters from the left end when shrinking the window, or adding/removing them at the wrong time.
    • Not handling the k > n edge case: Leading to out-of-bounds errors or incorrect results.
    • Inefficient uniqueness check: Using nested loops to check for duplicates in each substring, which degrades time complexity. The Set is crucial for efficiency here.
    • Confusing "distinct characters" with "no repeated characters": "No repeated characters" means all characters in the window are unique. "At most K distinct characters" means the count of unique characters in the window is less than or equal to K, but characters can repeat as long as they are one of the K distinct types.
  • Variations of This Problem:

    • Longest K-Length Substring with No Repeated Characters: Find the longest such substring (though here, all valid substrings are of length K, so it would just be k if any exist).
    • Count Substrings with Exactly K Distinct Characters: More complex, often solved by countAtMostK(s, K) - countAtMostK(s, K-1).
    • Count Substrings with At Most K Distinct Characters: A classic sliding window problem where the charSet.size condition would change.
    • Allowing a certain number of repetitions: E.g., "Find K-length substrings where at most one character repeats." This would require a frequency map instead of just a set.

6. Code Quality

The code quality is good:

  • Variable Naming: s, k, n, left, right, charSet, count are all clear, descriptive, and follow common conventions for this pattern.
  • Code Structure: The function is well-structured, with an early exit for an invalid k, clear initialization, and a main loop that encapsulates the sliding window logic.
  • Readability: The logic is easy to follow. The while (charSet.has(s[right])) loop clearly indicates the window shrinking logic due to a duplicate. The if (charSet.size === k) condition clearly checks for a valid substring.
  • TypeScript Best Practices: The use of export for the function is good for modularity and testing.

Minor Suggestion for Readability (Optional):
You could add a comment explaining why charSet.delete(s[left]); left++; happens immediately after count++ for a valid window. This is the "slide" part of the fixed-size sliding window.

// ...
if (charSet.size === k) {
  count++;
  // After finding a valid k-length substring,
  // we must slide the window forward by one character.
  // Remove the leftmost character s[left] and advance left.
  charSet.delete(s[left]);
  left++;
}
// ...

This is a small detail, but it emphasizes the fixed-size sliding window behavior after a valid window is found.

7. Alternative Approaches

  1. Brute Force with Set Check:

    • Iterate through all possible starting positions i from 0 to n - k.
    • For each i, extract the substring s.substring(i, i + k).
    • Create a Set from this substring's characters.
    • If Set.size === k, increment the count.
    • Trade-offs:
      • Time Complexity: O(N * K) in the best case (if Set creation from string is O(K)) or O(N * K^2) if Set creation is considered O(K) and then checking Set.size is O(K). If Set operations are considered O(1) for fixed alphabet, it's O(N * K). This is significantly worse than O(N).
      • Space Complexity: O(K) for each temporary Set, though could be O(1) if alphabet limited.
      • Simplicity: Easier to understand initially, but much less efficient.
  2. Fixed-Size Sliding Window with Frequency Array (or Map):

    • Instead of a Set, use a frequency array (e.g., charCounts: number[] = new Array(26).fill(0)) to store counts of characters in the current window.
    • Maintain a distinctCount variable. When a character's count goes from 0 to 1, increment distinctCount. When it goes from 1 to 0, decrement distinctCount.
    • Expand the window: charCounts[s[right]]++. If charCounts[s[right]] === 1, distinctCount++.
    • Shrink the window (after right - left + 1 === k): If charCounts[s[left]] === 1, distinctCount--. charCounts[s[left]]--. left++.
    • If distinctCount === k, increment the total result count.
    • Trade-offs:
      • Time Complexity: O(N), same as the Set approach.
      • Space Complexity: O(1) (fixed size 26 array for lowercase English letters).
      • Subtle difference: This approach explicitly tracks counts, which might be slightly more intuitive for some and is necessary for variations like "at most K distinct characters" or "exactly K distinct characters" where you need to know how many distinct characters there are, not just if all are unique. The current Set solution implicitly uses charSet.size to track distinct characters. In this specific problem, both Set and frequency array are equally efficient and valid.

Your current solution using the Set is highly efficient and idiomatic for this type of problem.

@github-actions

github-actions Bot commented Feb 2, 2026

Copy link
Copy Markdown

✅ Test Results

Tests have been executed for this pull request.

📊 Coverage Summary

Metric Coverage
Statements 94.61%
Branches 89.26%
Functions 85.71%
Lines 94.68%

Check the workflow logs for detailed test output.

@github-actions

github-actions Bot commented Feb 2, 2026

Copy link
Copy Markdown

🤖 Gemini Code Review (Model: gemini-2.5-flash)

Here's a detailed review of the provided LeetCode solution for "Find K-Length Substrings With No Repeated Characters":


1. Pattern Identification

This solution effectively uses the Sliding Window algorithmic pattern. Specifically, it employs a variable-sized sliding window that shrinks from the left to maintain a property (no repeated characters) and then checks if the current window, satisfying that property, also meets a fixed-size requirement (k).

2. Complexity Verification

  • Time Complexity: O(n)

    • The stated time complexity O(n) is accurate.
    • The right pointer iterates through the string s once, performing n increments.
    • The left pointer also iterates through the string at most once (it only moves forward).
    • Operations on the Map (like set, get, delete) take O(1) on average.
    • Since each character is added to and removed from the map at most once, the total time complexity remains linear, O(n).
  • Space Complexity: O(1)

    • The stated space complexity O(n) is inaccurate.
    • The charCount Map stores the frequency of characters within the current window.
    • Given the constraint that s consists of lowercase English letters, there are only 26 possible unique characters.
    • Therefore, the charCount Map will store at most 26 entries at any given time, regardless of the input string's length n or the window size k.
    • This makes the space complexity effectively O(26), which simplifies to O(1) (constant space relative to the alphabet size).

3. Key Insight

The key insight for this solution is to efficiently manage the "no repeated characters" constraint while iterating through all possible k-length substrings.

  1. Sliding Window for Uniqueness: Use a sliding window ([left, right]) and a frequency map (charCount) to keep track of characters within the current window.
  2. Dynamic Window Adjustment: As the right pointer expands the window, if a character s[right] causes a duplicate (its count in charCount becomes greater than 1), the while loop immediately shrinks the window from the left until the duplicate is resolved and the window once again contains only unique characters. This ensures that at any point after the while loop finishes, the current window `[

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This pull request adds a new LeetCode medium problem solution: Find K-Length Substrings With No Repeated Characters (problem #1084). The PR reorganizes the problem files into the correct directory structure and updates the repository's problem count and indices.

Changes:

  • Added TypeScript solution with sliding window algorithm implementation
  • Created problem README with examples, constraints, and problem description
  • Updated root README to increment problem count from 172 to 173
  • Added problem to both String Manipulation and Sliding Window pattern sections

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

File Description
leetcode/medium/1084-find-k-length-substrings-with-no-repeated-characters/find-k-length-substrings-with-no-repeated-characters.ts Reformatted JSDoc comments, added export keyword, removed trailing whitespace, and changed to function declaration syntax
leetcode/medium/1084-find-k-length-substrings-with-no-repeated-characters/README.md Created problem README with description, examples, and constraints following repository conventions
README.md Incremented LeetCode problem count to 173, added problem to String Manipulation section and Sliding Window pattern section
1084-find-k-length-substrings-with-no-repeated-characters/README.md Removed old README from incorrect directory location
Comments suppressed due to low confidence (1)

leetcode/medium/1084-find-k-length-substrings-with-no-repeated-characters/find-k-length-substrings-with-no-repeated-characters.ts:3

  • The space complexity should be O(k) or O(min(k, 26)) rather than O(n). The Map window can hold at most k characters (when all characters in the window are distinct), and since the string consists of lowercase English letters, it's bounded by the alphabet size of 26. The current annotation of O(n) is incorrect.

@pertrai1 pertrai1 merged commit ec6c3f1 into main Feb 3, 2026
11 of 12 checks passed
@pertrai1 pertrai1 deleted the leetcode-222026 branch February 3, 2026 23:51
@github-actions

github-actions Bot commented Feb 3, 2026

Copy link
Copy Markdown

📅 Spaced Repetition Reviews Scheduled!

Great job solving #1084 - Find K Length Substrings With No Repeated Characters! 🎉

To help you retain this knowledge long-term, I've scheduled 5 review sessions using spaced repetition:

Review Interval Schedule Logic
1st Review 1 day after solving Scheduled now
2nd Review 3 days after 1st review Auto-scheduled when 1st completes
3rd Review 7 days after 2nd review Auto-scheduled when 2nd completes
4th Review 14 days after 3rd review Auto-scheduled when 3rd completes
5th Review 30 days after 4th review Auto-scheduled when 4th completes

What to expect:

  • Your 1st review is scheduled for tomorrow
  • Each subsequent review is scheduled automatically when you complete the previous one
  • This ensures proper spacing even if you complete a review a few days late
  • GitHub issues will be created automatically for each review
  • Each issue will link back to your solution

🧠 Why Spaced Repetition?

Research shows that reviewing material at increasing intervals dramatically improves retention. This adaptive scheduling ensures optimal spacing based on when you actually complete each review!

Check docs/reviews/review-schedule.json to see your review schedule.

github-actions Bot pushed a commit that referenced this pull request Feb 3, 2026
…h No Repeated Characters

  Problem: #1084 - Find K Length Substrings With No Repeated Characters
  PR: #223
  First review scheduled (subsequent reviews auto-scheduled on completion)

  [skip ci]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

code challenge this is a coding challenge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants