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. Array

Two Sum

PreviousOnline Stock SpanNextBest time to by and sell stock

Last updated 3 years ago

Was this helpful?

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        return self.twoSumOpti(nums, target)

    def twoSumBruteForce(self, nums: List[int], target: int) -> List[int]:
        """
        Iterate through all the numbers and check if there is a number which 
        is equal to the difference of (target - num)
        
        Time complexity: O(N^3)
            The main loop takes O(N) time. Then, on every iteration we check 
            if the difference is within the rest of the array. 
            And, if so, we get the index for that item.
        
        Space complexity: O(1)
            Any variable is stored and there aren't any recursive call.
        """
        
        for i, num in enumerate(nums):
            difference = target - num
            
            if difference in nums[i+1:]:
                complementary_index = nums[i+1:].index(difference) + i+1
                return [i, complementary_index]
    
    def twoSumBruteForceIterating(self, nums: List[int], target: int) -> List[int]:
        """
        Iterate through all the numbers and check if there is a number which 
        is equal to the difference of (target - num)
        
        Time complexity: O(N^2)
            The main loop takes O(N) time. Then, on every iteration we look 
            for the diff in the remaining array.
        
        Space complexity: O(1)
            Any variable is stored and there aren't any recursive call.
        """
        
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    return [i, j]
    
    def twoSumLookup(self, nums: List[int], target: int) -> List[int]:
        """
        Store all the indexes for every number until you find a complementary 
        already stored in the lookup.
        
        Time complexity: O(N)
            Iterating only once over the array.
        Space complexity: O(N)
            Worst case scenary, we store all the items of the array 
            in the hashmap.
        """
        
        lookup = {}
        
        for i, num in enumerate(nums):
            difference = target - num
            
            if difference in lookup:
                return [i, lookup[difference]]
            
            lookup[num] = i
        
        return []
https://leetcode.com/problems/two-sum/