Tag Archives: c-sharp

C# || Two Sum IV – How To Get Two Numbers In Binary Search Tree Equal To Target Value Using C#

The following is a module with functions which demonstrates how to get two numbers in a binary search tree equal to target value using C#.


1. Find Target – Problem Statement

Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1:

Example 1


Input: root = [5,3,6,2,4,null,7], k = 9
Output: true

Example 2:

Example 2


Input: root = [5,3,6,2,4,null,7], k = 28
Output: false


2. Find Target – Solution

The following are two solutions which demonstrates how to get two numbers in a binary search tree equal to target value.

Both solutions use a set to keep track of the items already seen.

Each time a new node is encountered, we subtract the target value from the current node value. If the difference amount from subtracting the two numbers exists in the set, a 2 sum combination exists in the tree

1. Recursive

The following solution uses Depth First Search when looking for the target value.

2. Iterative

The following solution uses Breadth First Search when looking for the target value.

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
false

C# || Counting Bits – How To Return The Number Of 1’s In Binary Representation Of X Using C#

The following is a module with functions which demonstrates how to return the number of 1’s in binary representation of X using C#.


1. Count Bits – Problem Statement

Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1‘s in the binary representation of i.

Example 1:


Input: n = 2
Output: [0,1,1]
Explanation:
0 --> 0
1 --> 1
2 --> 10

Example 2:


Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101


2. Count Bits – Solution

The following is a solution which demonstrates how return the number of 1’s in binary representation of X.

In this problem, we can see a pattern start to form.

When the current n is even, we can get the answer by dividing by 2 (e.g result[n] = result[n / 2])

When the current n is odd, we can get the answer by getting the result at previous index and adding 1 (e.g result[n] = result[n – 1] + 1)

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

C# || How To Traverse N-ary Tree Level Order Using C#

The following is a module with functions which demonstrates how to traverse a N-ary Tree level order using C#.


1. Level Order – Problem Statement

Given an n-ary tree, return the level order traversal of its nodes’ values.

Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).

Example 1:

Example 1


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

Example 2:

Example 2


Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
Output: [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]


2. Level Order – Solution

The following is a solution which demonstrates how to traverse a N-ary Tree level order.

This solution uses Breadth First Search to explore items at each level.

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,4],[5,6]]
[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]

C# || How To Validate A Binary Search Tree Using C#

The following is a module with functions which demonstrates how to validate a binary search tree using C#.


1. Is Valid BST – Problem Statement

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

A valid BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • Both the left and right subtrees must also be binary search trees.

Example 1:

Example 1


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

Example 2:

Example 2


Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.


2. Is Valid BST – Solution

The following is a solution which demonstrates how to validate a binary search tree.

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
false

C# || Max Area of Island – How To Find The Maximum Area Of An Island In A Grid Using C#

The following is a module with functions which demonstrates how to find the maximum area of an island in a grid using C#.


1. Max Area Of Island – Problem Statement

You are given an m x n binary matrix grid. An island is a group of 1‘s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

The area of an island is the number of cells with a value 1 in the island.

Return the maximum area of an island in grid. If there is no island, return 0.

Example 1:

Example 1


Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
Output: 6
Explanation: The answer is not 11, because the island must be connected 4-directionally.

Example 2:


Input: grid = [[0,0,0,0,0,0,0,0]]
Output: 0


2. Max Area Of Island – Solution

The following is a solution which demonstrates how to find the maximum area of an island in a grid.

We want to know the area of each connected shape in the grid, then take the maximum of these.

If we are on a land square and explore every square connected to it 4-directionally (and recursively squares connected to those squares, and so on), then the total number of squares explored will be the area of that connected shape.

To ensure we don’t count squares in a shape more than once, we use ‘seen’ to keep track of squares we haven’t visited before. It will also prevent us from counting the same shape more than once.

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
0

C# || Binary Tree Right Side View – How To Get Nodes Ordered Top To Bottom C#

The following is a module with functions which demonstrates how to get nodes in a binary tree ordered from top to bottom using C#.


1. Right Side View – Problem Statement

Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

Example 1:

Example 1


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

Example 2:


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

Example 3:


Input: root = []
Output: []


2. Right Side View – Solution

The following is a solution which demonstrates how to get right side nodes ordered from top to bottom.

This solution uses Depth First Search level order traversal to explore items at each level, and then adds the last node on every layer.

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

C# || How To Find The Shortest Clear Path In A Binary Matrix Using C#

The following is a module with functions which demonstrates how to find the shortest clear path in a binary matrix using C#.


1. Shortest Path Binary Matrix – Problem Statement

Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.

A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n – 1, n – 1)) such that:

  • All the visited cells of the path are 0.
  • All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner).

The length of a clear path is the number of visited cells of this path.

Example 1:


Input: grid = [[0,1],[1,0]]
Output: 2

Example 2:


Input: grid = [[0,0,0],[1,1,0],[1,1,0]]
Output: 4

Example 3:


Input: grid = [[1,0,0],[1,1,0],[1,1,0]]
Output: -1


