## Tag Archives: leetcode

## C# || How To Group People Given The Group Size They Belong To Using C#

The following is a module with functions which demonstrates how to group people given the group size they belong to using C#.

1. Group The People – Problem Statement

There are **n** people that are split into some unknown number of groups. Each person is labeled with a **unique ID** from **0** to **n – 1**.

You are given an integer array **groupSizes**, where **groupSizes[i]** is the size of the group that person **i** is in. For example, if **groupSizes[1] = 3**, then person **1** must be in a group of size **3**.

Return *a list of groups such that each person i is in a group of size groupSizes[i]*.

Each person should appear in **exactly one group**, and every person must be in a group. If there are multiple answers, **return any of them**. It is **guaranteed** that there will be **at least one** valid solution for the given input.

**Example 1:**

Input:groupSizes = [3,3,3,3,3,1,3]

Output:[[5],[0,1,2],[3,4,6]]

Explanation:

The first group is [5]. The size is 1, and groupSizes[5] = 1.

The second group is [0,1,2]. The size is 3, and groupSizes[0] = groupSizes[1] = groupSizes[2] = 3.

The third group is [3,4,6]. The size is 3, and groupSizes[3] = groupSizes[4] = groupSizes[6] = 3.

Other possible solutions are [[2,1,6],[5],[0,4,3]] and [[5],[0,6,2],[4,3,1]].

**Example 2:**

Input:groupSizes = [2,1,3,3,3,2]

Output:[[1],[0,5],[2,3,4]]

2. Group The People – Solution

The following is a solution which demonstrates how to group people given the group size they belong to.

```
```
12345678910111213141516171819202122232425262728293031
// ============================================================================// Author: Kenneth Perkins// Date: Feb 14, 2024// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to group people given group they belong to// ============================================================================public class Solution { public IList<IList<int>> GroupThePeople(int[] groupSizes) { var ans = new List<IList<int>>(); // A map from group size to the list of indices that are there in the group. var szToGroup = new Dictionary<int, List<int>>(); for (int i = 0; i < groupSizes.Length; i++) { if (!szToGroup.ContainsKey(groupSizes[i])) { szToGroup.Add(groupSizes[i], new List<int>()); } var group = szToGroup[groupSizes[i]]; group.Add(i); // When the list size equals the group size, empty it and store it in the answer. if (group.Count == groupSizes[i]) { ans.Add(group); szToGroup.Remove(groupSizes[i]); } } return ans; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:

[[0,1,2],[5],[3,4,6]]

[[1],[2,3,4],[0,5]]

## C# || How To Find Minimum Deletions To Make Character Frequencies Unique Using C#

The following is a module with functions which demonstrates how to find the minimum deletions to make character frequencies unique using C#.

1. Min Deletions – Problem Statement

A string **s** is called **good** if there are no two different characters in **s** that have the same **frequency**.

Given a string **s**, return* the minimum number of characters you need to delete to make *

**s**

**good**.The **frequency** of a character in a string is the number of times it appears in the string. For example, in the string **“aab”**, the **frequency** of **‘a’** is **2**, while the **frequency** of **‘b’** is **1**.

**Example 1:**

Input:s = "aab"

Output:0

Explanation:`s`

is already good.

**Example 2:**

Input:s = "aaabbbcc"

Output:2

Explanation:You can delete two 'b's resulting in the good string "aaabcc".

Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc".

**Example 3:**

Input:s = "ceabaacb"

Output:2

Explanation:You can delete both 'c's resulting in the good string "eabaab".

Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).

2. Min Deletions – Solution

The following is a solution which demonstrates how to find the minimum deletions to make character frequencies unique.

```
```
1234567891011121314151617181920212223242526272829303132333435
// ============================================================================// Author: Kenneth Perkins// Date: Feb 1, 2024// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to find minimum deletions to make unique// ============================================================================public class Solution { public int MinDeletions(string s) { // Store the frequency of each character int[] frequency = new int[26]; for (int i = 0; i < s.Length; i++) { frequency[s[i] - 'a']++; } Array.Sort(frequency); int deleteCount = 0; // Maximum frequency the current character can have int maxFreqAllowed = s.Length; // Iterate over the frequencies in descending order for (int i = 25; i >= 0 && frequency[i] > 0; i--) { // Delete characters to make the frequency equal the maximum frequency allowed if (frequency[i] > maxFreqAllowed) { deleteCount += frequency[i] - maxFreqAllowed; frequency[i] = maxFreqAllowed; } // Update the maximum allowed frequency maxFreqAllowed = Math.Max(0, frequency[i] - 1); } return deleteCount; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:

