Tag Archives: c-sharp

C# || How To Construct A Binary Search Tree From Preorder Traversal Using C#

The following is a module with functions which demonstrates how to construct a binary search tree from preorder traversal using C#.


1. Binary Tree From Preorder – Problem Statement

Given an array of integers preorder, which represents the preorder traversal of a BST (i.e., binary search tree), construct the tree and return its root.

It is guaranteed that there is always possible to find a binary search tree with the given requirements for the given test cases.

A binary search tree is a binary tree where for every node, any descendant of Node.left has a value strictly less than Node.val, and any descendant of Node.right has a value strictly greater than Node.val.

A preorder traversal of a binary tree displays the value of the node first, then traverses Node.left, then traverses Node.right.

Example 1:

Example 1


Input: preorder = [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]

Example 2:


Input: preorder = [1,3]
Output: [1,null,3]


2. Binary Tree From Preorder – Solution

The following is a solution which demonstrates how to construct a binary search tree from preorder traversal.

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,5,10,1,7,null,12]
[1,null,3]

C# || How To Find The Next Greater Element In A Circular Array Using C#

The following is a module with functions which demonstrates how to find the next greater element in a circular array using C#.


1. Circular Next Greater – Problem Statement

Given a circular integer array nums (i.e., the next element of nums[nums.length – 1] is nums[0]), return the next greater number for every element in nums.

The next greater number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn’t exist, return -1 for this number.

Example 1:


Input: nums = [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number.
The second 1's next greater number needs to search circularly, which is also 2.

Example 2:


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


2. Circular Next Greater – Solution

The following is a solution which demonstrates how to find the next greater element in a circular array.

This solution uses the monotonic stack approach. This solution finds the next greater element for each array value, in the first pass, and then uses a second pass to process any remaining values since the array is circular.

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,2]
[2,3,4,-1,4]

C# || How To Find The Next Greater Element In An Array Using C#

The following is a module with functions which demonstrates how to find the next greater element in an array using C#.


1. Next Greater – Problem Statement

The next greater element of some element x in an array is the first greater element that is to the right of x in the same array.

You are given two distinct 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2.

For each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next greater element of nums2[j] in nums2. If there is no next greater element, then the answer for this query is -1.

Return an array ans of length nums1.length such that ans[i] is the next greater element as described above.

Example 1:


Input: nums1 = [4,1,2], nums2 = [1,3,4,2]
Output: [-1,3,-1]
Explanation: The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1.

Example 2:


Input: nums1 = [2,4], nums2 = [1,2,3,4]
Output: [3,-1]
Explanation: The next greater element for each value of nums1 is as follows:
- 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3.
- 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1.


2. Next Greater – Solution

The following is a solution which demonstrates how to find the next greater element in an array.

This solution uses the monotonic stack approach. This solution finds the next greater element for each array value in the second array, and uses that to find the next greater element for each matching value in the first array.

To determine the next greatest element, a stack is used to keep track of the items we’ve already seen. The array index of the item is saved to the stack.

For each loop iteration, the item at the top of the stack is checked to see if it is less than the current array item being checked. If the item at the top of the stack is less than the current array item, then the current array item is saved to the result index that matches the value from the top of the stack.

Once the next greatest elements have been found from nums2, that information is used to populate the final result from the matching values found in nums1

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]
[3,-1]

C# || How To Multiply Two Strings Using C#

The following is a module with functions which demonstrates how to multiply two strings together using C#.


1. Multiply Strings – Problem Statement

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

Example 1:


Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:


Input: num1 = "123", num2 = "456"
Output: "56088"


2. Multiply Strings – Solution

The following is a solution which demonstrates how to multiply two strings together.

This solution starts from the end of both strings and multiplies each individual number, keeping track of any carryovers. The result of each operation is stored in a ‘solution’ array, and when the operation is complete, the result is returned as a string.

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:


"6"
"56088"

C# || How To Add Two Binary Strings Using C#

The following is a module with functions which demonstrates how to add two binary strings together using C#.


1. Add Binary – Problem Statement

Given two binary strings a and b, return their sum as a binary string.

Example 1:


