Greedy Algorithm

Binary Tree Cameras

February 7, 2024
medium
DFS, Greedy Algorithm

Problem Statement # Given a binary tree, your goal is to install cameras on the tree nodes in such a way that every node in the tree is monitored. A camera at a node can monitor its parent, itself, and its immediate children. Calculate the minimum number of cameras needed to monitor all nodes of the given binary tree. Note: Every node has at most one parent. Tree nodes are numbered uniquely. ...

Minimize Deviation in Array

December 28, 2023
medium
heap, Greedy Algorithm

Problem # You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: If the element is even, divide it by 2. If the element is odd, multiply it by 2. The deviation of the array is the maximum difference between any two elements in the array. Find the minimum deviation the array can have after performing some number of operations. ...

Meeting Scheduler

December 26, 2023
medium
Two Pointers, Greedy Algorithm

Problem # Given the availability time slots arrays slots1 and slots2 of two people and a meeting duration, return the earliest time slot that works for both of them and is of duration. Solution # To solve this problem, we need to find a common time slot between two schedules (slots1 and slots2) that is at least as long as the given meeting duration. A practical approach is to sort both schedules based on start times and then iterate through them to find overlapping intervals that can accommodate the meeting duration. ...

Find the smallest set of numbers that covers all the intervals

December 24, 2023
medium
Greedy Algorithm

Problem # Given a set of closed intervals, find the smallest set of numbers that covers all the intervals. If there are multiple smallest sets, return any of them. For example, given the intervals [0, 3], [2, 6], [3, 4], [6, 9], one set of numbers that covers all these intervals is {3, 6}. Solution # Here is the Python code to find the smallest set of numbers that covers all the given intervals: ...

Optimal Meeting Points

December 24, 2023
medium
Greedy Algorithm

Problem # You are given an array of pairs representing the start and end times of various meetings. Given an integer K, a person can attend at most K meetings. Find the optimal meeting points that allow the person to attend the maximum number of meetings. Solution # The problem is about finding the maximum number of non-overlapping meetings a person can attend, given a limit on the total number of meetings they can attend (K). ...