0

2

2

## C# || Reconstruct Itinerary – How To Reconstruct Itinerary In Order Using C#

The following is a module with functions which demonstrates how to reconstruct itinerary in order using C#.

1. Find Itinerary – Problem Statement

You are given a list of airline **tickets** where **tickets[i] = [from _{i}, to_{i}]** represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.

All of the tickets belong to a man who departs from **“JFK”**, thus, the itinerary must begin with **“JFK”**. If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.

- For example, the itinerary
**[“JFK”, “LGA”]**has a smaller lexical order than**[“JFK”, “LGB”]**.

You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.

**Example 1:**

Input:tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]

Output:["JFK","MUC","LHR","SFO","SJC"]

**Example 2:**

Input:tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]

Output:["JFK","ATL","JFK","SFO","ATL","SFO"]

Explanation:Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order.

2. Find Itinerary – Solution

The following is a solution which demonstrates how to reconstruct itinerary in order.

```
```
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
// ============================================================================// Author: Kenneth Perkins// Date: Jan 1, 2024// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to reconstruct itinerary in order// ============================================================================public class Solution { public IList<string> FindItinerary(IList<IList<string>> tickets) { var map = new Dictionary<string, List<string>>(); for (int index = 0; index < tickets.Count; ++index) { List<string> ticket = tickets[index].ToList(); string from = ticket[0]; string to = ticket[1]; if (!map.ContainsKey(from)) { map[from] = new List<string>(); } map[from].Add(to); } foreach (List<string> list in map.Values) { list.Sort(); } var result = new List<string>(); string start = "JFK"; result.Add(start); DFS(map, start, result, tickets.Count); return result; } private bool DFS(Dictionary<string, List<string>> map, string cur, List<string> result, int totalTicket) { if (result.Count == totalTicket + 1) { return true; } if (!map.ContainsKey(cur)) { return false; } List<string> nextList = map[cur]; for (int index = 0; index < nextList.Count; ++index) { string next = nextList[index]; if (next == null) { continue; } nextList[index] = null; result.Add(next); if (DFS(map, next, result, totalTicket)) { return true; } // back track result.RemoveAt(result.Count - 1); nextList[index] = next; } return false; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output for the example cases:

["JFK","MUC","LHR","SFO","SJC"]

["JFK","ATL","JFK","SFO","ATL","SFO"]

## C# || How To Find Minimum Operations To Reduce X To Zero Using C#

The following is a module with functions which demonstrates how to find the minimum number of operations to reduce X to zero using C#.

1. Min Operations – Problem Statement

You are given an integer array **nums** and an integer **x**. In one operation, you can either remove the leftmost or the rightmost element from the array **nums** and subtract its value from **x**. Note that this **modifies** the array for future operations.

Return *the minimum number of operations to reduce *

**x**

*to*

**exactly****0**

*if it is possible*

*, otherwise, return*

**-1**.

**Example 1:**

Input:nums = [1,1,4,2,3], x = 5

Output:2

Explanation:The optimal solution is to remove the last two elements to reduce x to zero.

**Example 2:**

Input:nums = [5,6,7,8,9], x = 4

Output:-1

**Example 3:**

Input:nums = [3,2,20,1,1,3], x = 10

Output:5

Explanation:The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.

2. Min Operations – Solution

The following is a solution which demonstrates how to find the minimum number of operations to reduce X to zero.

```
```
123456789101112131415161718192021222324252627282930313233343536
// ============================================================================// Author: Kenneth Perkins// Date: Dec 25, 2023// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to find the minimum operations reduce X// ============================================================================public class Solution { public int MinOperations(int[] nums, int x) { var target = -x; foreach (int num in nums) { target += num; } // since all elements are positive, we have to take all of them if (target == 0) { return nums.Length; } var map = new Dictionary<int, int>(); map[0] = -1; var sum = 0; var res = int.MinValue; for (var index = 0; index < nums.Length; ++index) { sum += nums[index]; if (map.ContainsKey(sum - target)) { res = Math.Max(res, index - map[sum - target]); } // no need to check containsKey since sum is unique map[sum] = index; } return res == int.MinValue ? -1 : nums.Length - res; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

Once compiled, you should get this as your output for the example cases:

2

-1

5

## C# || How To Sort An Array By Parity Using C#

The following is a module with functions which demonstrates how to sort an array by parity using C#.

1. Sort Array By Parity – Problem Statement

