The iron ML notebook
  • The iron data science notebook
  • ML & Data Science
    • Frequent Questions
      • Discriminative vs Generative models
      • Supervised vs Unsupervised learning
      • Batch vs Online Learning
      • Instance-based vs Model-based Learning
      • Bias-Variance Tradeoff
      • Probability vs Likelihood
      • Covariance vs Correlation Matrix
      • Precision vs Recall
      • How does a ROC curve work?
      • Ridge vs Lasso
      • Anomaly detection methods
      • How to deal with imbalanced datasets?
      • What is "Statistically Significant"?
      • Recommendation systems methods
    • Statistics
      • The basics
      • Distributions
      • Sampling
      • IQR
      • Z-score
      • F-statistic
      • Outliers
      • The bayesian basis
      • Statistic vs Parameter
      • Markov Monte Carlo Chain
    • ML Techniques
      • Pre-process
        • PCA
      • Loss functions
      • Regularization
      • Optimization
      • Metrics
        • Distance measures
      • Activation Functions
      • Selection functions
      • Feature Normalization
      • Cross-validation
      • Hyperparameter tuning
      • Ensemble methods
      • Hard negative mining
      • ML Serving
        • Quantization
        • Kernel Auto-Tuning
        • NVIDIA TensorRT vs ONNX Runtime
    • Machine Learning Algorithms
      • Supervised Learning
        • Support Vector Machines
        • Adaptative boosting
        • Gradient boosting
        • Regression algorithms
          • Linear Regression
          • Lasso regression
          • Multi Layer Perceptron
        • Classification algorithms
          • Perceptron
          • Logistic Regression
          • Multilayer Perceptron
          • kNN
          • Naive Bayes
          • Decision Trees
          • Random Forest
          • Gradient Boosted Trees
      • Unsupervised learning
        • Clustering
          • Clustering metrics
          • kMeans
          • Gaussian Mixture Model
          • Hierarchical clustering
          • DBSCAN
      • Cameras
        • Intrinsic and extrinsic parameters
    • Computer Vision
      • Object Detection
        • Two-Stage detectors
          • Traditional Detection Models
          • R-CNN
          • Fast R-CNN
          • Faster R-CNN
        • One-Stage detectors
          • YOLO
          • YOLO v2
          • YOLO v3
          • YOLOX
        • Techniques
          • NMS
          • ROI Pooling
        • Metrics
          • Objectness Score
          • Coco Metrics
          • IoU
      • MOT
        • SORT
        • Deep SORT
  • Related Topics
    • Intro
    • Python
      • Global Interpreter Lock (GIL)
      • Mutability
      • AsyncIO
    • SQL
    • Combinatorics
    • Data Engineering Questions
    • Distributed computation
      • About threads & processes
      • REST vs gRPC
  • Algorithms & data structures
    • Array
      • Online Stock Span
      • Two Sum
      • Best time to by and sell stock
      • Rank word combination
      • Largest subarray with zero sum
    • Binary
      • Sum of Two Integers
    • Tree
      • Maximum Depth of Binary Tree
      • Same Tree
      • Invert/Flip Binary Tree
      • Binary Tree Paths
      • Binary Tree Maximum Path Sum
    • Matrix
      • Set Matrix Zeroes
    • Linked List
      • Reverse Linked List
      • Detect Cycle
      • Merge Two Sorted Lists
      • Merge k Sorted Lists
    • String
      • Longest Substring Without Repeating Characters
      • Longest Repeating Character Replacement
      • Minimum Window Substring
    • Interval
    • Graph
    • Heap
    • Dynamic Programming
      • Fibonacci
      • Grid Traveler
      • Can Sum
      • How Sum
      • Best Sum
      • Can Construct
      • Count Construct
      • All Construct
      • Climbing Stairs
Powered by GitBook
On this page

Was this helpful?

  1. Algorithms & data structures
  2. String

Longest Repeating Character Replacement

PreviousLongest Substring Without Repeating CharactersNextMinimum Window Substring

Last updated 3 years ago

Was this helpful?

Solution in O(N)

class Solution:
    def characterReplacement(self, s: str, k: int) -> int:        
        index = defaultdict(int)
        start = 0
        end = 0
        
        res = 0
        cur_max = 0
        
        for end in range(len(s)):
            index[s[end]] += 1
            cur_max = max(cur_max, index[s[end]])
            
            while (end - start + 1) - cur_max > k:
                index[s[start]] -= 1
                start += 1
            
            res = max(res, end - start + 1)
                        
        return res

Solution for replacing multiple characters

class Solution:
    # O(N) time
    # O(1) space

    def characterReplacement(self, s: str, k: int) -> int:
        index = defaultdict(int)
        sub_str = ""
        max_sum = 0
        
        for char in s:
            
            if self.can_add_char(char, index, k):
                sub_str += char
                index[char] += 1
                max_sum = max(max_sum, len(sub_str))
            
            else:
                if char in sub_str:
                    new_start = sub_str.index(char)
                    sub_str = sub_str[new_start+1:]
                else:
                    sub_str = ""
                sub_str += char
                
                index = defaultdict(
                        int, 
                        {
                            val: sub_str.count(val) for val in set(sub_str)
                        }
                    )
        
        return max_sum
    
    
    def can_add_char(self, char: str, index: Dict, k: int) -> bool:
        
        if len(index) == 0:
            return True
        
        elif len(index) == 1:
            return char in index.keys() if k == 0 else True
        
        elif len(index) == 2 and char not in index.keys():
            return False
        
        else:
            min_key, min_val = min(index.items(), key=lambda val: val[1])
            return False if min_key == char and min_val == k else True
https://leetcode.com/problems/longest-repeating-character-replacement/