Tag Archives: c-sharp
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] = [fromi, toi] 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
// ============================================================================ // 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
// ============================================================================ // 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.
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:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// ============================================================================ // 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.
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:
[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] = [prevCoursej, nextCoursej] denotes that course prevCoursej has to be completed before course nextCoursej (prerequisite relationship). Furthermore, you are given a 0-indexed integer array time where time[i] denotes how many months it takes to complete the (i+1)th course.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
// ============================================================================ // 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.
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:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
// ============================================================================ // 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.
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:
[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 ith 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 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark.
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 107 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
// ============================================================================ // 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.
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:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
// ============================================================================ // 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.
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:
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 ith 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
// ============================================================================ // 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.
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:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
// ============================================================================ // 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.
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:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
// ============================================================================ // 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.
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:
[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] = [ai, bi] denotes that there exists a bidirectional road connecting cities ai and bi.
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:
- Representative1 goes directly to the capital with 1 liter of fuel.
- Representative2 goes directly to the capital with 1 liter of fuel.
- Representative3 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:
- Representative2 goes directly to city 3 with 1 liter of fuel.
- Representative2 and representative3 go together to city 1 with 1 liter of fuel.
- Representative2 and representative3 go together to the capital with 1 liter of fuel.
- Representative1 goes directly to the capital with 1 liter of fuel.
- Representative5 goes directly to the capital with 1 liter of fuel.
- Representative6 goes directly to city 4 with 1 liter of fuel.
- Representative4 and representative6 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
// ============================================================================ // 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.
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:
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] = [ai, bi] means that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
// ============================================================================ // 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.
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:
8
6
0
C# || How To Sort An Array O(nlog(n)) Using C#

The following is a module with functions which demonstrates how to sort an array O(nlog(n)) complexity using C#.
1. Sort Array – Problem Statement
Given an array of integers nums, sort the array in ascending order and return it.
You must solve the problem without using any built-in functions in O(nlog(n)) time complexity and with the smallest space complexity possible.
Example 1:
Input: nums = [5,2,3,1]
Output: [1,2,3,5]
Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
Example 2:
Input: nums = [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
Explanation: Note that the values of nums are not necessairly unique.
2. Sort Array – Solution
The following is a solution which demonstrates how to sort an array O(nlog(n)) complexity using C#.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 1, 2023 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to sort an array O(nlog(n)) // ============================================================================ public class Solution { public int[] SortArray(int[] nums) { RadixSort(nums); return nums; } // Radix sort function. private void RadixSort(int[] arr) { // Find the absolute maximum element to find max number of digits. int maxElement = arr[0]; foreach (int val in arr) { maxElement = Math.Max(Math.Abs(val), maxElement); } int maxDigits = 0; while (maxElement > 0) { maxDigits += 1; maxElement /= 10; } // Radix sort, least significant digit place to most significant. int placeValue = 1; for (int digit = 0; digit < maxDigits; ++digit) { BucketSort(arr, placeValue); placeValue *= 10; } // Seperate out negatives and reverse them. List<int> negatives = new List<int>(); List<int> positives = new List<int>(); foreach (int val in arr) { if (val < 0) { negatives.Add(val); } else { positives.Add(val); } } negatives.Reverse(); // Final 'answer' will be 'negative' elements, then 'positive' elements. int index = 0; foreach (int val in negatives) { arr[index++] = val; } foreach (int val in positives) { arr[index++] = val; } } // Bucket sort function for each place value digit. private void BucketSort(int[] arr, int placeValue) { int bucketSize = 10; List<List<int>> buckets = new List<List<int>>(); for (int digit = 0; digit < bucketSize; ++digit) { buckets.Add(new List<int>()); } // Store the respective number based on its digit. foreach (int val in arr) { int digit = Math.Abs(val) / placeValue; digit = digit % bucketSize; buckets[digit].Add(val); } // Overwrite 'arr' in sorted order of current place digits. int index = 0; for (int digit = 0; digit < bucketSize; ++digit) { foreach (int val in buckets[digit]) { arr[index++] = val; } } } }// 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:
[1,2,3,5]
[0,0,1,1,2,5]
C# || How To Find The Cheapest Flights Within K Stops Using C#

The following is a module with functions which demonstrates how to find the cheapest flights within K stops using C#.
1. Find Cheapest Price – Problem Statement
There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.
You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.
Example 1:
Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1
Output: 700
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.
Example 2:
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.
Example 3:
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.
2. Find Cheapest Price – Solution
The following is a solution which demonstrates how to find the cheapest flights within K stops.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
// ============================================================================ // Author: Kenneth Perkins // Date: Apr 1, 2023 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to find cheapest flights in k stops // ============================================================================ public class Solution { public int FindCheapestPrice(int n, int[][] flights, int src, int dst, int k) { var adj = new Dictionary<int, List<int[]>>(); foreach (int[] i in flights) { if (!adj.ContainsKey(i[0])) { adj[i[0]] = new List<int[]>(); } adj[i[0]].Add(new int[] { i[1], i[2] }); } int[] stops = new int[n]; Array.Fill(stops, int.MaxValue); var pq = new PriorityQueue<int[], int[]>(Comparer<int[]>.Create((a, b) => a[0] - b[0])); // {dist_from_src_node, node, number_of_stops_from_src_node} var distance = new int[] { 0, src, 0 }; pq.Enqueue(distance, distance); while (pq.Count > 0) { int[] temp = pq.Dequeue(); int dist = temp[0]; int node = temp[1]; int steps = temp[2]; // We have already encountered a path with a lower cost and fewer stops, // or the number of stops exceeds the limit. if (steps > stops[node] || steps > k + 1) { continue; } stops[node] = steps; if (node == dst) { return dist; } if (!adj.ContainsKey(node)) { continue; } foreach (int[] a in adj[node]) { var newDistance = new int[] { dist + a[1], a[0], steps + 1 }; pq.Enqueue(newDistance, newDistance); } } return -1; } }// 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:
700
200
500