Given an integer array **nums**, move all the even integers at the beginning of the array followed by all the odd integers.

Return * any array that satisfies this condition*.

**Example 1:**

Input:nums = [3,1,2,4]

Output:[2,4,3,1]

Explanation:The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

**Example 2:**

Input:nums = [0]

Output:[0]

2. Sort Array By Parity – Solution

The following is a solution which demonstrates how to sort an array by parity.

```
```
1234567891011121314151617181920212223242526272829
// ============================================================================// Author: Kenneth Perkins// Date: Dec 1, 2023// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to sort an array by parity// ============================================================================public class Solution { public int[] SortArrayByParity(int[] nums) { var startIndex = 0; var endIndex = nums.Length -1; while (startIndex < endIndex) { if (IsOdd(nums[startIndex])) { var temp = nums[startIndex]; nums[startIndex] = nums[endIndex]; nums[endIndex] = temp; --endIndex; } else { ++startIndex; } } return nums; } private bool IsOdd(int num) { return num % 2 != 0; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

Once compiled, you should get this as your output for the example cases:

[4,2,1,3]

[0]

## C# || Parallel Courses III – How To Find Minimum Number Months To Complete All Courses Using C#

The following is a module with functions which demonstrates how to find the minimum number of months needed to complete all courses using C#.

1. Minimum Time – Problem Statement

You are given an integer **n**, which indicates that there are **n** courses labeled from **1** to **n**. You are also given a 2D integer array **relations** where **relations[j] = [prevCourse _{j}, nextCourse_{j}]** denotes that course

**prevCourse**has to be completed

_{j}**before**course

**nextCourse**(prerequisite relationship). Furthermore, you are given a

_{j}**0-indexed**integer array

**time**where

**time[i]**denotes how many

**months**it takes to complete the

**(i+1)**course.

^{th}You must find the **minimum** number of months needed to complete all the courses following these rules:

- You may start taking a course at
**any time**if the prerequisites are met. **Any number of courses**can be taken at the**same time**.

Return *the minimum number of months needed to complete all the courses*.

**Note:** The test cases are generated such that it is possible to complete every course (i.e., the graph is a directed acyclic graph).

**Example 1:**

Input:n = 3, relations = [[1,3],[2,3]], time = [3,2,5]

Output:8

Explanation:The figure above represents the given graph and the time required to complete each course.

We start course 1 and course 2 simultaneously at month 0.

Course 1 takes 3 months and course 2 takes 2 months to complete respectively.

Thus, the earliest time we can start course 3 is at month 3, and the total time required is 3 + 5 = 8 months.

**Example 2:**

Input:n = 5, relations = [[1,5],[2,5],[3,5],[3,4],[4,5]], time = [1,2,3,4,5]

Output:12

Explanation:The figure above represents the given graph and the time required to complete each course.

You can start courses 1, 2, and 3 at month 0.

You can complete them after 1, 2, and 3 months respectively.

Course 4 can be taken only after course 3 is completed, i.e., after 3 months. It is completed after 3 + 4 = 7 months.

Course 5 can be taken only after courses 1, 2, 3, and 4 have been completed, i.e., after max(1,2,3,7) = 7 months.

Thus, the minimum time needed to complete all the courses is 7 + 5 = 12 months.

2. Minimum Time – Solution

The following is a solution which demonstrates how to find the minimum number of months needed to complete all courses.

```
```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
// ============================================================================// Author: Kenneth Perkins// Date: Nov 1, 2023// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to find the minimum months complete courses// ============================================================================public class Solution { public int MinimumTime(int n, int[][] relations, int[] time) { var graph = new Dictionary<int, List<int>>(); for (int i = 0; i < n; i++) { graph[i] = new List<int>(); } int[] indegree = new int[n]; foreach (int[] edge in relations) { int x = edge[0] - 1; int y = edge[1] - 1; graph[x].Add(y); indegree[y]++; } var queue = new Queue<int>(); int[] maxTime = new int[n]; for (int node = 0; node < n; node++) { if (indegree[node] == 0) { queue.Enqueue(node); maxTime[node] = time[node]; } } while (queue.Count > 0) { int node = queue.Dequeue(); foreach (int neighbor in graph[node]) { maxTime[neighbor] = Math.Max(maxTime[neighbor], maxTime[node] + time[neighbor]); indegree[neighbor]--; if (indegree[neighbor] == 0) { queue.Enqueue(neighbor); } } } int ans = 0; for (int node = 0; node < n; node++) { ans = Math.Max(ans, maxTime[node]); } return ans; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

