Monthly Archives: May 2022
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.
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 24, 2022 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to find the longest valid parentheses // ============================================================================ public class Solution { public int LongestValidParentheses(string s) { var result = 0; var stack = new Stack<int>(); stack.Push(-1); for (var index = 0; index < s.Length; ++index) { if (s[index] == '(') { stack.Push(index); } else { stack.Pop(); if (stack.Count == 0) { stack.Push(index); } else { result = Math.Max(result, index - stack.Peek()); } } } return result; } }// 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
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.
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: May 23, 2022 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to backspace compare two strings // ============================================================================ public class Solution { public bool BackspaceCompare(string s, string t) { return Clean(s) == Clean(t); } public string Clean(string source) { // Create result buffer var buffer = new StringBuilder(); foreach (var ch in source) { if (ch == '#') { // Backspace by removing the last character in the buffer if (buffer.Length > 0) { buffer.Length -= 1; } } else { // Add the character to the buffer buffer.Append(ch); } } return buffer.ToString(); } }// 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:
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.
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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 1, 2022 // Taken From: http://programmingnotes.org/ // File: Solution.cs // Description: Demonstrates how to design underground system // ============================================================================ public class UndergroundSystem { Dictionary<string, KeyValuePair<int, int>> checkoutMap; Dictionary<int, KeyValuePair<string, int>> checkInMap; public UndergroundSystem() { checkoutMap = new Dictionary<string, KeyValuePair<int, int>>(); // Route - {TotalTime, Count} checkInMap = new Dictionary<int, KeyValuePair<string, int>>(); // Uid - {StationName, Time} } public void CheckIn(int id, string stationName, int t) { checkInMap[id] = new KeyValuePair<string, int>(stationName, t); } public void CheckOut(int id, string stationName, int t) { var checkIn = checkInMap[id]; var route = checkIn.Key + "_" + stationName; var totalTime = t - checkIn.Value; var checkout = checkoutMap.ContainsKey(route) ? checkoutMap[route] : new KeyValuePair<int, int>(0, 0); checkoutMap[route] = new KeyValuePair<int, int>(checkout.Key + totalTime, checkout.Value + 1); } public double GetAverageTime(string startStation, string endStation) { var route = startStation + "_" + endStation; var checkout = checkoutMap[route]; return (double) checkout.Key / checkout.Value; } }// http://programmingnotes.org/ /** * Your UndergroundSystem object will be instantiated and called as such: * UndergroundSystem obj = new UndergroundSystem(); * obj.CheckIn(id,stationName,t); * obj.CheckOut(id,stationName,t); * double param_3 = obj.GetAverageTime(startStation,endStation); */ |
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]