Input: a = "11", b = "1"
Output: "100"

Example 2:


Input: a = "1010", b = "1011"
Output: "10101"


2. Add Binary – Solution

The following is a solution which demonstrates how to add two binary strings together.

In this solution, we start at the end of both strings, and perform basic math on each number, adding them together. If any mathematical carry over is required, that is added to the next loop iteration.

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:


"100"
"10101"

C# || How To Traverse A Binary Tree Postorder Using C#

The following is a module with functions which demonstrates how to traverse a binary tree post order using C#.


1. Binary Tree Traversal – Problem Statement

Given the root of a binary tree, return the postorder traversal of its nodes’ values.

Example 1:

Example 1


Input: root = [1,null,2,3]
Output: [3,2,1]

Example 2:


Input: root = []
Output: []

Example 3:


Input: root = [1]
Output: [1]

Example 4:

Example 4


Input: root = [1,2]
Output: [2,1]

Example 5:

Example 5


Input: root = [1,null,2]
Output: [2,1]


2. Binary Tree Traversal – Solution

The following is a solution which demonstrates how to traverse a binary tree post order.

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,2,1]
[]
[1]
[2,1]
[2,1]

C# || How To Traverse A Binary Tree Preorder Using C#

The following is a module with functions which demonstrates how to traverse a binary tree pre order using C#.


1. Binary Tree Traversal – Problem Statement

Given the root of a binary tree, return the preorder traversal of its nodes’ values.

Example 1:

Example 1


Input: root = [1,null,2,3]
Output: [1,2,3]

Example 2:


Input: root = []
Output: []

Example 3:


Input: root = [1]
Output: [1]

Example 4:

Example 4


Input: root = [1,2]
Output: [1,2]

Example 5:

Example 5


Input: root = [1,null,2]
Output: [1,2]


2. Binary Tree Traversal – Solution

The following is a solution which demonstrates how to traverse a binary tree pre order.

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]
[]
[1]
[1,2]
[1,2]

C# || How To Traverse A Binary Tree Inorder Using C#

The following is a module with functions which demonstrates how to traverse a binary tree in order using C#.


1. Binary Tree Traversal – Problem Statement

Given the root of a binary tree, return the inorder traversal of its nodes’ values.

Example 1:

Example 1


Input: root = [1,null,2,3]
Output: [1,3,2]

Example 2:


Input: root = []
Output: []

Example 3:


Input: root = [1]
Output: [1]

Example 4:

Example 4


Input: root = [1,2]
Output: [2,1]

Example 5:

Example 5


Input: root = [1,null,2]
Output: [1,2]


2. Binary Tree Traversal – Solution

The following is a solution which demonstrates how to traverse a binary tree in order.

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,2]
[]
[1]
[2,1]
[1,2]

C# || How To Determine The Maximum Units On A Truck Using C#

The following is a module with functions which demonstrates how to determine the maximum units on a truck using C#.


1. Maximum Units – Problem Statement

You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxes, numberOfUnitsPerBox]:


numberOfBoxes is the number of boxes of type i.
numberOfUnitsPerBox is the number of units in each box of the type i

You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.

Return the maximum total number of units that can be put on the truck.

Example 1:


Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
Output: 8
Explanation: There are:
- 1 box of the first type that contains 3 units.
- 2 boxes of the second type that contain 2 units each.
- 3 boxes of the third type that contain 1 unit each.
You can take all the boxes of the first and second types, and one box of the third type.
The total number of units will be = (1 * 3) + (2 * 2) + (1 * 1) = 8.

Example 2:


Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
Output: 91


2. Maximum Units – Solution

The following is a solution which demonstrates how to determine the maximum units on a truck.

In this solution, we start with the box with the most units. The box types are sorted by the number of units per box in descending order. Then, the box types are iterated over, taking from each type as many as possible.

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
91

C# || Word Search – How To Search A Grid Matrix For A Target Word Using C#

The following is a module with functions which demonstrates how to search a grid matrix for a target word using C#.


1. Word Search – Problem Statement

Given an m x n grid of characters board and a string word, return true if word exists in the grid.

The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example 1:

Example 1


Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
Output: true

Example 2:

Example 2


Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
Output: true

Example 3:

Example 3


Input: board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
Output: false


2. Word Search – Solution

The following is a solution which demonstrates how to search a grid matrix for a target word. This solution uses Depth First Search.

Depth First Search (DFS) is an algorithm for searching tree or graph data structures. It starts at the root node and explores as far as possible along each branch before backtracking.

In this problem we start at the root node and search all the possibilities at each array index until a match is found. We create a ‘visited’ array to keep track of the indexes already seen.

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:


true
true
false

C# || How To Find All Combinations Of Well-Formed Brackets Using C#

The following is a program with functions which demonstrates how to find all combinations of well-formed brackets using C#.

The task is to write a function Brackets(int n) that prints all combinations of well-formed brackets from 1…n. For example, Brackets(3), the output would be:

()
(()) ()()
((())) (()()) (())() ()(()) ()()()

The number of possible combinations is the Catalan number of N pairs C(n).


1. Find All Well-Formed Brackets

The example below demonstrates the use of the ‘Brackets‘ function to find all the well-formed bracket combinations.

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


Pair: 1, Combination: ()
Pair: 2, Combination: (()), ()()
Pair: 3, Combination: ((())), (()()), (())(), ()(()), ()()()
Pair: 4, Combination: (((()))), ((()())), ((())()), ((()))(), (()(())), (()()()), (()())(), (())(()), (())()(), ()((())), ()(()()), ()(())(), ()()(()), ()()()()

C# || How To Pad Center & Center Align A String Of Fixed Length Using C#

The following is a module with functions which demonstrates how to pad center and center align a string of a fixed length using C#.

The function demonstrated on this page center aligns the characters in a string by padding them on the left and right with a specified character, of a specified total length.

The returned string is padded with as many padding characters needed to reach a length of the specified total width.

The padding character is user defined, but if no padding character is specified, the string is padded using a whitespace (‘ ‘).


1. Pad Center

The example below demonstrates the use of ‘Utils.Extensions.PadCenter‘ to center align a string of a fixed length.

In this example, the default padding character is used to pad the string, which is a whitespace (‘ ‘).


2. Utils Namespace

The following is the Utils Namespace. Include this in your project to start using!


3. More Examples

Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!

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.

C# || How To Get The Date Value & Time Value From A Date Using C#

The following is a module with functions which demonstrates how to get the date value and time value from a DateTime using C#.

The functions listed on this page demonstrates how to isolate the date portion of a date, as well as the time portion of a date. For example, given the date “5/23/2019 7:28:31 PM”, the date value would be 5/23/2019, and time value 7:28:31 PM.


1. Date Value

The example below demonstrates the use of ‘Utils.Methods.DateValue‘ to get the date value of a date.

The DateTime object value contains the date information, with the time portion set to midnight (00:00:00)


2. Time Value

The example below demonstrates the use of ‘Utils.Methods.TimeValue‘ to get the date value of a date.

The DateTime object contains the time information, with the date portion set to January 1 of the year 1


3. Utils Namespace

The following is the Utils Namespace. Include this in your project to start using!


4. More Examples

Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!

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.

C# || How To Create Multiple Tasks With Maximum Concurrency Using C#

The following is a module with functions which demonstrates how to create multiple tasks with maximum concurrency using C#.

The examples demonstrated on this page uses System.Threading.Tasks.Task to start and run tasks. They also use System.Threading.SemaphoreSlim to limit the number of tasks that can run concurrently.

The examples on this page demonstrates how to start and run multiple tasks with a maximum concurrency. It also demonstrates how to start and run multiple tasks with a return value.


1. Task – Maximum Concurrency

The example below demonstrates how to start and run multiple tasks with a maximum concurrency. For example purposes, the tasks do not return a value.

The functions shown in the example below are called asynchronously, but they can also be called synchronously.


2. Task – Maximum Concurrency – Return Value

The example below demonstrates how to start and run multiple tasks with a maximum concurrency. In this example, a value is returned and retrieved from the tasks

The functions shown in the example below are called asynchronously, but they can also be called synchronously.


3. More Examples

Below is a full example of the process demonstrated on this page!

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.