Once compiled, you should get this as your output for the example cases:

8

12

## C# || How To Find Largest Value In Each Binary Tree Row Using C#

The following is a module with functions which demonstrates how to find the largest value in each binary tree row using C#.

1. Largest Values – Problem Statement

Given the **root** of a binary tree, return *an array of the largest value in each row* of the tree **(0-indexed)**.

**Example 1:**

Input:root = [1,3,2,5,3,null,9]

Output:[1,3,9]

**Example 2:**

Input:root = [1,2,3]

Output:[1,3]

2. Largest Values – Solution

The following is a solution which demonstrates how to find the largest value in each binary tree row.

```
```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
// ============================================================================// Author: Kenneth Perkins// Date: Oct 28, 2023// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to find the largest value binary tree row// ============================================================================/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) { * this.val = val; * this.left = left; * this.right = right; * } * } */public class Solution { public IList<int> LargestValues(TreeNode root) { if (root == null) { return new List<int>(); } var ans = new List<int>(); var queue = new Queue<TreeNode>(); queue.Enqueue(root); while (queue.Count > 0) { int currMax = int.MinValue; for (int i = queue.Count -1; i >= 0; --i) { var node = queue.Dequeue(); currMax = Math.Max(currMax, node.val); if (node.left != null) { queue.Enqueue(node.left); } if (node.right != null) { queue.Enqueue(node.right); } } ans.Add(currMax); } return ans; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

Once compiled, you should get this as your output for the example cases:

[1,3,9]

[1,3]

## C# || How To Find The Minimum Speed To Arrive On Time Using C#

The following is a module with functions which demonstrates how to find the minimum speed to arrive on time using C#.

1. Min Speed On Time – Problem Statement

You are given a floating-point number **hour**, representing the amount of time you have to reach the office. To commute to the office, you must take **n** trains in sequential order. You are also given an integer array **dist** of length **n**, where **dist[i]** describes the distance (in kilometers) of the **i ^{th}** train ride.

Each train can only depart at an integer hour, so you may need to wait in between each train ride.

- For example, if the
**1**train ride takes^{st}**1.5**hours, you must wait for an additional**0.5**hours before you can depart on the**2**train ride at the 2 hour mark.^{nd}

Return *the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or *

**-1**

*if it is impossible to be on time*.

Tests are generated such that the answer will not exceed **10 ^{7}** and

**hour**will have

**at most two digits after the decimal point**.

**Example 1:**

Input:dist = [1,3,2], hour = 6

Output:1

Explanation:At speed 1:

- The first train ride takes 1/1 = 1 hour.

- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours.

- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours.

- You will arrive at exactly the 6 hour mark.

**Example 2:**

Input:dist = [1,3,2], hour = 2.7

Output:3

Explanation:At speed 3:

- The first train ride takes 1/3 = 0.33333 hours.

- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour.

- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours.

- You will arrive at the 2.66667 hour mark.

**Example 3:**

Input:dist = [1,3,2], hour = 1.9

Output:-1

Explanation:It is impossible because the earliest the third train can depart is at the 2 hour mark.

2. Min Speed On Time – Solution

The following is a solution which demonstrates how to find the minimum speed to arrive on time.

```
```
1234567891011121314151617181920212223242526272829303132333435363738
// ============================================================================// Author: Kenneth Perkins// Date: Sep 1, 2023// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to find the minimum speed to arrive on time// ============================================================================public class Solution { public int MinSpeedOnTime(int[] dist, double hour) { int left = 1; int right = 10000000; int minSpeed = -1; while (left <= right) { int mid = left + (right - left) / 2; // Move to the left half. if (TimeRequired(dist, mid) <= hour) { minSpeed = mid; right = mid - 1; } else { // Move to the right half. left = mid + 1; } } return minSpeed; } double TimeRequired(int[] dist, int speed) { double time = 0.0; for (int i = 0 ; i < dist.Length; i++) { double t = (double) dist[i] / (double) speed; // Round off to the next integer, if not the last ride. time += (i == dist.Length - 1 ? t : Math.Ceiling(t)); } return time; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

Once compiled, you should get this as your output for the example cases:

1

3

-1

## C# || How To Find The Minimum ASCII Delete Sum for Two Strings Using C#

The following is a module with functions which demonstrates how to find the minimum ASCII delete sum for two strings using C#.

1. Minimum Delete Sum – Problem Statement