2. Shortest Path Binary Matrix – Solution

The following is a solution which demonstrates how find the shortest clear path in a binary matrix.

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
4
-1

C# || Palindromic Substrings – How To Find The Number Of Palindromic Substrings Using C#

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


1. Count Substrings – Problem Statement

Given a string s, return the number of palindromic substrings in it.

A string is a palindrome when it reads the same backward as forward.

A substring is a contiguous sequence of characters within the string.

Example 1:


Input: s = "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".

Example 2:


Input: s = "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".


2. Count Substrings – Solution

The following is a solution which demonstrates how to find the number of palindromic substrings.

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
6

C# || Longest Valid Parentheses – How To Find The Longest Valid Well Formed Parentheses Using C#

The following is a module with functions which demonstrates how to find the longest valid well formed parentheses using C#.


1. Longest Valid Parentheses – Problem Statement

Given a string containing just the characters ‘(‘ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.

Example 1:


Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".

Example 2:


Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".

Example 3:


Input: s = ""
Output: 0


2. Longest Valid Parentheses – Solution

The following is a solution which demonstrates how to find the longest valid well formed parentheses.

In this solution we can make use of a stack while scanning the given string to:

  • Check if the string scanned so far is valid
  • Find the length of the longest valid string

In order to do so, we start by pushing -1 onto the stack. For every ‘(‘ encountered, we push its index onto the stack.

For every ‘)‘ encountered, we pop the topmost element. Then, the length of the currently encountered valid string of parentheses will be the difference between the current element’s index and the top element of the stack.

If, while popping the element, the stack becomes empty, we will push the current element’s index onto the stack. In this way, we can continue to calculate the length of the valid substrings and return the length of the longest valid string at the end.

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
4
0

C# || Backspace String Compare – How To Backspace Compare Two Strings Using C#

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


1. Backspace Compare – Problem Statement

Given two strings s and t, return true if they are equal when both are typed into empty text editors. ‘#’ means a backspace character.

Note that after backspacing an empty text, the text will continue empty.

Example 1:


Input: s = "ab#c", t = "ad#c"
Output: true
Explanation: Both s and t become "ac".

Example 2:


Input: s = "ab##", t = "c#d#"
Output: true
Explanation: Both s and t become "".

Example 3:


Input: s = "a#c", t = "b"
Output: false
Explanation: s becomes "c" while t becomes "b".


2. Backspace Compare – Solution

The following is a solution which demonstrates how to backspace compare two strings.

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 Design Underground System To Keep Track Of Customer Travel Times Between Stations Using C#

The following is a module with functions which demonstrates how to design an underground system to keep track of customer travel times between different stations using C#.


1. Underground System – Problem Statement

An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.

Implement the UndergroundSystem class:

  • void checkIn(int id, string stationName, int t)
    • A customer with a card ID equal to id, checks in at the station stationName at time t.
    • A customer can only be checked into one place at a time.
  • void checkOut(int id, string stationName, int t)
    • A customer with a card ID equal to id, checks out from the station stationName at time t.
  • double getAverageTime(string startStation, string endStation)
    • Returns the average time it takes to travel from startStation to endStation.
    • The average time is computed from all the previous traveling times from startStation to endStation that happened directly, meaning a check in at startStation followed by a check out from endStation.
    • The time it takes to travel from startStation to endStation may be different from the time it takes to travel from endStation to startStation.
    • There will be at least one customer that has traveled from startStation to endStation before getAverageTime is called.

You may assume all calls to the checkIn and checkOut methods are consistent. If a customer checks in at time t1 then checks out at time t2, then t1 < t2. All events happen in chronological order.

Example 1:


Input
["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"]
[[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]]

Output
[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]

Explanation
UndergroundSystem undergroundSystem = new UndergroundSystem();
undergroundSystem.checkIn(45, "Leyton", 3);
undergroundSystem.checkIn(32, "Paradise", 8);
undergroundSystem.checkIn(27, "Leyton", 10);
undergroundSystem.checkOut(45, "Waterloo", 15); // Customer 45 "Leyton" -> "Waterloo" in 15-3 = 12
undergroundSystem.checkOut(27, "Waterloo", 20); // Customer 27 "Leyton" -> "Waterloo" in 20-10 = 10
undergroundSystem.checkOut(32, "Cambridge", 22); // Customer 32 "Paradise" -> "Cambridge" in 22-8 = 14
undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. One trip "Paradise" -> "Cambridge", (14) / 1 = 14
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000. Two trips "Leyton" -> "Waterloo", (10 + 12) / 2 = 11
undergroundSystem.checkIn(10, "Leyton", 24);
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 11.00000
undergroundSystem.checkOut(10, "Waterloo", 38); // Customer 10 "Leyton" -> "Waterloo" in 38-24 = 14
undergroundSystem.getAverageTime("Leyton", "Waterloo"); // return 12.00000. Three trips "Leyton" -> "Waterloo", (10 + 12 + 14) / 3 = 12

Example 2:


Input
["UndergroundSystem","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime","checkIn","checkOut","getAverageTime"]
[[],[10,"Leyton",3],[10,"Paradise",8],["Leyton","Paradise"],[5,"Leyton",10],[5,"Paradise",16],["Leyton","Paradise"],[2,"Leyton",21],[2,"Paradise",30],["Leyton","Paradise"]]

Output
[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]

Explanation
UndergroundSystem undergroundSystem = new UndergroundSystem();
undergroundSystem.checkIn(10, "Leyton", 3);
undergroundSystem.checkOut(10, "Paradise", 8); // Customer 10 "Leyton" -> "Paradise" in 8-3 = 5
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000, (5) / 1 = 5
undergroundSystem.checkIn(5, "Leyton", 10);
undergroundSystem.checkOut(5, "Paradise", 16); // Customer 5 "Leyton" -> "Paradise" in 16-10 = 6
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000, (5 + 6) / 2 = 5.5
undergroundSystem.checkIn(2, "Leyton", 21);
undergroundSystem.checkOut(2, "Paradise", 30); // Customer 2 "Leyton" -> "Paradise" in 30-21 = 9
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667


2. Underground System – Solution

The following is a solution which demonstrates how to design an underground system to keep track of customer travel times between different stations.

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,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]
[null,null,null,5.00000,null,null,5.50000,null,null,6.66667]

