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
  • Brute force
  • Memoization
  • Tabulation

Was this helpful?

  1. Algorithms & data structures
  2. Dynamic Programming

Can Construct

Brute force

def can_construct_brute(
    target: str, 
    word_bank: list[str]
) -> bool:
    """
    N = len(work_bank)
    M = len(target)

    Time complexity: O(N^M * M)
        We are removing words for the target in every iteration. 
        In the worst scenario, we will remove then up to M times. 
        And, we have N branches to explore at every iteration.
        As well, in every iteration we copy and remove 
        some characters the target (depending on M).

    Space complexity: O(M*M) = O(M²)
        It will make up to M recursive calls. And for every call, 
        it will store the suffix 
        of the target.
    """

    if target == "":
        return True

    for word in word_bank:
        if word in target and target.index(word) == 0:
            diff = target.removeprefix(word)
            if can_construct(diff, word_bank):
                return True

    return False

Memoization

def can_construct_memo(
    target: str, 
    word_bank: list[str], 
    index: dict = None
) -> bool:
    """
    N = len(work_bank)
    M = len(target)

    Time complexity: O(N*M²)
        Worst case scenario, it will need to check every 
        combination of every value of N while decreasing M 
        (worst scenario will be by 1 character every time).
        As well, in every iteration we copy and remove some 
        characters the target (depending on M).

    Space complexity: O(M*M) = O(M²)
        It will make up to M recursive calls. And for every call, 
        it will store the suffix of the target.
    """

    if index is None:
        index = {}
    
    if target in index.keys():
        return index[target]

    if target == "":
        return True

    for word in word_bank:
        if word in target and target.index(word) == 0:
            diff = target.removeprefix(word)
            if can_construct_memo(diff, word_bank, index):
                index[target] = True
                return True

    index[target] = False
    return False

Tabulation

def can_construct_tab(target: str, word_bank: list[str]) -> bool:
    """
    Time complexity: O(M*N*M)
    Space complexity: O(M)
    """

    table = [False] * (len(target) + 1)
    table[0] = True

    for i in range(len(table)):
        if table[i] == True:
            for word in word_bank:
                substring = target[i:]
                if (
                    word in substring 
                    and substring.index(word) == 0
                ):
                    table[i + len(word)] = True

    return table[-1]
PreviousBest SumNextCount Construct

Last updated 3 years ago

Was this helpful?