Given two strings **s1** and **s2**, return *the lowest ASCII sum of deleted characters to make two strings equal*.

**Example 1:**

Input:s1 = "sea", s2 = "eat"

Output:231

Explanation:Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.

Deleting "t" from "eat" adds 116 to the sum.

At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.

**Example 2:**

Input:s1 = "delete", s2 = "leet"

Output:403

Explanation:Deleting "dee" from "delete" to turn the string into "let",

adds 100[d] + 101[e] + 101[e] to the sum.

Deleting "e" from "leet" adds 101[e] to the sum.

At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.

If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.

2. Minimum Delete Sum – Solution

The following is a solution which demonstrates how to find the minimum ASCII delete sum for two strings.

```
```
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
// ============================================================================// Author: Kenneth Perkins// Date: Aug 28, 2023// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to find minimum ASCII delete sum two string// ============================================================================public class Solution { public int MinimumDeleteSum(string s1, string s2) { // Make sure s2 is smaller string if (s1.Length < s2.Length) { return MinimumDeleteSum(s2, s1); } // Case for empty s1 int m = s1.Length, n = s2.Length; int[] currRow = new int[n + 1]; for (int j = 1; j <= n; j++) { currRow[j] = currRow[j - 1] + s2[j - 1]; } // Compute answer row-by-row for (int i = 1; i <= m; i++) { int diag = currRow[0]; currRow[0] += s1[i - 1]; for (int j = 1; j <= n; j++) { int answer; // If characters are the same, the answer is top-left-diagonal value if (s1[i - 1] == s2[j - 1]) { answer = diag; } // Otherwise, the answer is minimum of top and left values with // deleted character's ASCII value else { answer = Math.Min( s1[i - 1] + currRow[j], s2[j - 1] + currRow[j - 1] ); } // Before overwriting currRow[j] with answer, save it in diag // for the next column diag = currRow[j]; currRow[j] = answer; } } // Return the answer return currRow[n]; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

Once compiled, you should get this as your output for the example cases:

231

403

## C# || Fruit Into Baskets – How To Find The Maximum Number Of Fruits Using C#

The following is a module with functions which demonstrates how to find the maximum number of fruits using C#.

1. Total Fruit – Problem Statement

You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array **fruits** where **fruits[i]** is the **type** of fruit the **i ^{th}** tree produces.

You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:

- You only have
**two**baskets, and each basket can only hold a**single type**of fruit. There is no limit on the amount of fruit each basket can hold. - Starting from any tree of your choice, you must pick
**exactly one fruit**from**every**tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets. - Once you reach a tree with fruit that cannot fit in your baskets, you must stop.

Given the integer array **fruits**, return *the maximum number of fruits you can pick*.

**Example 1:**

Input:fruits = [1,2,1]

Output:3

Explanation:We can pick from all 3 trees.

**Example 2:**

Input:fruits = [0,1,2,2]

Output:3

Explanation:We can pick from trees [1,2,2].

If we had started at the first tree, we would only pick from trees [0,1].

**Example 3:**

Input:fruits = [1,2,3,2,2]

Output:4

Explanation:We can pick from trees [2,3,2,2].

If we had started at the first tree, we would only pick from trees [1,2].

2. Total Fruit – Solution

The following is a solution which demonstrates how to find the maximum number of fruits.

```
```
12345678910111213141516171819202122232425262728293031323334353637
// ============================================================================// Author: Kenneth Perkins// Date: Jul 28, 2023// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to find the maximum number of fruits// ============================================================================public class Solution { public int TotalFruit(int[] fruits) { // We use a hash map 'basket' to store the number of each type of fruit. var basket = new Dictionary<int, int>(); int left = 0; int maxPicked = 0; // Add fruit from the right index (right) of the window. for (int right = 0; right < fruits.Length; ++right) { basket[fruits[right]] = basket.GetValueOrDefault(fruits[right], 0) + 1; // If the current window has more than 2 types of fruit, // we remove fruit from the left index (left) of the window, // until the window has only 2 types of fruit. while (basket.Count > 2) { basket[fruits[left]] = basket[fruits[left]] - 1; if (basket[fruits[left]] == 0) { basket.Remove(fruits[left]); } ++left; } // Update maxPicked. maxPicked = Math.Max(maxPicked, right - left + 1); } // Return maxPicked as the maximum number of fruits we can collect. return maxPicked; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

Once compiled, you should get this as your output for the example cases:

3

3

4

## C# || How To Find The Minimum Rounds To Complete All Tasks Using C#