C# || How To Add Simple Object Change Tracking To Track Changes Using C#

The following is a module with functions which demonstrates how to add simple object change tracking to track changes made to an object using C#.

Contents

1. Overview
2. Basic Usage
3. Accept Changes
4. Reject Changes
5. Ignore Tracking For Property
6. Notify Property Changed
7. Utils Namespace
8. More Examples


1. Overview

The following is a simple abstract change tracker class which implements INotifyPropertyChanged and IRevertibleChangeTracking which provides functionality to track object changes, and to ‘accept’ or ‘revert’ changes.

To use this class, simply inherit the abstract class, and your all set!

Note: Don’t forget to include the ‘Utils Namespace‘ before running the examples!


2. Basic Usage

The example below demonstrates the use of ChangeTracker.BeginChanges to start tracking object changes, as well as ChangeTracker.GetChanges to get the changes made to an object.

The following example demonstrates the basic usage of adding change tracking to an object, and making and getting changes.


3. Accept Changes

The example below demonstrates the use of ChangeTracker.AcceptChanges to accept modification changes made to an object.

This function commits all the changes made to the object since either ChangeTracker.BeginChanges was called, or since ChangeTracker.AcceptChanges was last called.

When the accept function is called, all the changes made to the object up to that point will be marked as the current ‘source of truth’ for change tracking.


4. Reject Changes

The example below demonstrates the use of ChangeTracker.RejectChanges to reject modification changes made to an object.

This function rejects all the changes made to the object since either ChangeTracker.BeginChanges was called, or since ChangeTracker.AcceptChanges was last called.

When the reject function is called, all the changes made to the object up to that point reverts back to the objects state before modifications initially began or modifications was last accepted.


5. Ignore Tracking For Property

The example below demonstrates the use of ChangeTracker.ChangeTrackerIgnore attribute to mark a specific property to be ignored from change tracking.


6. Notify Property Changed

The example below demonstrates the use of ChangeTracker.NotifyPropertyChanged to fire the PropertyChanged event notifying that the specified property value has changed.

In the class declaration, simply add ChangeTracker.NotifyPropertyChanged to the properties you wish to notify changes, and add a PropertyChanged event handler function to receive the notifications.


7. Utils Namespace

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


8. 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# || Remove Linked List Elements – How To Remove All Target Linked List Elements Using C#

The following is a module with functions which demonstrates how to remove all target linked list elements using C#.


1. Remove Elements – Problem Statement

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

Example 1:

Example 1


Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]

Example 2:


Input: head = [], val = 1
Output: []

Example 3:


Input: head = [7,7,7,7], val = 7
Output: []


2. Remove Elements – Solution

The following is a solution which demonstrates how to remove all target linked list elements.

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,4,5]
[]
[]

C# || How To Compare Version Numbers Using C#

The following is a module with functions which demonstrates how to compare version numbers using C#.


1. Compare Version – Problem Statement

Given two version numbers, version1 and version2, compare them.

Version numbers consist of one or more revisions joined by a dot ‘.’. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers.

To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1.

Return the following:

  • If version1 < version2, return -1.
  • If version1 > version2, return 1.
  • Otherwise, return 0.

Example 1:


Input: version1 = "1.01", version2 = "1.001"
Output: 0
Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1".

Example 2:


Input: version1 = "1.0", version2 = "1.0.0"
Output: 0
Explanation: version1 does not specify revision 2, which means it is treated as "0".

Example 3:


Input: version1 = "0.1", version2 = "1.1"
Output: -1
Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2.


2. Compare Version – Solution

The following is a solution which demonstrates how to compare version numbers.

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
0
-1