As Docker containers have become a staple in the development and deployment of machine learning applications, it's crucial to optimize Docker images to reduce their size and build time. This not only speeds up development cycles but also makes deployment more efficient. In this blog, we'll explore practical techniques to optimize Docker images using a Python PyTorch application as an example.


1. Choose Minimal Base Images

The base image you select can have a huge impact on your final Docker image size. For Python applications, especially when working with PyTorch, choosing a minimal base image can drastically reduce the size of your Docker image.

Example: Switching from python to python-slim or alpine

Before:

FROM python:3.9

This base image is comprehensive but can be quite large, often over 100 MB.

After:

FROM python:3.9-slim

The slim version of the Python image is much smaller, around 50 MB, but still contains enough tools to run your Python applications.

Impact:

Switching to a minimal base image like python:3.9-slim can reduce the base image size by half or more, leading to smaller Docker images and faster builds.

 


2. Use Multi-Stage Builds

Multi-stage builds are a powerful feature in Docker that allows you to build your application in one stage and then copy only the necessary parts to a final, smaller image. This helps to keep your Docker images lean and efficient by removing unnecessary files and dependencies.

Example: Building a PyTorch Application

Before:

FROM python:3.9-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .

CMD ["python", "train.py"]

In this example, all the dependencies and application files are installed and copied into the final image, which makes the image bigger.

After:

# First stage: Build the application
FROM python:3.9-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

# Second stage: Create the final image
FROM python:3.9-slim
WORKDIR /app
# Copy only the necessary files from the builder stage
COPY --from=builder /app /app

CMD ["python", "train.py"]

In this improved version, the builder stage installs all the dependencies and builds the application. The final image only includes the files needed to run the application, without all the extra tools and files used during the build process.

Impact:

Using multi-stage builds helps you create a much smaller Docker image by excluding unnecessary files and dependencies from the final image. This leads to faster downloads, quicker deployments, and more efficient storage use.


3. Minimize Layers in Dockerfile

Each command in a Dockerfile creates a new layer in the final image. Reducing the number of layers by combining commands can help decrease the image size.

Example: Combining Commands

Before:

FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN python setup.py install

After:

FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
COPY . .
RUN pip install --no-cache-dir -r requirements.txt && \
    python setup.py install

Here, the pip install and python setup.py install commands are combined into a single RUN instruction.

Impact:

By reducing the number of layers, the final image is smaller and more efficient, leading to quicker build times and less disk usage.


4. Leverage .dockerignore

A .dockerignore file can be used to exclude unnecessary files and directories from being copied into the Docker image, which reduces the size of the build context and the final image.

Example: Creating a .dockerignore File

Example .dockerignore:

__pycache__
*.pyc
.git
Dockerfile
README.md

Impact:

By excluding files like __pycache__, .git, and other unnecessary files, you can reduce the size of the build context, which speeds up the build process and results in a smaller Docker image.

5. Clean Up After Yourself

Temporary files and caches left over after installing dependencies can unnecessarily bloat your Docker image. Cleaning up these files can make a big difference in the final image size.

Example: Cleaning Up in a PyTorch Dockerfile

Before:

FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

After:

FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt && \
    rm -rf /root/.cache/pip

In this optimized Dockerfile, we clean up the pip cache after installing dependencies to reduce the image size.

Impact:

Removing unnecessary files and caches reduces the Docker image size, leading to faster builds, quicker downloads, and more efficient use of storage.


Conclusion

Optimizing Docker images by

  1. selecting minimal base images
  2. using multi-stage builds
  3. minimizing Dockerfile layers
  4. leveraging .dockerignore
  5. cleaning up after installations

These can significantly reduce image size and build times. These optimizations not only improve the efficiency of your Docker workflow but also lead to faster deployments, reduced storage costs, and a more streamlined development process.

1. Pulling the Image from Docker Registry

Start by pulling the image from your Amazon ECR registry with the tag v1.0.0.

Command:

docker pull 12345689.dkr.ecr.us-east-1.amazonaws.com/asr-docker:v1.0.0

 

2. Attaching to the Image

Create and start a container from the image and attach to it with an interactive terminal.

Command:

docker run -it 12345689.dkr.ecr.us-east-1.amazonaws.com/asr-docker:v1.0.0 /bin/bash

 

3. Making Changes Inside the Container

After attaching to the container, make any necessary changes. Once done, exit the terminal by typing:

Command:

apt update && apt upgrade -yq && \
    apt install -yq \
        gcc \
        wget \
        htop \
        python3-pip

exit

 

4. Committing Changes

After making changes inside the container, commit those changes to a new Docker image.

Command:

docker commit <container_id> 12345689.dkr.ecr.us-east-1.amazonaws.com/asr-docker:v1.0.1

 

5. Tagging the New Image

Since the new image is already correctly tagged in this example, this step can be considered complete with the previous commit command. However, if you needed to tag the image differently, you would use:

Command:

docker tag 12345689.dkr.ecr.us-east-1.amazonaws.com/asr-docker:v1.0.1 12345689.dkr.ecr.us-east-1.amazonaws.com/asr-docker:another-tag

 

6. Pushing to Registry

Push your newly tagged image to the Amazon ECR registry.

Command:

docker push 12345689.dkr.ecr.us-east-1.amazonaws.com/asr-docker:v1.0.1

 

7. Cleanup

Finally, clean up unused Docker resources to free up space.

Commands:

docker system prune
docker image prune

Math problems on platforms like LeetCode often require a combination of mathematical insight, algorithmic thinking, and coding skills. These problems can range from simple arithmetic operations to complex mathematical theories. Here, I will explain some common types of math problems and the techniques used to solve them.

Common Types of Math Problems and Techniques

  1. Random Pick with Weight
  2. Basic Calculator II
  3. Pow(x, n)
  4. K Closest Points to Origin
  5. Continuous Subarray Sum
  6. Random Pick Index
  7. Maximum Swap
  8. Add Strings

528. Random Pick with Weight

Problem: Given an array w of positive integers where w[i] describes the weight of index i, write a function pickIndex which randomly picks an index in proportion to its weight.

Approach:

  • Use prefix sums and binary search.
  • Compute the prefix sum array and use binary search to pick an index based on a random number.

Code:

import random
import bisect

class Solution:
    def __init__(self, w):
        self.prefix_sums = []
        prefix_sum = 0
        for weight in w:
            prefix_sum += weight
            self.prefix_sums.append(prefix_sum)
        self.total_sum = prefix_sum

    def pickIndex(self):
        target = random.randint(1, self.total_sum)
        return bisect.bisect_left(self.prefix_sums, target)

# Example usage:
weights = [1, 3, 2]
obj = Solution(weights)
print(obj.pickIndex())  # Randomly returns 0, 1, or 2 based on weights

Explanation:

  1. Prefix Sums: Compute the prefix sum of weights.
  2. Binary Search: Use binary search to find the index corresponding to a random target within the total weight range.

227. Basic Calculator II