The following is a module with functions which demonstrates how to find the minimum rounds to complete all tasks using C#.

1. Minimum Rounds – Problem Statement

You are given a **0-indexed** integer array **tasks**, where **tasks[i]** represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the **same difficulty level**.

Return *the minimum rounds required to complete all the tasks, or *

**-1**

*if it is not possible to complete all the tasks.*

**Example 1:**

Input:tasks = [2,2,3,3,2,4,4,4,4,4]

Output:4

Explanation:To complete all the tasks, a possible plan is:

- In the first round, you complete 3 tasks of difficulty level 2.

- In the second round, you complete 2 tasks of difficulty level 3.

- In the third round, you complete 3 tasks of difficulty level 4.

- In the fourth round, you complete 2 tasks of difficulty level 4.

It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.

**Example 2:**

Input:tasks = [2,3,3]

Output:-1

Explanation:There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.

2. Minimum Rounds – Solution

The following is a solution which demonstrates how to find the minimum rounds to complete all tasks.

```
```
123456789101112131415161718192021222324252627282930313233343536
// ============================================================================// Author: Kenneth Perkins// Date: Jul 1, 2023// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to find minimum rounds to complete tasks// ============================================================================public class Solution { public int MinimumRounds(int[] tasks) { var freq = new Dictionary<int, int>(); // Store the frequencies in the map. foreach (var task in tasks) { freq[task] = freq.GetValueOrDefault(task, 0) + 1; } int minimumRounds = 0; // Iterate over the task's frequencies. foreach (int count in freq.Values) { // If the frequency is 1, it's not possible to complete tasks. if (count == 1) { return - 1; } if (count % 3 == 0) { // Group all the task in triplets. minimumRounds += count / 3; } else { // If count % 3 = 1; (count / 3 - 1) groups of triplets and 2 pairs. // If count % 3 = 2; (count / 3) groups of triplets and 1 pair. minimumRounds += (count / 3) + 1; } } return minimumRounds; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

Once compiled, you should get this as your output for the example cases:

4

-1

## C# || How To Design A Least Frequently Used (LFU) Cache Using C#

The following is a module with functions which demonstrates how to design a least frequently used (LFU) cache using C#.

1. LFU Cache – Problem Statement

Design and implement a data structure for a Least Frequently Used (LFU) cache.

Implement the **LFUCache** class:

**LFUCache(int capacity)**Initializes the object with the**capacity**of the data structure.**int get(int key)**Gets the value of the**key**if the**key**exists in the cache. Otherwise, returns**-1**.**void put(int key, int value)**Update the value of the**key**if present, or inserts the**key**if not already present. When the cache reaches its**capacity**, it should invalidate and remove the**least frequently used**key before inserting a new item. For this problem, when there is a**tie**(i.e., two or more keys with the same frequency), the**least recently used****key**would be invalidated.

To determine the least frequently used key, a **use counter** is maintained for each key in the cache. The key with the smallest **use counter** is the least frequently used key.

When a key is first inserted into the cache, its **use counter** is set to **1** (due to the **put** operation). The **use counter** for a key in the cache is incremented either a **get** or **put** operation is called on it.

The functions **get** and **put** must each run in **O(1)** average time complexity.

**Example 1:**

Input

["LFUCache", "put", "put", "get", "put", "get", "get", "put", "get", "get", "get"]

[[2], [1, 1], [2, 2], [1], [3, 3], [2], [3], [4, 4], [1], [3], [4]]

Output

[null, null, null, 1, null, -1, 3, null, -1, 3, 4]

Explanation

// cnt(x) = the use counter for key x

// cache=[] will show the last used order for tiebreakers (leftmost element is most recent)

LFUCache lfu = new LFUCache(2);

lfu.put(1, 1); // cache=[1,_], cnt(1)=1

lfu.put(2, 2); // cache=[2,1], cnt(2)=1, cnt(1)=1

lfu.get(1); // return 1

// cache=[1,2], cnt(2)=1, cnt(1)=2

lfu.put(3, 3); // 2 is the LFU key because cnt(2)=1 is the smallest, invalidate 2.

// cache=[3,1], cnt(3)=1, cnt(1)=2

lfu.get(2); // return -1 (not found)

lfu.get(3); // return 3

// cache=[3,1], cnt(3)=2, cnt(1)=2

lfu.put(4, 4); // Both 1 and 3 have the same cnt, but 1 is LRU, invalidate 1.

// cache=[4,3], cnt(4)=1, cnt(3)=2

