< Summary

Information
Class: LeetCode.Algorithms.TakeKOfEachCharacterFromLeftAndRight.TakeKOfEachCharacterFromLeftAndRightSlidingWindow
Assembly: LeetCode
File(s): D:\a\LeetCode-CS\LeetCode-CS\source\LeetCode\Algorithms\TakeKOfEachCharacterFromLeftAndRight\TakeKOfEachCharacterFromLeftAndRightSlidingWindow.cs
Line coverage
100%
Covered lines: 24
Uncovered lines: 0
Coverable lines: 24
Total lines: 58
Line coverage: 100%
Branch coverage
100%
Covered branches: 14
Total branches: 14
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
TakeCharacters(...)100%1414100%

File(s)

D:\a\LeetCode-CS\LeetCode-CS\source\LeetCode\Algorithms\TakeKOfEachCharacterFromLeftAndRight\TakeKOfEachCharacterFromLeftAndRightSlidingWindow.cs

#LineLine coverage
 1// --------------------------------------------------------------------------------
 2// Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv).
 3// All Rights Reserved.
 4// --------------------------------------------------------------------------------
 5// This software is the confidential and proprietary information of Eugene Eremeev
 6// (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not
 7// disclose such Confidential Information and shall use it only in accordance with
 8// the terms of the license agreement you entered into with Eugene Eremeev (also
 9// known as Yevhenii Yeriemeieiv).
 10// --------------------------------------------------------------------------------
 11
 12namespace LeetCode.Algorithms.TakeKOfEachCharacterFromLeftAndRight;
 13
 14/// <inheritdoc />
 15public class TakeKOfEachCharacterFromLeftAndRightSlidingWindow : ITakeKOfEachCharacterFromLeftAndRight
 16{
 17    /// <summary>
 18    ///     Time complexity - O(n)
 19    ///     Space complexity - O(1)
 20    /// </summary>
 21    /// <param name="s"></param>
 22    /// <param name="k"></param>
 23    /// <returns></returns>
 24    public int TakeCharacters(string s, int k)
 225    {
 226        var count = new int[3];
 27
 3228        foreach (var c in s)
 1329        {
 1330            count[c - 'a']++;
 1331        }
 32
 733        if (count.Any(c => c < k))
 134        {
 135            return -1;
 36        }
 37
 138        var window = new int[3];
 139        var left = 0;
 140        var maxWindow = 0;
 41
 2642        for (var right = 0; right < s.Length; right++)
 1243        {
 1244            window[s[right] - 'a']++;
 45
 2446            while (left <= right && (count[0] - window[0] < k || count[1] - window[1] < k || count[2] - window[2] < k))
 1247            {
 1248                window[s[left] - 'a']--;
 49
 1250                left++;
 1251            }
 52
 1253            maxWindow = Math.Max(maxWindow, right - left + 1);
 1254        }
 55
 156        return s.Length - maxWindow;
 257    }
 58}