Problem: Implement a basic calculator to evaluate a simple expression string containing non-negative integers, +, -, *, and / operators.

Approach:

  • Use a stack to manage the numbers and operators.
  • Traverse the string and handle operations based on operator precedence.

Code:

def calculate(s):
    if not s:
        return 0

    stack = []
    num = 0
    sign = '+'
    s += '+'

    for c in s:
        if c.isdigit():
            num = num * 10 + int(c)
        elif c in '+-*/':
            if sign == '+':
                stack.append(num)
            elif sign == '-':
                stack.append(-num)
            elif sign == '*':
                stack.append(stack.pop() * num)
            elif sign == '/':
                stack.append(int(stack.pop() / num))
            sign = c
            num = 0

    return sum(stack)

# Example usage:
expression = "3+2*2"
print(calculate(expression))  # Output: 7

Explanation:

  1. Stack for Numbers: Use a stack to handle numbers and intermediate results.
  2. Operator Precedence: Handle * and / immediately, defer + and - until the end.

50. Pow(x, n)

Problem: Implement pow(x, n), which calculates x raised to the power n.

Approach:

  • Use recursion and the concept of exponentiation by squaring.

Code:

def my_pow(x, n):
    def helper(x, n):
        if n == 0:
            return 1
        half = helper(x, n // 2)
        if n % 2 == 0:
            return half * half
        else:
            return half * half * x

    if n < 0:
        x = 1 / x
        n = -n
    return helper(x, n)

# Example usage:
x = 2.0
n = 10
print(my_pow(x, n))  # Output: 1024.0

Explanation:

  1. Recursion: Break down the problem into smaller subproblems using recursion.
  2. Exponentiation by Squaring: Efficiently compute powers by squaring intermediate results.

973. K Closest Points to Origin

Problem: Given an array of points where points[i] = [xi, yi] represents a point on the XY plane, return the k closest points to the origin (0, 0).

Approach:

  • Use a max-heap to keep track of the k closest points.

Code:

import heapq

def k_closest(points, k):
    max_heap = []
    for x, y in points:
        dist = -(x**2 + y**2)
        if len(max_heap) == k:
            heapq.heappushpop(max_heap, (dist, x, y))
        else:
            heapq.heappush(max_heap, (dist, x, y))
    return [(x, y) for (dist, x, y) in max_heap]

# Example usage:
points = [[1, 3], [-2, 2]]
k = 1
print(k_closest(points, k))  # Output: [[-2, 2]]

Explanation:

  1. Max-Heap: Use a max-heap to keep the closest k points by distance.
  2. Distance Calculation: Calculate the Euclidean distance and maintain the closest points.

523. Continuous Subarray Sum

Problem: Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k.

Approach:

  • Use a hash map to store the running sum modulo k.

Code:

def check_subarray_sum(nums, k):
    sum_map = {0: -1}
    running_sum = 0

    for i, num in enumerate(nums):
        running_sum += num
        if k != 0:
            running_sum %= k
        if running_sum in sum_map:
            if i - sum_map[running_sum] > 1:
                return True
        else:
            sum_map[running_sum] = i

    return False

# Example usage:
nums = [23, 2, 4, 6, 7]
k = 6
print(check_subarray_sum(nums, k))  # Output: True

Explanation:

  1. Running Sum: Calculate the running sum modulo k.
  2. Hash Map: Use a hash map to track the first occurrence of each remainder and check the distance between occurrences.

398. Random Pick Index

Problem: Given an integer array nums with possible duplicates, implement the Solution class:

  • pick(target): Randomly returns the index of the target number.

Approach:

  • Use reservoir sampling to handle random selection efficiently.

Code:

import random

class Solution:
    def __init__(self, nums):
        self.nums = nums

    def pick(self, target):
        count = 0
        result = -1
        for i, num in enumerate(self.nums):
            if num == target:
                count += 1
                if random.randint(1, count) == count:
                    result = i
        return result

# Example usage:
nums = [1, 2, 3, 3, 3]
target = 3
obj = Solution(nums)
print(obj.pick(target))  # Randomly returns one of the indices: 2, 3, or 4

Explanation:

  1. Reservoir Sampling: Ensure each index has an equal probability of being chosen.
  2. Count Occurrences: Traverse the array, counting occurrences of the target and selecting based on random chance.

670. Maximum Swap

Problem: Given a non-negative integer, you can swap two digits at most once to get the maximum valued number. Return the maximum valued number.

Approach:

  • Use a greedy algorithm to find the best swap.

Code:

def maximum_swap(num):
    digits = list(str(num))
    last = {int(x): i for i, x in enumerate(digits)}

    for i, x in enumerate(digits):
        for d in range(9, int(x), -1):
            if last.get(d, -1) > i:
                digits[i], digits[last[d]] = digits[last[d]], digits[i]
                return int(''.join(digits))

    return num

# Example usage:
num = 2736
print(maximum_swap(num))  # Output: 7236

Explanation:

  1. Greedy Approach: Find the highest digit that can be swapped to maximize the number.
  2. Track Last Occurrence: Use a dictionary to store the last occurrence of each digit for efficient swaps.

415. Add Strings

Problem: Given two non-negative integers represented as strings, return the sum of the two numbers as a string.

Approach:

  • Use digit-by-digit addition with carry handling.

Code:

def add_strings(num1, num2):
    i, j = len(num1) - 1, len(num2) - 1
    carry = 0
    result = []

    while i >= 0 or j >= 0 or carry:
        x = int(num1[i]) if i >= 0 else 0
        y = int(num2[j]) if j >= 0 else 0
        total = x + y + carry
        carry = total // 10
        result.append(total % 10)
        i -= 1
        j -= 1

    return ''.join(map(str, result[::-1]))

# Example usage:
num1 = "123"
num2 = "456"

Subset Techniques

Subset techniques involve generating and manipulating subsets of a given set. These techniques are widely used in combinatorial problems, where you need to explore all possible combinations of elements. Here, we will explore different methods to generate subsets and their applications.

Key Concepts

  1. Subset: A subset is any combination of elements from a set, including the empty set and the set itself.
  2. Power Set: The power set is the set of all possible subsets of a set, including the empty set and the set itself.

Methods to Generate Subsets

  1. Recursive Backtracking: A common method to generate all subsets by exploring all possibilities recursively.
  2. Iterative Approach: Using iterative techniques to build subsets, often leveraging bit manipulation.
  3. Library Functions: Using built-in functions or libraries in programming languages to generate subsets.

1. Recursive Backtracking

Recursive backtracking explores all possible subsets by including or excluding each element.

Code:

def subsets_backtracking(nums):
    def backtrack(start, path):
        result.append(path)
        for i in range(start, len(nums)):
            backtrack(i + 1, path + [nums[i]])

    result = []
    backtrack(0, [])
    return result

# Example usage:
nums = [1, 2, 3]
print(subsets_backtracking(nums))  # Output: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]

Explanation:

  1. Initialize: Start with an empty path and explore all possibilities.
  2. Include/Exclude: For each element, decide to include it in the current path or not.
  3. Recursive Call: Recursively call the function with the next starting index.
  4. Collect Results: Collect all paths (subsets) in the result list.

2. Iterative Approach

The iterative approach builds subsets by iterating over the existing subsets and adding the current element to each of them.

Code:

def subsets_iterative(nums):
    result = [[]]
    for num in nums:
        result += [curr + [num] for curr in result]
    return result

# Example usage:
nums = [1, 2, 3]
print(subsets_iterative(nums))  # Output: [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

Explanation:

  1. Initialize: Start with the empty subset.
  2. Iterate: For each element, add it to all existing subsets to form new subsets.
  3. Update Result: Append the new subsets to the result list.

3. Bit Manipulation

Using bit manipulation to generate subsets leverages the binary representation of numbers. Each bit can represent the inclusion or exclusion of an element.

Code:

def subsets_bit_manipulation(nums):
    n = len(nums)
    result = []
    for i in range(1 << n):
        subset = []
        for j in range(n):
            if i & (1 << j):
                subset.append(nums[j])
        result.append(subset)
    return result

# Example usage:
nums = [1, 2, 3]
print(subsets_bit_manipulation(nums))  # Output: [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

Explanation:

  1. Binary Representation: Iterate over the range (0) to (2^n - 1) (all possible binary numbers with (n) bits).
  2. Include/Exclude: Use each bit to decide whether to include the corresponding element.
  3. Form Subsets: Form subsets based on the binary representation and collect them in the result list.

Applications of Subset Techniques

  1. Combinatorial Problems: Problems that require exploring all possible combinations of elements, such as the knapsack problem, generating power sets, and finding all unique subsets.
  2. Optimization Problems: Problems that involve finding the best subset that meets certain criteria, such as maximizing profit or minimizing cost.
  3. String Manipulation: Problems involving substrings or subsequences where all possible combinations of characters need to be explored.
  4. Subset Sum Problem: Finding subsets that sum to a specific value, used in dynamic programming and algorithmic challenges.

Summary

  • Recursive Backtracking: Explores all subsets by including or excluding each element recursively. It is simple and easy to understand but can be less efficient for larger sets.
  • Iterative Approach: Builds subsets iteratively by adding each element to existing subsets. It is more efficient and avoids the overhead of recursion.
  • Bit Manipulation: Leverages binary representation to generate subsets. It is highly efficient and compact, suitable for problems with fixed-size sets.

Each method has its strengths and is suited to different types of problems. By understanding and applying these techniques, you can efficiently solve a wide range of combinatorial and optimization problems involving subsets.

Top K Elements Technique

The "Top K Elements" technique involves finding the largest (or smallest) ( k ) elements from a dataset. This is a common problem in computer science with applications in data analysis, search engines, recommendation systems, and more.

Key Concepts

  1. Priority Queue (Min-Heap or Max-Heap): A heap data structure that allows efficient extraction of the minimum or maximum element.
  2. Quickselect Algorithm: A selection algorithm to find the ( k )th largest (or smallest) element in an unordered list.
  3. Sorting: Sorting the entire dataset and then selecting the top ( k ) elements.
  4. Bucket Sort or Counting Sort: Special techniques for integer data with a limited range.

Methods to Find Top K Elements

  1. Heap (Priority Queue) Method: Efficient for dynamic data and large datasets.
  2. Quickselect Algorithm: Efficient for static data with good average-case performance.
  3. Sorting: Simple but less efficient for large datasets.
  4. Bucket Sort or Counting Sort: Efficient for specific types of data.

1. Heap (Priority Queue) Method

Using a min-heap (for the largest ( k ) elements) or max-heap (for the smallest ( k ) elements) to maintain the top ( k ) elements.

Code:

import heapq

def top_k_elements(nums, k):
    # Use a min-heap for the largest k elements
    if k == 0:
        return []

    min_heap = nums[:k]
    heapq.heapify(min_heap)

    for num in nums[k:]:
        if num > min_heap[0]:
            heapq.heappushpop(min_heap, num)

    return min_heap

# Example usage:
nums = [3, 2, 1, 5, 6, 4]
k = 2
print(top_k_elements(nums, k))  # Output: [5, 6]

Explanation:

  1. Initialize: Create a min-heap with the first ( k ) elements.
  2. Process: For each remaining element, if it is larger than the smallest element in the heap, replace the smallest element.
  3. Result: The heap contains the top ( k ) largest elements.

2. Quickselect Algorithm

Quickselect is a selection algorithm to find the ( k )th largest (or smallest) element in an unordered list, which can then be used to find the top ( k ) elements.

Code:

import random

def quickselect(nums, k):
    def partition(left, right, pivot_index):
        pivot_value = nums[pivot_index]
        nums[pivot_index], nums[right] = nums[right], nums[pivot_index]
        store_index = left
        for i in range(left, right):
            if nums[i] < pivot_value:
                nums[store_index], nums[i] = nums[i], nums[store_index]
                store_index += 1
        nums[right], nums[store_index] = nums[store_index], nums[right]
        return store_index

    def select(left, right, k_smallest):
        if left == right:
            return nums[left]
        pivot_index = random.randint(left, right)
        pivot_index = partition(left, right, pivot_index)
        if k_smallest == pivot_index:
            return nums[k_smallest]
        elif k_smallest < pivot_index:
            return select(left, pivot_index - 1, k_smallest)
        else:
            return select(pivot_index + 1, right, k_smallest)

    n = len(nums)
    return select(0, n - 1, n - k)

# Example usage:
nums = [3, 2, 1, 5, 6, 4]
k = 2
print(quickselect(nums, k))  # Output: 5

Explanation:

  1. Partition: Use the partitioning step from the QuickSort algorithm to position the pivot element correctly.
  2. Select: Recursively select the ( k )th smallest element, which corresponds to the ( (n - k) )th largest element.
  3. Result: The algorithm returns the ( k )th largest element, and the elements larger than it can be found in the list.

3. Sorting

Sorting the array and selecting the top ( k ) elements.

Code:

def top_k_elements_sort(nums, k):
    nums.sort(reverse=True)
    return nums[:k]

# Example usage:
nums = [3, 2, 1, 5, 6, 4]
k = 2
print(top_k_elements_sort(nums, k))  # Output: [6, 5]

Explanation:

  1. Sort: Sort the array in descending order.
  2. Select: Take the first ( k ) elements from the sorted array.
  3. Result: These are the top ( k ) largest elements.

4. Bucket Sort or Counting Sort

For integer data with a limited range, bucket sort or counting sort can be efficient.

Code (Counting Sort for a limited range):

def top_k_elements_counting_sort(nums, k):
    max_val = max(nums)
    count = [0] * (max_val + 1)

    for num in nums:
        count[num] += 1

    result = []
    for num in range(max_val, -1, -1):
        while count[num] > 0 and len(result) < k:
            result.append(num)
            count[num] -= 1

    return result

# Example usage:
nums = [3, 2, 1, 5, 6, 4]
k = 2
print(top_k_elements_counting_sort(nums, k))  # Output: [6, 5]

Explanation:

  1. Count Frequency: Count the frequency of each element.
  2. Select: Traverse the count array from the highest value, selecting elements until ( k ) elements are selected.
  3. Result: These are the top ( k ) largest elements.

If you want to find the largest K numbers and the smallest K numbers in an array simultaneously, you can use a combination of Min-Heap and Max-Heap. Here's a step-by-step approach in English:

Approach:

  1. Initialization:
    • Create a Min-Heap to keep track of the largest K elements.
    • Create a Max-Heap to keep track of the smallest K elements. (Since Python's heapq module only provides a Min-Heap, you can simulate a Max-Heap by pushing negative values.)
  2. Iterate through the array:
    • For each element in the array:
      • Add it to the Min-Heap if it's larger than the smallest element in the heap (the root). If the Min-Heap exceeds size K, remove the smallest element.
      • Add it to the Max-Heap (with a negative sign) if it's smaller than the largest element (the root). If the Max-Heap exceeds size K, remove the largest element.
  3. Results:
    • After processing all elements, the Min-Heap contains the largest K elements, and the Max-Heap (with the negative signs removed) contains the smallest K elements.

This method ensures that you maintain both the largest and smallest K elements as you process the array, and the time complexity remains efficient.

Code:

import heapq

def find_largest_and_lowest_k_numbers(nums, k):
    # Min-Heap for largest K numbers
    min_heap = nums[:k]
    heapq.heapify(min_heap)

    # Max-Heap for smallest K numbers (using negative values)
    max_heap = [-num for num in nums[:k]]
    heapq.heapify(max_heap)

    # Process the remaining elements in the array
    for num in nums[k:]:
        # Maintain the largest K numbers
        if num > min_heap[0]:
            heapq.heapreplace(min_heap, num)

        # Maintain the smallest K numbers
        if -num > max_heap[0]:
            heapq.heapreplace(max_heap, -num)

    # Convert the Max-Heap back to positive numbers
    lowest_k = [-x for x in max_heap]

    return min_heap, lowest_k

# Example usage
nums = [3, 2, 1, 5, 6, 4, 8, 7]
k = 3
largest_k, lowest_k = find_largest_and_lowest_k_numbers(nums, k)
print("Largest K:", largest_k)  # Output: [6, 7, 8]
print("Lowest K:", lowest_k)    # Output: [1, 2, 3]

215. Kth Largest Element in an Array

Problem: Given an integer array nums and an integer k, return the kth largest element in the array.

Approach:

  • Min-Heap: Use a min-heap to keep track of the largest k elements in the array. The top element of the heap will be the kth largest element.
  • Quickselect: Another approach is to use the Quickselect algorithm, which is based on the partition method used in QuickSort. This method is efficient with an average time complexity of (O(n)).

Min-Heap Code:

import heapq

def find_kth_largest(nums, k):
    heap = nums[:k]
    heapq.heapify(heap)
    for num in nums[k:]:
        if num > heap[0]:
            heapq.heappushpop(heap, num)
    return heap[0]

# Example usage:
nums = [3, 2, 1, 5, 6, 4]
k = 2
print(find_kth_largest(nums, k))  # Output: 5

Quickselect Code:

def find_kth_largest(nums, k):
    k = len(nums) - k

    def quickselect(l, r):
        pivot, p = nums[r], l
        for i in range(l, r):
            if nums[i] <= pivot:
                nums[p], nums[i] = nums[i], nums[p]
                p += 1
        nums[p], nums[r] = nums[r], nums[p]
        if p > k:
            return quickselect(l, p - 1)
        elif p < k:
            return quickselect(p + 1, r)
        else:
            return nums[p]

    return quickselect(0, len(nums) - 1)

# Example usage:
nums = [3, 2, 1, 5, 6, 4]
k = 2
print(find_kth_largest(nums, k))  # Output: 5


23. Merge k Sorted Lists

Problem: You are given an array of k linked-lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.

Approach:

  • Min-Heap: Use a min-heap to efficiently merge the k sorted linked lists. Each time, extract the smallest element from the heap and add it to the merged list.

Code:

import heapq

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

    def __lt__(self, other):
        return self.val < other.val

def merge_k_lists(lists):
    min_heap = []
    for root in lists:
        if root:
            heapq.heappush(min_heap, root)

    dummy = ListNode()
    curr = dummy

    while min_heap:
        smallest_node = heapq.heappop(min_heap)
        curr.next = smallest_node
        curr = curr.next
        if smallest_node.next:
            heapq.heappush(min_heap, smallest_node.next)

    return dummy.next

# Example usage:
# Assuming ListNode class is defined and linked lists are created.
lists = [list1, list2, list3]  # Example linked-lists
result = merge_k_lists(lists)

Explanation:

  1. Min-Heap: Each list's head is added to the heap. The heap helps efficiently find and add the smallest element across all lists to the final merged list.


703. Kth Largest Element in a Stream

Problem: Design a class to find the kth largest element in a stream. Implement the KthLargest class:

  • KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums.
  • int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.

Approach:

  • Min-Heap: Maintain a min-heap of size k. The smallest element in the heap is the kth largest element in the stream.

Code:

import heapq

class KthLargest:
    def __init__(self, k, nums):
        self.k = k
        self.min_heap = nums
        heapq.heapify(self.min_heap)
        while len(self.min_heap) > k:
            heapq.heappop(self.min_heap)

    def add(self, val):
        heapq.heappush(self.min_heap, val)
        if len(self.min_heap) > self.k:
            heapq.heappop(self.min_heap)
        return self.min_heap[0]

# Example usage:
k = 3
nums = [4, 5, 8, 2]
kthLargest = KthLargest(k, nums)
print(kthLargest.add(3))  # Output: 4
print(kthLargest.add(5))  # Output: 5
print(kthLargest.add(10))  # Output: 5
print(kthLargest.add(9))  # Output: 8
print(kthLargest.add(4))  # Output: 8

Summary

  • Heap (Priority Queue) Method:
    • Pros: Efficient for dynamic data and large datasets.
    • Cons: Slightly complex to implement.
  • Quickselect Algorithm:
    • Pros: Good average-case performance, efficient for static data.
    • Cons: Worst-case performance can be poor.
  • Sorting:
    • Pros: Simple to implement.
    • Cons: Less efficient for large datasets ((O(n \log n))).
  • Bucket Sort or Counting Sort:
    • Pros: Very efficient for integer data with a limited range.
    • Cons: Not general-purpose, requires specific data characteristics.

Choosing the right method depends on the characteristics of the dataset and the specific requirements of the problem at hand.

'ML Engineering > python' 카테고리의 다른 글

08. Math  (0) 2024.08.07
07. Subset Techniques  (0) 2024.08.06
05. Modified Binary Search Technique  (0) 2024.08.06
04. Binary Tree BFS Techniques  (0) 2024.08.06
03. Binary Tree DFS Techniques  (0) 2024.08.06

Modified Binary Search Technique

Modified Binary Search techniques are variations of the traditional binary search algorithm that are adapted to solve specific problems or work on specialized data structures. The traditional binary search algorithm is used to find the position of a target value within a sorted array in (O(\log n)) time. Modified versions extend this principle to handle more complex scenarios.

Key Concepts

  1. Binary Search: A divide-and-conquer algorithm that repeatedly divides the search interval in half.
  2. Modification: Adjusting the standard binary search to handle variations in data or specific problem requirements.

Applications

  1. Finding the First or Last Occurrence of an Element.
  2. Searching in a Rotated Sorted Array.
  3. Finding the Peak Element in an Array.
  4. Finding the Square Root of a Number.
  5. Searching in a Nearly Sorted Array.

1. Finding the First or Last Occurrence of an Element

Problem: Given a sorted array with duplicate elements, find the first or last occurrence of a target value.

Code:

def find_first_occurrence(arr, target):
    left, right = 0, len(arr) - 1
    result = -1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            result = mid
            right = mid - 1  # continue to search on the left side
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return result

def find_last_occurrence(arr, target):
    left, right = 0, len(arr) - 1
    result = -1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            result = mid
            left = mid + 1  # continue to search on the right side
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return result

# Example usage:
arr = [1, 2, 2, 2, 3, 4, 5]
target = 2
print(find_first_occurrence(arr, target))  # Output: 1
print(find_last_occurrence(arr, target))   # Output: 3

Explanation:

  1. Initialization: Start with the left and right pointers at the ends of the array.
  2. Midpoint Calculation: Calculate the midpoint of the current search interval.
  3. Adjust Search Range: If the target is found, update the result and adjust the search range to continue looking for the first or last occurrence.
  4. Result: Return the index of the first or last occurrence.

2. Searching in a Rotated Sorted Array

Problem: Given a rotated sorted array, find the index of a target value.

Code:

def search_rotated_sorted_array(nums, target):
    left, right = 0, len(nums) - 1
    while left <= right:
        mid = (left + right) // 2
        if nums[mid] == target:
            return mid
        if nums[left] <= nums[mid]:  # left half is sorted
            if nums[left] <= target < nums[mid]:
                right = mid - 1
            else:
                left = mid + 1
        else:  # right half is sorted
            if nums[mid] < target <= nums[right]:
                left = mid + 1
            else:
                right = mid - 1
    return -1

# Example usage:
nums = [4, 5, 6, 7, 0, 1, 2]
target = 0
print(search_rotated_sorted_array(nums, target))  # Output: 4

Explanation:

  1. Initialization: Start with the left and right pointers at the ends of the array.
  2. Midpoint Calculation: Calculate the midpoint of the current search interval.
  3. Determine Sorted Half: Check which half of the array is sorted.
  4. Adjust Search Range: Narrow down the search range to the half that might contain the target.
  5. Result: Return the index of the target if found, otherwise return -1.

3. Finding the Peak Element in an Array

Problem: Given an array, find the index of a peak element. A peak element is greater than its neighbors.

Code:

def find_peak_element(nums):
    left, right = 0, len(nums) - 1
    while left < right:
        mid = (left + right) // 2
        if nums[mid] > nums[mid + 1]:
            right = mid
        else:
            left = mid + 1
    return left

# Example usage:
nums = [1, 2, 3, 1]
print(find_peak_element(nums))  # Output: 2 (index of peak element 3)

Explanation:

  1. Initialization: Start with the left and right pointers at the ends of the array.
  2. Midpoint Calculation: Calculate the midpoint of the current search interval.
  3. Compare Midpoint with Neighbor: Compare the midpoint with its right neighbor to determine the direction of the peak.
  4. Adjust Search Range: Move the search range towards the peak.
  5. Result: Return the index of the peak element.

4. Finding the Square Root of a Number

Problem: Find the integer square root of a non-negative integer ( x ).

Code:

def my_sqrt(x):
    if x < 2:
        return x
    left, right = 2, x // 2
    while left <= right:
        mid = (left + right) // 2
        num = mid * mid
        if num == x:
            return mid
        elif num < x:
            left = mid + 1
        else:
            right = mid - 1
    return right

# Example usage:
x = 8
print(my_sqrt(x))  # Output: 2

Explanation:

  1. Initialization: Start with the left pointer at 2 and the right pointer at ( x // 2 ).
  2. Midpoint Calculation: Calculate the midpoint of the current search interval.
  3. Square Comparison: Compare the square of the midpoint with ( x ).
  4. Adjust Search Range: Narrow down the search range based on the comparison.
  5. Result: Return the integer part of the square root.

5. Searching in a Nearly Sorted Array

Problem: Given a nearly sorted array (where each element may be misplaced by at most one position), find the index of a target value.

Code:

def search_nearly_sorted_array(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        if mid - 1 >= left and arr[mid - 1] == target:
            return mid - 1
        if mid + 1 <= right and arr[mid + 1] == target:
            return mid + 1
        if arr[mid] < target:
            left = mid + 2
        else:
            right = mid - 2
    return -1

# Example usage:
arr = [10, 3, 40, 20, 50, 80, 70]
target = 40
print(search_nearly_sorted_array(arr, target))  # Output: 2

Explanation:

  1. Initialization: Start with the left and right pointers at the ends of the array.
  2. Midpoint Calculation: Calculate the midpoint of the current search interval.
  3. Check Neighboring Elements: Check the midpoint and its immediate neighbors.
  4. Adjust Search Range: Narrow down the search range based on the comparison.
  5. Result: Return the index of the target if found, otherwise return -1.

1. 1004. Max Consecutive Ones III

This problem is typically solved using the sliding window technique, not binary search. However, if you wanted to use binary search to determine the maximum window size, you could explore different window sizes and use a helper function to check the validity, but this would be less efficient than the sliding window method.

Problem:

Given a binary array nums and an integer k, find the maximum number of consecutive 1s in the array if you can flip at most k 0s.

Code:
This problem doesn't naturally lend itself to a binary search solution in the traditional sense. Instead, the optimal approach is the sliding window method:

def longestOnes(nums: List[int], k: int) -> int:
    left = 0
    max_length = 0
    zeros_count = 0

    for right in range(len(nums)):
        if nums[right] == 0:
            zeros_count += 1

        while zeros_count > k:
            if nums[left] == 0:
                zeros_count -= 1
            left += 1

        max_length = max(max_length, right - left + 1)

    return max_length

Explanation:

  • We expand the window size until we exceed the number of 0s that can be flipped, and then we start shrinking the window from the left side.
  • This problem is best solved using the sliding window technique, and binary search is not a natural fit here.

33. Search in Rotated Sorted Array

Problem:
Given a rotated sorted array and a target value, find the index of the target. If not found, return -1.

Code:

def search(nums: List[int], target: int) -> int:
    left, right = 0, len(nums) - 1

    while left <= right:
        mid = (left + right) // 2

        if nums[mid] == target:
            return mid

        if nums[left] <= nums[mid]:  # Left half is sorted
            if nums[left] <= target < nums[mid]:
                right = mid - 1
            else:
                left = mid + 1
        else:  # Right half is sorted
            if nums[mid] < target <= nums[right]:
                left = mid + 1
            else:
                right = mid - 1

    return -1

Explanation:

  • We use binary search to identify which half of the array is sorted.
  • Depending on whether the target lies within the sorted half, we adjust our search range.

34. Find First and Last Position of Element in Sorted Array

Problem:
Given a sorted array of integers nums and a target value, find the starting and ending position of the target.

Code:

def searchRange(nums: List[int], target: int) -> List[int]:
    def findLeft():
        left, right = 0, len(nums) - 1
        while left <= right:
            mid = (left + right) // 2
            if nums[mid] < target:
                left = mid + 1
            else:
                right = mid - 1
        return left

    def findRight():
        left, right = 0, len(nums) - 1
        while left <= right:
            mid = (left + right) // 2
            if nums[mid] <= target:
                left = mid + 1
            else:
                right = mid - 1
        return right

    left_index = findLeft()
    right_index = findRight()

    if left_index <= right_index:
        return [left_index, right_index]
    return [-1, -1]

Explanation:

  • Two binary searches are conducted: one for the first occurrence of the target (findLeft), and one for the last occurrence (findRight).
  • This ensures both the start and end positions of the target are found efficiently.

69. Sqrt(x)

Problem:
Given a non-negative integer x, compute and return the square root of x. Since the return type is an integer, only the integer part of the result is returned.

Code:

def mySqrt(x: int) -> int:
    left, right = 0, x

    while left <= right:
        mid = (left + right) // 2
        if mid * mid == x:
            return mid
        elif mid * mid < x:
            left = mid + 1
        else:
            right = mid - 1

    return right

Explanation:

  • The binary search finds the integer square root by narrowing down the possible values.
  • If mid * mid is too small, the left boundary is adjusted; if too large, the right boundary is adjusted.

162. Find Peak Element

Problem:
A peak element is an element that is greater than its neighbors. Given an array of integers, find a peak element and return its index.

Code:

def findPeakElement(nums: List[int]) -> int:
    left, right = 0, len(nums) - 1

    while left < right:
        mid = (left + right) // 2

        if nums[mid] > nums[mid + 1]:
            right = mid
        else:
            left = mid + 1

    return left

Explanation:

  • Binary search is used to find the peak by comparing the middle element with its neighbors.
  • If the middle element is larger than the next, the peak is to the left; otherwise, it's to the right.

825. Friends Of Appropriate Ages

Problem:
Given an array representing the ages of a group of people, determine the number of friend requests made according to specific rules.

Code:
This problem does not naturally lend itself to binary search as the primary technique. Instead, a combination of sorting and two-pointer technique (which is sometimes referred to as a variation of binary search) is used to solve it efficiently.

def numFriendRequests(ages: List[int]) -> int:
    ages.sort()
    requests = 0

    for i in range(len(ages)):
        if ages[i] <= 14:
            continue

        left = bisect.bisect_left(ages, 0.5 * ages[i] + 7 + 1)
        right = bisect.bisect_right(ages, ages[i])

        requests += right - left - 1

    return requests

Explanation:

  • The ages are sorted, and for each person, valid friend requests are counted by using binary search (bisect_left and bisect_right) to find the valid age range.
  • This ensures that the number of friend requests is calculated efficiently.

Binary search is an essential technique for several of these problems, particularly when dealing with sorted arrays or when trying to minimize/maximize a certain condition within a range of values.

Summary

Modified binary search techniques adapt the basic binary search algorithm to solve a variety of problems more efficiently. By leveraging the divide-and-conquer strategy, these techniques can handle different data structures and problem constraints. Understanding and implementing these variations can significantly improve the performance of your algorithms for specific use cases.

'ML Engineering > python' 카테고리의 다른 글

07. Subset Techniques  (0) 2024.08.06
06. Top K Elements Technique  (0) 2024.08.06
04. Binary Tree BFS Techniques  (0) 2024.08.06
03. Binary Tree DFS Techniques  (0) 2024.08.06
02. Sliding Window Technique  (0) 2024.08.06

Binary Tree BFS Techniques

Breadth-First Search (BFS) is a fundamental algorithm used to traverse or search tree or graph data structures. In the context of binary trees, BFS is often referred to as level-order traversal because it visits all nodes at each level of the tree before moving to the next level.

Key Concepts

  1. Queue: BFS uses a queue to keep track of nodes at the current level before moving to the next level.
  2. Level by Level Traversal: Nodes are processed level by level, starting from the root.
  3. First In, First Out (FIFO): Nodes are added to the queue in the order they are encountered and processed in the same order.

Steps

  1. Initialize: Start with a queue containing the root node.
  2. Process: Dequeue a node, process it, and enqueue its children.
  3. Repeat: Continue until the queue is empty, indicating that all nodes have been processed.

Applications

  1. Level Order Traversal: Printing or collecting nodes level by level.
  2. Finding the Depth/Height: Calculating the maximum depth or height of the tree.
  3. Shortest Path in Unweighted Trees: Finding the shortest path in terms of number of edges from the root to any node.
  4. Checking Completeness: Determining if a binary tree is complete.

Example: Level Order Traversal

Problem: Traverse the binary tree level by level and print each level.

Code:

from collections import deque

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def level_order_traversal(root):
    if not root:
        return []

    result = []
    queue = deque([root])

    while queue:
        level_size = len(queue)
        level = []

        for _ in range(level_size):
            node = queue.popleft()
            level.append(node.val)

            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)

        result.append(level)

    return result

# Example usage:
# Constructing the binary tree
#       3
#      / \
#     9   20
#        /  \
#       15   7
tree = TreeNode(3)
tree.left = TreeNode(9)
tree.right = TreeNode(20, TreeNode(15), TreeNode(7))

print(level_order_traversal(tree))  # Output: [[3], [9, 20], [15, 7]]

Explanation:

  1. Initialize: A queue is initialized with the root node.
  2. Process: Nodes are dequeued one by one. Their values are collected, and their children are enqueued.
  3. Level by Level: The process repeats until the queue is empty, resulting in a list of lists where each sublist contains nodes at the same level.

Example: Finding Maximum Depth

Problem: Calculate the maximum depth (height) of a binary tree.

Code:

from collections import deque

def max_depth_bfs(root):
    if not root:
        return 0

    queue = deque([root])
    depth = 0

    while queue:
        depth += 1
        level_size = len(queue)

        for _ in range(level_size):
            node = queue.popleft()

            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)

    return depth

# Example usage:
print(max_depth_bfs(tree))  # Output: 3

Explanation:

  1. Initialize: A queue is initialized with the root node and depth is set to 0.
  2. Process: Nodes are dequeued level by level, and the depth counter is incremented after processing each level.
  3. Depth Calculation: The process repeats until the queue is empty, resulting in the maximum depth of the tree.

Summary of BFS Techniques in Binary Trees

  • Level Order Traversal: Collecting or printing nodes level by level using a queue.
  • Finding Maximum Depth: Using BFS to determine the maximum depth by processing nodes level by level.
  • Shortest Path in Unweighted Trees: BFS naturally finds the shortest path in terms of edges from the root to any node.
  • Checking Completeness: Ensuring that all levels of the tree are fully filled except possibly the last level, which should be filled from left to right.

Advantages of BFS

  • Simple and Intuitive: Easy to understand and implement using a queue.
  • Level by Level Processing: Ideal for problems that require processing nodes level by level.
  • Shortest Path: Naturally finds the shortest path in unweighted trees or graphs.

When to Use BFS

  • When you need to process nodes level by level.
  • When finding the shortest path in an unweighted graph or tree.
  • When calculating metrics that depend on levels, such as the maximum depth or checking the completeness of a tree.

1. 200. Number of Islands

Problem:

Given a 2D grid of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.

Approach (BFS):

  • Use Breadth-First Search (BFS) to explore each island. Start BFS whenever you encounter '1', mark all connected '1's as visited (by changing them to '0'), and increment the island count.

Python Code:

Certainly! Here is the code with comments explaining each step.

1. 200. Number of Islands

from collections import deque

def numIslands(grid: List[List[str]]) -> int:
    if not grid:
        return 0

    rows, cols = len(grid), len(grid[0])
    island_count = 0

    # BFS function to traverse the island
    def bfs(r, c):
        queue = deque([(r, c)])
        while queue:
            row, col = queue.popleft()
            # Check boundaries and if the current cell is part of an island
            if 0 <= row < rows and 0 <= col < cols and grid[row][col] == '1':
                grid[row][col] = '0'  # Mark as visited by setting to '0'
                # Add all neighboring cells (up, down, left, right) to the queue
                queue.extend([(row-1, col), (row+1, col), (row, col-1), (row, col+1)])

    # Iterate over each cell in the grid
    for r in range(rows):
        for c in range(cols):
            # If the cell is a '1', start BFS to mark the entire island
            if grid[r][c] == '1':
                bfs(r, c)
                island_count += 1  # Increase island count for each BFS

    return island_count  # Return the total number of islands found

Example:

grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
print(numIslands(grid))  # Output: 1

Explanation:

  • We start BFS whenever we find an unvisited '1' and mark all connected lands as visited by changing them to '0'.
  • The BFS continues until all parts of the island are explored.
  • This continues for each island found, resulting in the total count.

2. 339. Nested List Weight Sum

Problem:

Given a nested list of integers, return the sum of all integers in the list weighted by their depth. For example, [1,[4,[6]]] would return 1*1 + 4*2 + 6*3 = 27.

Approach (BFS):

  • Use a Breadth-First Search (BFS) approach to traverse the nested list and calculate the weighted sum by tracking the depth level of each element.

Python Code:

from collections import deque

def depthSum(nestedList: List[NestedInteger]) -> int:
    queue = deque([(nestedList, 1)])  # Queue stores (list, depth) pairs
    total_sum = 0

    # BFS loop to process each element in the queue
    while queue:
        current_list, depth = queue.popleft()
        for element in current_list:
            if element.isInteger():
                # If it's an integer, add to the total sum weighted by depth
                total_sum += element.getInteger() * depth
            else:
                # If it's a list, add it to the queue with increased depth
                queue.append((element.getList(), depth + 1))

    return total_sum  # Return the weighted sum of all integers

Example:

nestedList = [NestedInteger(1), NestedInteger([NestedInteger(4), NestedInteger([NestedInteger(6)])])]
print(depthSum(nestedList))  # Output: 27

Explanation:

  • The BFS traverses the nested list level by level.
  • Each integer’s contribution to the sum is calculated based on its depth, which is tracked as we traverse each level.

3. 827. Making A Large Island

Problem:

You are given an n x n binary grid. You can change exactly one 0 to 1. Find the largest island size you can create by making this change.

Approach (BFS):

  • First, identify all islands using BFS, and assign unique island identifiers.
  • Then, for each 0 in the grid, check its neighboring islands and calculate the possible new island size by merging these islands.
  • Track the maximum possible island size.

Python Code:

from collections import deque, defaultdict

def largestIsland(grid: List[List[int]]) -> int:
    n = len(grid)
    island_size = defaultdict(int)  # Dictionary to store island sizes
    island_id = 2  # Start with an island id of 2 to distinguish from 1 and 0

    # BFS function to determine the size of each island
    def bfs(r, c, island_id):
        queue = deque([(r, c)])
        size = 0
        while queue:
            row, col = queue.popleft()
            if 0 <= row < n and 0 <= col < n and grid[row][col] == 1:
                grid[row][col] = island_id  # Mark as part of the current island
                size += 1  # Increment the size of the island
                # Add neighboring cells to the queue
                queue.extend([(row-1, col), (row+1, col), (row, col-1), (row, col+1)])
        return size

    # First pass: assign ids to islands and record sizes
    for r in range(n):
        for c in range(n):
            if grid[r][c] == 1:  # If it's part of an island
                island_size[island_id] = bfs(r, c, island_id)
                island_id += 1

    # Second pass: check every 0 cell and calculate potential island size
    max_island = max(island_size.values(), default=0)  # Start with the largest existing island
    for r in range(n):
        for c in range(n):
            if grid[r][c] == 0:  # Consider flipping this 0 to a 1
                seen_islands = set()  # Track unique neighboring islands
                new_size = 1  # Start with size 1 for the flipped cell
                for nr, nc in [(r-1, c), (r+1, c), (r, c-1), (r, c+1)]:
                    if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] > 1:
                        seen_islands.add(grid[nr][nc])  # Add neighboring island ids
                new_size += sum(island_size[i] for i in seen_islands)  # Add sizes of all unique neighboring islands
                max_island = max(max_island, new_size)  # Update max island size if necessary

    return max_island  # Return the size of the largest possible island

Example:

grid = [
  [1, 0],
  [0, 1]
]
print(largestIsland(grid))  # Output: 3

Explanation:

  • The BFS first identifies all islands and calculates their sizes.
  • We then evaluate the effect of converting each 0 to 1, merging adjacent islands, and keeping track of the maximum island size.

4. 1091. Shortest Path in Binary Matrix

Problem:

Given a binary matrix, return the length of the shortest clear path from the top-left corner to the bottom-right corner. If such a path does not exist, return -1. The path can only move in 8 possible directions.

Approach (BFS):

  • Use BFS to explore all possible paths starting from the top-left corner. The first time you reach the bottom-right corner, the length of the path is the answer.

Python Code:

from collections import deque

def rightSideView(root: TreeNode) -> List[int]:
    if not root:
        return []

    view = []  # List to store the rightmost nodes
    queue = deque([root])  # Start BFS with the root

    while queue:
        level_length = len(queue)  # Number of nodes at the current level
        for i in range(level_length):
            node = queue.popleft()
            if i == level_length - 1:  # If it's the last node in the current level
                view.append(node.val)  # Add it to the view

            if node.left:
                queue.append(node.left)  # Add left child to the queue
            if node.right:
                queue.append(node.right)  # Add right child to the queue

    return view  # Return the list of rightmost nodes

Example:

grid = [
  [0, 1],
  [1, 0]
]
print(shortestPathBinaryMatrix(grid))  # Output: 2

Explanation:

  • BFS explores all paths level by level. The first time the BFS reaches the bottom-right corner, it returns the path length as the answer.
  • This guarantees the shortest path is found.

5. 199. Binary Tree Right Side View

Problem:

Given a binary tree, return the values of the nodes you can see when looking at the tree from the right side.

Approach (BFS):

  • Use BFS to traverse the tree level by level, and take the last node of each level, as it represents the rightmost node visible from the right side.

Python Code:

6. 133. Clone Graph

from collections import deque

def cloneGraph(node: 'Node') -> 'Node':
    if not node:
        return None

    clones = {node: Node(node.val)}  # Dictionary to keep track of cloned nodes
    queue = deque([node])  # BFS queue starting with the original node

    # BFS loop to clone the graph
    while queue:
        current = queue.popleft()
        for neighbor in current.neighbors:
            if neighbor not in clones:  # If the neighbor hasn't been cloned yet
                clones[neighbor] = Node(neighbor.val)  # Clone the neighbor
                queue.append(neighbor)  # Add the original neighbor to the queue
            clones[current].neighbors.append(clones[neighbor])  # Link the clone of the current node to the clone of the neighbor

    return clones[node]  # Return the clone of the original node

7. 102. Binary Tree Level Order Traversal

from collections import deque

def levelOrder(root: TreeNode) -> List[List[int]]:
    if not root:
        return []

    result = []  # List to store the level order traversal
    queue = deque([root])  # Start BFS with the root

    # BFS loop to traverse the tree level by level
    while queue:
        level = []
        level_length = len(queue)  # Number of nodes at the current level
        for _ in range(level_length):
            node = queue.popleft()
            level.append(node.val)  # Add the node's value to the current level

'ML Engineering > python' 카테고리의 다른 글

06. Top K Elements Technique  (0) 2024.08.06
05. Modified Binary Search Technique  (0) 2024.08.06
03. Binary Tree DFS Techniques  (0) 2024.08.06
02. Sliding Window Technique  (0) 2024.08.06
01. Two Pointers Technique  (0) 2024.08.06

Binary Tree DFS Techniques

Depth-First Search (DFS) is a fundamental algorithm used to traverse or search tree or graph data structures. In the context of binary trees, DFS can be implemented in three primary ways: Inorder, Preorder, and Postorder traversal. Each of these traversals has a distinct order of visiting nodes.

1. Inorder Traversal (Left, Root, Right)

In Inorder traversal, the nodes are visited in the following order: left subtree, root, right subtree. This traversal is particularly useful for binary search trees (BSTs) because it visits the nodes in ascending order.

Algorithm:

  1. Traverse the left subtree.
  2. Visit the root node.
  3. Traverse the right subtree.

Code:

def inorder_traversal(root):
    if root is not None:
        inorder_traversal(root.left)
        print(root.val, end=' ')
        inorder_traversal(root.right)

# Example usage:
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

# Constructing the binary tree
#       3
#      / \
#     9   20
#        /  \
#       15   7
tree = TreeNode(3)
tree.left = TreeNode(9)
tree.right = TreeNode(20, TreeNode(15), TreeNode(7))

inorder_traversal(tree)  # Output: 9 3 15 20 7

2. Preorder Traversal (Root, Left, Right)

In Preorder traversal, the nodes are visited in the following order: root, left subtree, right subtree. This traversal is useful for creating a copy of the tree or for prefix expression evaluation.

Algorithm:

  1. Visit the root node.
  2. Traverse the left subtree.
  3. Traverse the right subtree.

Code:

def preorder_traversal(root):
    if root is not None:
        print(root.val, end=' ')
        preorder_traversal(root.left)
        preorder_traversal(root.right)

# Example usage:
preorder_traversal(tree)  # Output: 3 9 20 15 7

3. Postorder Traversal (Left, Right, Root)

In Postorder traversal, the nodes are visited in the following order: left subtree, right subtree, root. This traversal is useful for deleting nodes in a tree or for postfix expression evaluation.

Algorithm:

  1. Traverse the left subtree.
  2. Traverse the right subtree.
  3. Visit the root node.

Code:

def postorder_traversal(root):
    if root is not None:
        postorder_traversal(root.left)
        postorder_traversal(root.right)
        print(root.val, end=' ')

# Example usage:
postorder_traversal(tree)  # Output: 9 15 7 20 3

Iterative Approaches

While the above examples use recursion, DFS traversals can also be implemented iteratively using a stack.

Iterative Inorder Traversal

Code:

def iterative_inorder_traversal(root):
    stack, result = [], []
    current = root
    while current or stack:
        while current:
            stack.append(current)
            current = current.left
        current = stack.pop()
        result.append(current.val)
        current = current.right
    return result

# Example usage:
print(iterative_inorder_traversal(tree))  # Output: [9, 3, 15, 20, 7]

Iterative Preorder Traversal

Code:

def iterative_preorder_traversal(root):
    if root is None:
        return []
    stack, result = [root], []
    while stack:
        node = stack.pop()
        result.append(node.val)
        if node.right:
            stack.append(node.right)
        if node.left:
            stack.append(node.left)
    return result

# Example usage:
print(iterative_preorder_traversal(tree))  # Output: [3, 9, 20, 15, 7]

Iterative Postorder Traversal

Code:

def iterative_postorder_traversal(root):
    if root is None:
        return []
    stack1, stack2, result = [root], [], []
    while stack1:
        node = stack1.pop()
        stack2.append(node)
        if node.left:
            stack1.append(node.left)
        if node.right:
            stack1.append(node.right)
    while stack2:
        node = stack2.pop()
        result.append(node.val)
    return result

# Example usage:
print(iterative_postorder_traversal(tree))  # Output: [9, 15, 7, 20, 3]

Summary

  • Inorder Traversal: Visits nodes in ascending order for BSTs (Left, Root, Right).
  • Preorder Traversal: Useful for copying the tree and prefix expression (Root, Left, Right).
  • Postorder Traversal: Useful for deleting nodes and postfix expression (Left, Right, Root).

Each traversal method has its unique applications and can be implemented both recursively and iteratively, depending on the problem requirements and constraints.

+ Recent posts