lfu.get(1); // return -1 (not found)

lfu.get(3); // return 3

// cache=[3,4], cnt(4)=1, cnt(3)=3

lfu.get(4); // return 4

// cache=[4,3], cnt(4)=2, cnt(3)=3

2. LFU Cache – Solution

The following is a solution which demonstrates how to design a least frequently used (LFU) cache.

```
```
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
// ============================================================================// Author: Kenneth Perkins// Date: Jun 1, 2022// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to design a least frequently used cache// ============================================================================/** * Your LFUCache object will be instantiated and called as such: * LFUCache obj = new LFUCache(capacity); * int param_1 = obj.Get(key); * obj.Put(key,value); */public class LFUCache { // key: original key, value: frequency and original value. private Dictionary<int, Pair<int, Pair<int, int>>> cache; // key: frequency, value: All keys that have the same frequency. private Dictionary<int, List<Pair<int, int>>> frequencies; private int minf; private int capacity; public LFUCache(int capacity) { cache = new Dictionary<int, Pair<int, Pair<int, int>>>(); frequencies = new Dictionary<int, List<Pair<int, int>>>(); minf = 0; this.capacity = capacity; } public void Insert(int key, int frequency, int value) { if (!frequencies.ContainsKey(frequency)) { frequencies[frequency] = new List<Pair<int, int>>(); } frequencies[frequency].Add(new Pair<int, int>(key, value)); cache[key] = new Pair<int, Pair<int, int>>(frequency, frequencies[frequency].Last()); } public int Get(int key) { if (!cache.ContainsKey(key)) { return -1; } var pair = cache[key]; int f = pair.Key; var kv = pair.Value; frequencies[f].Remove(kv); if (frequencies[f].Count == 0 && minf == f) { ++minf; } Insert(key, f + 1, kv.Value); return kv.Value; } public void Put(int key, int value) { if (capacity <= 0) { return; } if (cache.ContainsKey(key)) { var it = cache[key]; it.Value.Value = value; Get(key); return; } if (capacity == cache.Count) { cache.Remove(frequencies[minf].First().Key); frequencies[minf].RemoveAt(0); } minf = 1; Insert(key, 1, value); } private class Pair<TKey, TValue> { public TKey Key; public TValue Value; public Pair(TKey key, TValue value) { Key = key; Value = value; } }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

Once compiled, you should get this as your output for the example cases:

[null,null,null,1,null,-1,3,null,-1,3,4]

## C# || How To Find The Minimum Fuel Cost To Report To The Capital Using C#

The following is a module with functions which demonstrates how to find the minimum fuel cost to report to the capital using C#.

1. Minimum Fuel Cost – Problem Statement

There is a tree (i.e., a connected, undirected graph with no cycles) structure country network consisting of **n** cities numbered from **0** to **n – 1** and exactly **n – 1** roads. The capital city is city **0**. You are given a 2D integer array **roads** where **roads[i] = [a _{i}, b_{i}]** denotes that there exists a

**bidirectional road**connecting cities

**a**and

_{i}**b**.

_{i}There is a meeting for the representatives of each city. The meeting is in the capital city.

There is a car in each city. You are given an integer **seats** that indicates the number of seats in each car.

A representative can use the car in their city to travel or change the car and ride with another representative. The cost of traveling between two cities is one liter of fuel.

Return *the minimum number of liters of fuel to reach the capital city*.

**Example 1:**

Input:roads = [[0,1],[0,2],[0,3]], seats = 5

Output:3

Explanation:

- Representative_{1}goes directly to the capital with 1 liter of fuel.

- Representative_{2}goes directly to the capital with 1 liter of fuel.

- Representative_{3}goes directly to the capital with 1 liter of fuel.

It costs 3 liters of fuel at minimum.

It can be proven that 3 is the minimum number of liters of fuel needed.

**Example 2:**

Input:roads = [[3,1],[3,2],[1,0],[0,4],[0,5],[4,6]], seats = 2

Output:7

Explanation:

- Representative_{2}goes directly to city 3 with 1 liter of fuel.

- Representative_{2}and representative_{3}go together to city 1 with 1 liter of fuel.

- Representative_{2}and representative_{3}go together to the capital with 1 liter of fuel.

- Representative_{1}goes directly to the capital with 1 liter of fuel.

- Representative_{5}goes directly to the capital with 1 liter of fuel.

- Representative_{6}goes directly to city 4 with 1 liter of fuel.

- Representative_{4}and representative_{6}go together to the capital with 1 liter of fuel.

It costs 7 liters of fuel at minimum.

It can be proven that 7 is the minimum number of liters of fuel needed.

**Example 3:**

Input:roads = [], seats = 1

Output:0

Explanation:No representatives need to travel to the capital city.

2. Minimum Fuel Cost – Solution

The following is a solution which demonstrates how to find the minimum fuel cost to report to the capital.

```
```
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
// ============================================================================// Author: Kenneth Perkins// Date: May 24, 2023// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to find minimum fuel cost to the capital// ============================================================================public class Solution { public long MinimumFuelCost(int[][] roads, int seats) { int n = roads.Length + 1; var adj = new Dictionary<int, List<int>>(); int[] degree = new int[n]; foreach (int[] road in roads) { if (!adj.ContainsKey(road[0])) { adj[road[0]] = new List<int>(); } adj[road[0]].Add(road[1]); if (!adj.ContainsKey(road[1])) { adj[road[1]] = new List<int>(); } adj[road[1]].Add(road[0]); ++degree[road[0]]; ++degree[road[1]]; } return BFS(n, adj, degree, seats); } public long BFS(int n, Dictionary<int, List<int>> adj, int[] degree, int seats) { var q = new Queue<int>(); for (int i = 1; i < n; i++) { if (degree[i] == 1) { q.Enqueue(i); } } int[] representatives = new int[n]; Array.Fill(representatives, 1); long fuel = 0; while (q.Count > 0) { int node = q.Dequeue(); fuel += (long)Math.Ceiling((double) representatives[node] / seats); foreach (int neighbor in adj[node]) { --degree[neighbor]; representatives[neighbor] += representatives[node]; if (degree[neighbor] == 1 && neighbor != 0) { q.Enqueue(neighbor); } } } return fuel; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

Once compiled, you should get this as your output for the example cases:

3

7

0

## C# || How To Find The Minimum Time To Collect All Apples In A Tree Using C#

The following is a module with functions which demonstrates how to find the minimum time to collect all apples in a tree using C#.

1. Min Time – Problem Statement

Given an undirected tree consisting of **n** vertices numbered from **0** to **n-1**, which has some apples in their vertices. You spend 1 second to walk over one edge of the tree. *Return the minimum time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and coming back to this vertex.*

The edges of the undirected tree are given in the array **edges**, where **edges[i] = [a _{i}, b_{i}]** means that exists an edge connecting the vertices

**a**and

_{i}**b**. Additionally, there is a boolean array

_{i}**hasApple**, where

**hasApple[i] = true**means that vertex

**i**has an apple; otherwise, it does not have any apple.

**Example 1:**

Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,true,true,false]

Output:8

Explanation:The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.

**Example 2:**

Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,true,false,false,true,false]

Output:6

Explanation:The figure above represents the given tree where red vertices have an apple. One optimal path to collect all apples is shown by the green arrows.

**Example 3:**

Input:n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]], hasApple = [false,false,false,false,false,false,false]

Output:0

2. Min Time – Solution

The following is a solution which demonstrates how to find the cheapest flights within K stops.

```
```
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
// ============================================================================// Author: Kenneth Perkins// Date: May 23, 2023// Taken From: http://programmingnotes.org/// File: Solution.cs// Description: Demonstrates how to find minimum time to collect apples// ============================================================================public class Solution { public int MinTime(int n, int[][] edges, IList<bool> hasApple) { var adj = new Dictionary<int, List<int>>(); foreach (int[] edge in edges) { int a = edge[0]; int b = edge[1]; if (!adj.ContainsKey(a)) { adj[a] = new List<int>(); } if (!adj.ContainsKey(b)) { adj[b] = new List<int>(); } adj[a].Add(b); adj[b].Add(a); } return DFS(0, -1, adj, hasApple); } public int DFS(int node, int parent, Dictionary<int, List<int>> adj, IList<bool> hasApple) { if (!adj.ContainsKey(node)) { return 0; } int totalTime = 0; foreach (int child in adj[node]) { if (child == parent) { continue; } int childTime = DFS(child, node, adj, hasApple); // childTime > 0 indicates subtree of child has apples. Since the root node of the // subtree does not contribute to the time, even if it has an apple, we have to check it // independently. if (childTime > 0 || hasApple[child]) { totalTime += childTime + 2; } } return totalTime; }}// http://programmingnotes.org/

**QUICK NOTES**:

The highlighted lines are sections of interest to look out for.

Once compiled, you should get this as your output for the example cases:

8

6

0