├── .gitattributes ├── .gitignore ├── LICENSE ├── LeetCode.sln ├── LeetCode ├── App.config ├── Easy.cs ├── Extra.cs ├── Hard.cs ├── JavaScript │ └── Easy.js ├── LeetCode.csproj ├── Medium.cs ├── Pandas │ └── Easy.py ├── Program.cs ├── Properties │ └── AssemblyInfo.cs └── SQL │ └── Easy.sql └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Kyler Condran 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LeetCode.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.6.33829.357 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LeetCode", "LeetCode\LeetCode.csproj", "{DFD4F070-0A1B-4390-9DA2-45968000A055}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {DFD4F070-0A1B-4390-9DA2-45968000A055}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {DFD4F070-0A1B-4390-9DA2-45968000A055}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {DFD4F070-0A1B-4390-9DA2-45968000A055}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {DFD4F070-0A1B-4390-9DA2-45968000A055}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {32BF7894-53BB-4A77-881F-47956400B80E} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /LeetCode/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /LeetCode/Extra.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Numerics; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace LeetCode 9 | { 10 | public class ReverseSortComparer : IComparer 11 | { 12 | public int Compare(int x, int y) 13 | { 14 | return y.CompareTo(x); 15 | } 16 | } 17 | public class ReverseSortLongComparer : IComparer 18 | { 19 | public int Compare(long x, long y) 20 | { 21 | return y.CompareTo(x); 22 | } 23 | } 24 | public class ListNode 25 | { 26 | public int val; 27 | public ListNode next; 28 | public ListNode(int val = 0, ListNode next = null) 29 | { 30 | this.val = val; 31 | this.next = next; 32 | } 33 | } 34 | public class TreeNode 35 | { 36 | public int val; 37 | public TreeNode left; 38 | public TreeNode right; 39 | public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null) 40 | { 41 | this.val = val; 42 | this.left = left; 43 | this.right = right; 44 | } 45 | } 46 | public class PreSortItem 47 | { 48 | public BigInteger Key { get; set; } 49 | public int Index { get; set; } 50 | } 51 | public class BookRange 52 | { 53 | public int start { get; set; } 54 | public int end { get; set; } 55 | } 56 | } -------------------------------------------------------------------------------- /LeetCode/Hard.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Security.Policy; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace LeetCode 10 | { 11 | #region "Hard Methods" 12 | public class Hard 13 | { 14 | 15 | //Title: 4. Median of Two Sorted Arrays 16 | //Link: https://leetcode.com/problems/median-of-two-sorted-arrays 17 | //Tags: Array, Binary Search, Divide and Conquer 18 | public static double FindMedianSortedArrays(int[] nums1, int[] nums2) 19 | { 20 | 21 | int[] merged = nums1.Concat(nums2).ToArray(); 22 | Array.Sort(merged); 23 | int size = merged.Length; 24 | if (size == 1) { return merged[0]; } 25 | if (size % 2 == 0) 26 | { 27 | int mid1 = merged[(size / 2) - 1]; 28 | int mid2 = merged[((size / 2))]; 29 | return (double)(mid1 + mid2) / 2; 30 | } 31 | else 32 | { 33 | int median = ((size + 1) / 2) - 1; 34 | return merged[median]; 35 | } 36 | } 37 | //Title: 1944. Number of Visible People in a Queue 38 | //Link: https://leetcode.com/problems/number-of-visible-people-in-a-queue 39 | //Tags: Array, Stack, Monotonic Stack 40 | public static int[] CanSeePersonsCount(int[] heights) 41 | { 42 | int[] a = new int[heights.Length]; 43 | int cansee = 0; 44 | for (int i = 0; i < heights.Length; i++) 45 | { 46 | a[i] = 0; 47 | int tallestsofar = 0; 48 | for (int j = i + 1; j < heights.Length; j++) 49 | { 50 | if (heights[i] > heights[j]) 51 | { 52 | if (tallestsofar < heights[j]) 53 | { 54 | tallestsofar = heights[j]; 55 | cansee++; 56 | } 57 | } 58 | else 59 | { 60 | cansee++; 61 | break; 62 | } 63 | } 64 | a[i] = cansee; 65 | cansee = 0; 66 | } 67 | return a; 68 | } 69 | //Title: 41. First Missing Positive 70 | //Link: https://leetcode.com/problems/first-missing-positive 71 | //Tags: Array, Hash Table 72 | public static int FirstMissingPositive(int[] nums) 73 | { 74 | int counter = 1; 75 | Array.Sort(nums); 76 | for (int i = 0; i < nums.Length; i++) 77 | { 78 | if (nums[i] > 0 && nums[i] >= counter) 79 | { 80 | if (nums[i] != counter) 81 | { 82 | return counter; 83 | } 84 | counter++; 85 | } 86 | } 87 | if (nums.Max() < 0) 88 | { 89 | return 1; 90 | } 91 | return nums.Max() + 1; 92 | } 93 | //Title: 239. Sliding Window Maximum 94 | //Link: https://leetcode.com/problems/sliding-window-maximum 95 | //Tags: Array, Queue, Sliding Window, Heap (Priority Queue), Monotonic Queue 96 | //====================================================================================================================== 97 | //I wrote and used this custom class to change the default sort behavior of the SortedDictionary from ascending to descending. 98 | //This sorts the keys in descending order which allows SortedDictionary.Keys.First() to be called rather than 99 | //SortedDictionary.Keys.Last() which is much slower with larger datasets, likely due to iterating from the top to the bottom. 100 | //This allowed me to pass the time limit exceeded restriction and optimized the runtime complexity of my algorithm. 101 | //====================================================================================================================== 102 | //public class ReverseSortComparer : IComparer 103 | //{ 104 | // public int Compare(int x, int y) 105 | // { 106 | // return y.CompareTo(x); 107 | // } 108 | //} 109 | //====================================================================================================================== 110 | static int[] MaxSlidingWindow(int[] nums, int k) 111 | { 112 | SortedDictionary a = new SortedDictionary(new ReverseSortComparer()); 113 | Queue q = new Queue(); 114 | int final = nums.Length - k + 1; 115 | int[] ans = new int[final]; 116 | int index = 0; 117 | for (int i = 0; i < k; i++) 118 | { 119 | q.Enqueue(nums[i]); 120 | if (!a.ContainsKey(nums[i])) 121 | { 122 | a.Add(nums[i], 1); 123 | } 124 | else 125 | { 126 | a[nums[i]]++; 127 | } 128 | } 129 | ans[index] = a.Keys.First(); 130 | index++; 131 | for (int i = k; i < nums.Length; i++) 132 | { 133 | int peek = q.Peek(); 134 | if (a[peek] == 1) 135 | { 136 | a.Remove(peek); 137 | } 138 | else 139 | { 140 | a[peek]--; 141 | } 142 | q.Dequeue(); 143 | q.Enqueue(nums[i]); 144 | if (!a.ContainsKey(nums[i])) 145 | { 146 | a.Add(nums[i], 1); 147 | } 148 | else 149 | { 150 | a[nums[i]]++; 151 | } 152 | ans[index] = a.Keys.First(); 153 | index++; 154 | } 155 | return ans; 156 | } 157 | //Title: 273. Integer to English Words 158 | //Link: https://leetcode.com/problems/integer-to-english-words 159 | //Tags: Math, String, Recursion 160 | public static string NumberToWords(int num) 161 | { 162 | int start = num; 163 | string startstring = start.ToString(); 164 | char[] c = startstring.ToCharArray(); 165 | Array.Reverse(c); 166 | string backwards = new string(c); 167 | string final = ""; 168 | Dictionary a = new Dictionary(); 169 | a.Add(0, "Zero"); 170 | a.Add(1, "One"); 171 | a.Add(2, "Two"); 172 | a.Add(3, "Three"); 173 | a.Add(4, "Four"); 174 | a.Add(5, "Five"); 175 | a.Add(6, "Six"); 176 | a.Add(7, "Seven"); 177 | a.Add(8, "Eight"); 178 | a.Add(9, "Nine"); 179 | a.Add(10, "Ten"); 180 | a.Add(11, "Eleven"); 181 | a.Add(12, "Twelve"); 182 | a.Add(13, "Thirteen"); 183 | a.Add(14, "Fourteen"); 184 | a.Add(15, "Fifteen"); 185 | a.Add(16, "Sixteen"); 186 | a.Add(17, "Seventeen"); 187 | a.Add(18, "Eighteen"); 188 | a.Add(19, "Nineteen"); 189 | a.Add(20, "Twenty"); 190 | a.Add(30, "Thirty"); 191 | a.Add(40, "Forty"); 192 | a.Add(50, "Fifty"); 193 | a.Add(60, "Sixty"); 194 | a.Add(70, "Seventy"); 195 | a.Add(80, "Eighty"); 196 | a.Add(90, "Ninety"); 197 | a.Add(100, "Hundred"); 198 | a.Add(1000, "Thousand"); 199 | a.Add(1000000, "Million"); 200 | a.Add(1000000000, "Billion"); 201 | if (num == 0) 202 | { 203 | return a[0]; 204 | } 205 | //billion 206 | if (num > 999999999) 207 | { 208 | int billion = 0; 209 | while (num > 999999999) 210 | { 211 | billion++; 212 | num = num - 1000000000; 213 | } 214 | final += a[billion] + " " + a[1000000000] + " "; 215 | } 216 | //hundred million 217 | if (num > 99999999) 218 | { 219 | int hundred = 0; 220 | while (num > 99999999) 221 | { 222 | hundred++; 223 | num = num - 100000000; 224 | } 225 | final += a[hundred] + " " + a[100] + " "; 226 | } 227 | //ten million 228 | if (num > 19999999) 229 | { 230 | int tens = 0; 231 | while (num > 9999999) 232 | { 233 | tens++; 234 | num = num - 10000000; 235 | } 236 | final += a[tens * 10] + " "; 237 | } 238 | //one million 239 | if (num > 999999) 240 | { 241 | int million = 0; 242 | while (num > 999999) 243 | { 244 | million++; 245 | num = num - 1000000; 246 | } 247 | final += a[million] + " " + a[1000000] + " "; 248 | } 249 | if (!final.Contains("Million") && start > 999999) 250 | { 251 | int counter = 0; 252 | for (int i = 6; i < backwards.Length; i++) 253 | { 254 | if (counter >= 3) 255 | { 256 | break; 257 | } 258 | if (backwards[i] != '0') 259 | { 260 | final = final + a[1000000] + " "; 261 | break; 262 | } 263 | counter++; 264 | } 265 | } 266 | //hundred thousand 267 | if (num > 99999) 268 | { 269 | int hundred = 0; 270 | while (num > 99999) 271 | { 272 | hundred++; 273 | num = num - 100000; 274 | } 275 | final += a[hundred] + " " + a[100] + " "; 276 | } 277 | //ten thousand 278 | if (num > 19999) 279 | { 280 | int tens = 0; 281 | while (num > 9999) 282 | { 283 | tens++; 284 | num = num - 10000; 285 | } 286 | final += a[tens * 10] + " "; 287 | } 288 | //one thousand 289 | if (num > 999) 290 | { 291 | int thousand = 0; 292 | while (num > 999) 293 | { 294 | thousand++; 295 | num = num - 1000; 296 | } 297 | final += a[thousand] + " " + a[1000] + " "; 298 | } 299 | if (!final.Contains("Thousand") && start > 999) 300 | { 301 | int counter = 0; 302 | for (int i = 3; i < backwards.Length; i++) 303 | { 304 | if (counter >= 3) 305 | { 306 | break; 307 | } 308 | if (backwards[i] != '0') 309 | { 310 | final = final + a[1000] + " "; 311 | break; 312 | } 313 | counter++; 314 | } 315 | } 316 | //hundred 317 | if (num > 99) 318 | { 319 | int hundred = 0; 320 | while (num > 99) 321 | { 322 | hundred++; 323 | num = num - 100; 324 | } 325 | final += a[hundred] + " " + a[100] + " "; 326 | } 327 | //tens 328 | if (num > 19) 329 | { 330 | int tens = 0; 331 | while (num > 9) 332 | { 333 | tens++; 334 | num = num - 10; 335 | } 336 | final += a[tens * 10] + " "; 337 | } 338 | //ones 339 | if (num > 0) 340 | { 341 | int ones = 0; 342 | while (num > 0) 343 | { 344 | ones++; 345 | num = num - 1; 346 | } 347 | final += a[ones]; 348 | } 349 | final = final.TrimEnd(); 350 | return final; 351 | } 352 | //Title: 23. Merge k Sorted Lists 353 | //Link: https://leetcode.com/problems/merge-k-sorted-lists 354 | //Tags: Linked List, Divide and Conquer, Heap (Priority Queue), Merge Sort 355 | public static ListNode MergeKLists(ListNode[] lists) 356 | { 357 | SortedDictionary a = new SortedDictionary(); 358 | ListNode head = null; 359 | foreach (var list in lists) 360 | { 361 | ListNode mylist = list; 362 | while (mylist != null) 363 | { 364 | int listval = mylist.val; 365 | if (!a.ContainsKey(listval)) 366 | { 367 | a.Add(listval, 1); 368 | } 369 | else 370 | { 371 | a[listval]++; 372 | } 373 | mylist = mylist.next; 374 | } 375 | } 376 | foreach (KeyValuePair b in a) 377 | { 378 | for (int i = 0; i < b.Value; i++) 379 | { 380 | AddLink(ref head, b.Key); 381 | } 382 | } 383 | return head; 384 | } 385 | public static void AddLink(ref ListNode headref, int linkval) 386 | { 387 | ListNode link = new ListNode(linkval); 388 | if (headref == null) 389 | { 390 | headref = link; 391 | } 392 | else 393 | { 394 | ListNode current = headref; 395 | while (current.next != null) 396 | { 397 | current = current.next; 398 | } 399 | current.next = link; 400 | } 401 | } 402 | //Title: 154. Find Minimum in Rotated Sorted Array II 403 | //Link: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii 404 | //Tags: Array, Binary Search 405 | public static int FindMin(int[] nums) 406 | { 407 | return nums.Min(); 408 | } 409 | //Title: 25. Reverse Nodes in k-Group 410 | //Link: https://leetcode.com/problems/reverse-nodes-in-k-group 411 | //Tags: Linked List, Recursion 412 | public static ListNode ReverseKGroup(ListNode head, int k) 413 | { 414 | Queue q1 = new Queue(); 415 | Queue q2 = new Queue(); 416 | ListNode ans = null; 417 | while (head != null) 418 | { 419 | q1.Enqueue(head.val); 420 | head = head.next; 421 | } 422 | while (q1.Count > 0) 423 | { 424 | if (q1.Count >= k) 425 | { 426 | List b = new List(); 427 | for (int i = 0; i < k; i++) 428 | { 429 | b.Add(q1.Dequeue()); 430 | } 431 | b.Reverse(); 432 | foreach (int i in b) 433 | { 434 | q2.Enqueue(i); 435 | } 436 | } 437 | else 438 | { 439 | q2.Enqueue(q1.Dequeue()); 440 | } 441 | } 442 | ListNode current = ans; 443 | while (q2.Count > 0) 444 | { 445 | ListNode link = new ListNode(q2.Dequeue()); 446 | if (ans == null) 447 | { 448 | ans = link; 449 | current = ans; 450 | } 451 | else 452 | { 453 | current.next = link; 454 | current = current.next; 455 | } 456 | } 457 | return ans; 458 | } 459 | //Title: 480. Sliding Window Median 460 | //Link: https://leetcode.com/problems/sliding-window-median 461 | //Tags: Array, Hash Table, Sliding Window, Heap (Priority Queue) 462 | public static double[] MedianSlidingWindow(int[] nums, int k) 463 | { 464 | double[] ans = new double[nums.Length + 1 - k]; 465 | List x = new List(); 466 | Queue q = new Queue(); 467 | bool even = false; 468 | int index = 0; 469 | int mid1 = 0; 470 | int mid2 = 0; 471 | if (k % 2 == 0) 472 | { 473 | even = true; 474 | mid1 = (k / 2) - 1; 475 | mid2 = k / 2; 476 | } 477 | else mid1 = ((k + 1) / 2) - 1; 478 | for (int i = 0; i < k; i++) 479 | { 480 | int val = nums[i]; 481 | q.Enqueue(val); 482 | InsertIntoSortedList(x, val, (a, b) => a.CompareTo(b)); 483 | } 484 | if (even) ans[index] = (double)((long)x[mid1] + (long)x[mid2]) / 2; 485 | else ans[index] = (double)x[mid1]; 486 | index++; 487 | for (int i = k; i < nums.Length; i++) 488 | { 489 | int val = nums[i]; 490 | x.Remove(q.Dequeue()); 491 | q.Enqueue(val); 492 | InsertIntoSortedList(x, val, (a, b) => a.CompareTo(b)); 493 | if (even) ans[index] = (double)((long)x[mid1] + (long)x[mid2]) / 2; 494 | else ans[index] = (double)x[mid1]; 495 | index++; 496 | } 497 | return ans; 498 | } 499 | public static void InsertIntoSortedList(IList list, IComparable value, Comparison comparison) 500 | { 501 | var startIndex = 0; 502 | var endIndex = list.Count; 503 | while (endIndex > startIndex) 504 | { 505 | var windowSize = endIndex - startIndex; 506 | var middleIndex = startIndex + (windowSize / 2); 507 | var middleValue = (IComparable)list[middleIndex]; 508 | var compareToResult = comparison(middleValue, value); 509 | if (compareToResult == 0) 510 | { 511 | list.Insert(middleIndex, value); 512 | return; 513 | } 514 | else if (compareToResult < 0) startIndex = middleIndex + 1; 515 | else endIndex = middleIndex; 516 | } 517 | list.Insert(startIndex, value); 518 | } 519 | //Title: 315. Count of Smaller Numbers After Self 520 | //Link: https://leetcode.com/problems/count-of-smaller-numbers-after-self 521 | //Tags: Array, Binary Search, Divide and Conquer, Binary Indexed Tree, Segment Tree, Merge Sort, Ordered Set 522 | public static IList CountSmaller(int[] nums) 523 | { 524 | int[] ans = new int[nums.Length]; 525 | List x = new List(); 526 | int index = nums.Length - 1; 527 | for (int i = nums.Length - 1; i >= 0; i--) 528 | { 529 | ans[index] = InsertIntoSortedDupeList(x, nums[i], (a, b) => a.CompareTo(b)); 530 | index--; 531 | } 532 | return ans.ToList(); 533 | } 534 | public static int InsertIntoSortedDupeList(IList list, IComparable value, Comparison comparison) 535 | { 536 | if (list.Contains(value)) 537 | { 538 | int val = list.IndexOf(value); 539 | list.Insert(val, value); 540 | return val; 541 | } 542 | else 543 | { 544 | var startIndex = 0; 545 | var endIndex = list.Count; 546 | while (endIndex > startIndex) 547 | { 548 | var windowSize = endIndex - startIndex; 549 | var middleIndex = startIndex + (windowSize / 2); 550 | var middleValue = (IComparable)list[middleIndex]; 551 | var compareToResult = comparison(middleValue, value); 552 | if (compareToResult == 0) 553 | { 554 | list.Insert(middleIndex, value); 555 | return middleIndex; 556 | } 557 | else if (compareToResult < 0) startIndex = middleIndex + 1; 558 | else endIndex = middleIndex; 559 | } 560 | list.Insert(startIndex, value); 561 | return startIndex; 562 | } 563 | } 564 | //Title: 2444. Count Subarrays With Fixed Bounds 565 | //Link: https://leetcode.com/problems/count-subarrays-with-fixed-bounds 566 | //Tags: Array, Queue, Sliding Window, Monotonic Queue 567 | public static long CountSubarrays(int[] nums, int minK, int maxK) 568 | { 569 | int a = -1; int b = -1; int c = -1; 570 | long counter = 0; 571 | for (int i = 0; i < nums.Length; i++) 572 | { 573 | int val = nums[i]; 574 | if (val < minK || val > maxK) c = i; 575 | if (val == minK) a = i; 576 | if (val == maxK) b = i; 577 | counter += Math.Max(0, Math.Min(a, b) - c); 578 | } 579 | return counter; 580 | } 581 | } 582 | #endregion 583 | #region "Hard Classes" 584 | //Title: 895. Maximum Frequency Stack 585 | //Link: https://leetcode.com/problems/maximum-frequency-stack 586 | //Tags: Hash Table, Stack, Design, Ordered Set 587 | public class FreqStack 588 | { 589 | Dictionary a; 590 | List b; 591 | SortedDictionary> c; 592 | public FreqStack() 593 | { 594 | this.a = new Dictionary(); 595 | this.b = new List(); 596 | this.c = new SortedDictionary>(new ReverseSortComparer()); 597 | } 598 | public void Push(int val) 599 | { 600 | if (!a.ContainsKey(val)) 601 | { 602 | a.Add(val, 1); 603 | if (!c.ContainsKey(1)) 604 | { 605 | c.Add(1, new List { val }); 606 | } 607 | else 608 | { 609 | c[1].Add(val); 610 | } 611 | } 612 | else 613 | { 614 | c[a[val]].Remove(val); 615 | if (c[a[val]].Count == 0) 616 | { 617 | c.Remove(a[val]); 618 | } 619 | a[val]++; 620 | if (!c.ContainsKey(a[val])) 621 | { 622 | c.Add(a[val], new List { val }); 623 | } 624 | else 625 | { 626 | c[a[val]].Add(val); 627 | } 628 | } 629 | b.Add(val); 630 | } 631 | public int Pop() 632 | { 633 | int min = Int32.MinValue; 634 | int integer = -1; 635 | if (c.ElementAt(0).Value.Count == 1) 636 | { 637 | int num = c.ElementAt(0).Value[0]; 638 | int index = b.LastIndexOf(num); 639 | if (index != -1 && index > min) 640 | { 641 | min = index; 642 | integer = num; 643 | } 644 | } 645 | else if (c.ElementAt(0).Value.Count > 1) 646 | { 647 | int[] d = new int[2]; 648 | d = GetIndex(b, c.ElementAt(0).Value); 649 | if (d[0] != -1) 650 | { 651 | min = d[0]; 652 | integer = d[1]; 653 | } 654 | } 655 | c[a[integer]].Remove(integer); 656 | if (c[a[integer]].Count == 0) 657 | { 658 | c.Remove(a[integer]); 659 | } 660 | a[integer]--; 661 | if (!c.ContainsKey(a[integer])) 662 | { 663 | c.Add(a[integer], new List { integer }); 664 | } 665 | else 666 | { 667 | if (a[integer] != 0) 668 | { 669 | c[a[integer]].Add(integer); 670 | } 671 | } 672 | if (a[integer] == 0) 673 | { 674 | a.Remove(integer); 675 | } 676 | b.RemoveAt(min); 677 | return integer; 678 | } 679 | public int[] GetIndex(List list, List topfreq) 680 | { 681 | int[] ans = new int[2]; 682 | ans[0] = -1; 683 | ans[1] = -1; 684 | for (int index = list.Count - 1; index >= 0; index--) 685 | { 686 | if (topfreq.Contains(list[index])) 687 | { 688 | ans[0] = index; 689 | ans[1] = list[index]; 690 | return ans; 691 | } 692 | } 693 | return ans; 694 | } 695 | } 696 | //Title: 432. All O`one Data Structure 697 | //Link: https://leetcode.com/problems/all-oone-data-structure 698 | //Tags: Hash Table, Linked List, Design, Doubly-Linked List 699 | public class AllOne 700 | { 701 | Dictionary a; 702 | SortedDictionary> b; 703 | public AllOne() 704 | { 705 | this.a = new Dictionary(); 706 | this.b = new SortedDictionary>(new ReverseSortComparer()); 707 | } 708 | public void Inc(string key) 709 | { 710 | if (!a.ContainsKey(key)) 711 | { 712 | a.Add(key, 1); 713 | if (!b.ContainsKey(1)) 714 | { 715 | b.Add(1, new List { key }); 716 | } 717 | else 718 | { 719 | b[1].Add(key); 720 | } 721 | } 722 | else 723 | { 724 | b[a[key]].Remove(key); 725 | if (b[a[key]].Count == 0) 726 | { 727 | b.Remove(a[key]); 728 | } 729 | a[key]++; 730 | if (!b.ContainsKey(a[key])) 731 | { 732 | b.Add(a[key], new List { key }); 733 | } 734 | else 735 | { 736 | b[a[key]].Add(key); 737 | } 738 | } 739 | } 740 | public void Dec(string key) 741 | { 742 | if (a[key] == 1) 743 | { 744 | b[a[key]].Remove(key); 745 | if (b[a[key]].Count == 0) 746 | { 747 | b.Remove(a[key]); 748 | } 749 | a.Remove(key); 750 | } 751 | else 752 | { 753 | b[a[key]].Remove(key); 754 | if (b[a[key]].Count == 0) 755 | { 756 | b.Remove(a[key]); 757 | } 758 | a[key]--; 759 | if (!b.ContainsKey(a[key])) 760 | { 761 | b.Add(a[key], new List { key }); 762 | } 763 | else 764 | { 765 | b[a[key]].Add(key); 766 | } 767 | } 768 | } 769 | public string GetMaxKey() 770 | { 771 | if (a.Count == 0) return ""; 772 | return b.ElementAt(0).Value[0]; 773 | } 774 | public string GetMinKey() 775 | { 776 | if (a.Count == 0) return ""; 777 | return b.ElementAt(b.Count - 1).Value[0]; 778 | } 779 | } 780 | //Title: 295. Find Median from Data Stream 781 | //Link: https://leetcode.com/problems/find-median-from-data-stream 782 | //Tags: Two Pointers, Design, Sorting, Heap (Priority Queue), Data Stream 783 | public class MedianFinder 784 | { 785 | List a; 786 | public MedianFinder() 787 | { 788 | this.a = new List(); 789 | } 790 | public void AddNum(int num) 791 | { 792 | InsertIntoSortedList(a, num, (a, b) => a.CompareTo(b)); 793 | } 794 | public double FindMedian() 795 | { 796 | int size = a.Count; 797 | if (size == 1) { return (double)a[0]; } 798 | if (size % 2 == 0) 799 | { 800 | int mid1 = a[(size / 2) - 1]; 801 | int mid2 = a[((size / 2))]; 802 | return (double)(mid1 + mid2) / 2; 803 | } 804 | else 805 | { 806 | int median = ((size + 1) / 2) - 1; 807 | return (double)a[median]; 808 | } 809 | } 810 | public void InsertIntoSortedList(IList list, IComparable value, Comparison comparison) 811 | { 812 | var startIndex = 0; 813 | var endIndex = list.Count; 814 | while (endIndex > startIndex) 815 | { 816 | var windowSize = endIndex - startIndex; 817 | var middleIndex = startIndex + (windowSize / 2); 818 | var middleValue = (IComparable)list[middleIndex]; 819 | var compareToResult = comparison(middleValue, value); 820 | if (compareToResult == 0) 821 | { 822 | list.Insert(middleIndex, value); 823 | return; 824 | } 825 | else if (compareToResult < 0) 826 | { 827 | startIndex = middleIndex + 1; 828 | } 829 | else 830 | { 831 | endIndex = middleIndex; 832 | } 833 | } 834 | list.Insert(startIndex, value); 835 | } 836 | } 837 | //Title: 710. Random Pick with Blacklist 838 | //Link: https://leetcode.com/problems/random-pick-with-blacklist 839 | //Tags: Array, Hash Table, Math, Binary Search, Sorting, Randomized 840 | public class RandomPickBlackList 841 | { 842 | Random rand; 843 | int diff; 844 | int len; 845 | int[] BL; 846 | public RandomPickBlackList(int n, int[] blacklist) 847 | { 848 | this.rand = new System.Random(); 849 | this.len = blacklist.Length; 850 | this.diff = n - this.len; 851 | this.BL = new int[this.len]; 852 | Array.Sort(blacklist); 853 | Array.Copy(blacklist, 0, this.BL, 0, this.len); 854 | } 855 | public int Pick() 856 | { 857 | int result = this.rand.Next(0, this.diff); 858 | for (int i = 0; i < this.len; i++) 859 | { 860 | if (result < this.BL[i]) return result; 861 | result++; 862 | } 863 | return result; 864 | } 865 | } 866 | //Title: 1172. Dinner Plate Stacks 867 | //Link: https://leetcode.com/problems/dinner-plate-stacks 868 | //Tags: Hash Table, Stack, Design, Heap (Priority Queue) 869 | public class DinnerPlates 870 | { 871 | int cap; 872 | int stackcount; 873 | int freecount; 874 | int somecount; 875 | List> a; 876 | Dictionary b; 877 | SortedDictionary c; 878 | SortedDictionary d; 879 | public DinnerPlates(int capacity) 880 | { 881 | cap = capacity; 882 | stackcount = 0; 883 | freecount = 0; 884 | somecount = 0; 885 | a = new List>(); 886 | b = new Dictionary(); 887 | c = new SortedDictionary(); 888 | d = new SortedDictionary(new ReverseSortComparer()); 889 | } 890 | public void Push(int val) 891 | { 892 | if (stackcount == 0) 893 | { 894 | b.Add(stackcount, 1); 895 | a.Add(new Stack()); 896 | a[stackcount].Push(val); 897 | if (cap > 1) { c.Add(stackcount, true); freecount++; } 898 | d.Add(stackcount, true); somecount++; 899 | stackcount++; 900 | return; 901 | } 902 | if (freecount > 0) 903 | { 904 | int key = c.ElementAt(0).Key; 905 | b[key]++; 906 | a[key].Push(val); 907 | if (b[key] == cap) { c.Remove(key); freecount--; } 908 | if (!d.ContainsKey(key)) { d.Add(key, true); somecount++; } 909 | return; 910 | } 911 | b.Add(stackcount, 1); 912 | a.Add(new Stack()); 913 | a[stackcount].Push(val); 914 | if (cap > 1) { c.Add(stackcount, true); freecount++; } 915 | d.Add(stackcount, true); somecount++; 916 | stackcount++; 917 | return; 918 | } 919 | public int Pop() 920 | { 921 | if (somecount > 0) 922 | { 923 | int key = d.ElementAt(0).Key; 924 | if (!c.ContainsKey(key)) { c.Add(key, true); freecount++; } 925 | b[key]--; 926 | if (b[key] == 0) { d.Remove(key); somecount--; } 927 | return a[key].Pop(); 928 | } 929 | return -1; 930 | } 931 | public int PopAtStack(int index) 932 | { 933 | if (b.ContainsKey(index)) 934 | { 935 | if (b[index] > 0) 936 | { 937 | if (!c.ContainsKey(index)) { c.Add(index, true); freecount++; } 938 | b[index]--; 939 | if (b[index] == 0) { d.Remove(index); somecount--; } 940 | return a[index].Pop(); 941 | } 942 | } 943 | return -1; 944 | } 945 | } 946 | //Title: 460. LFU Cache 947 | //Link: https://leetcode.com/problems/lfu-cache 948 | //Tags: Hash Table, Linked List, Design, Doubly-Linked List 949 | public class LFUCache 950 | { 951 | Dictionary a; 952 | List b; 953 | Dictionary c; 954 | SortedDictionary> d; 955 | int cap; 956 | int keycount; 957 | public LFUCache(int capacity) 958 | { 959 | a = new Dictionary(); 960 | b = new List(); 961 | c = new Dictionary(); 962 | d = new SortedDictionary>(); 963 | cap = capacity; 964 | keycount = 0; 965 | } 966 | public int Get(int key) 967 | { 968 | if (a.ContainsKey(key)) 969 | { 970 | d[c[key]].Remove(key); 971 | if (d[c[key]].Count() == 0) d.Remove(c[key]); 972 | c[key]++; 973 | if (!d.ContainsKey(c[key])) d.Add(c[key], new List { key }); 974 | else d[c[key]].Add(key); 975 | b.Remove(key); 976 | b.Add(key); 977 | return a[key]; 978 | } 979 | else return -1; 980 | } 981 | public void Put(int key, int value) 982 | { 983 | if (!a.ContainsKey(key)) 984 | { 985 | if (keycount == cap) 986 | { 987 | int remkey = 0; 988 | if (d.ElementAt(0).Value.Count() == 1) remkey = d.ElementAt(0).Value[0]; 989 | else if (d.ElementAt(0).Value.Count() > 1) 990 | { 991 | foreach (int i in b) 992 | { 993 | if (d.ElementAt(0).Value.Contains(i)) 994 | { 995 | remkey = i; 996 | break; 997 | } 998 | } 999 | } 1000 | d.ElementAt(0).Value.Remove(remkey); 1001 | if (d.ElementAt(0).Value.Count() == 0) d.Remove(c[remkey]); 1002 | c.Remove(remkey); 1003 | a.Remove(remkey); 1004 | b.Remove(remkey); 1005 | keycount--; 1006 | } 1007 | c.Add(key, 1); 1008 | if (!d.ContainsKey(c[key])) d.Add(c[key], new List { key }); 1009 | else d[c[key]].Add(key); 1010 | b.Add(key); 1011 | a.Add(key, value); 1012 | keycount++; 1013 | } 1014 | else 1015 | { 1016 | d[c[key]].Remove(key); 1017 | if (d[c[key]].Count() == 0) d.Remove(c[key]); 1018 | c[key]++; 1019 | if (!d.ContainsKey(c[key])) d.Add(c[key], new List { key }); 1020 | else d[c[key]].Add(key); 1021 | b.Remove(key); 1022 | b.Add(key); 1023 | a[key] = value; 1024 | } 1025 | } 1026 | } 1027 | #endregion 1028 | } -------------------------------------------------------------------------------- /LeetCode/JavaScript/Easy.js: -------------------------------------------------------------------------------- 1 | //Title: 2703. Return Length of Arguments Passed 2 | //Link: https://leetcode.com/problems/return-length-of-arguments-passed 3 | //Tags: JavaScript 4 | var argumentsLength = function (...args) { 5 | x = 0; 6 | for (let variable in args) { 7 | x += 1; 8 | } 9 | return x; 10 | }; 11 | //Title: 2667. Create Hello World Function 12 | //Link: https://leetcode.com/problems/create-hello-world-function 13 | //Tags: JavaScript 14 | var createHelloWorld = function () { 15 | return function (...args) { 16 | return HelloWorld(); 17 | } 18 | }; 19 | function HelloWorld() { 20 | return 'Hello World'; 21 | }; 22 | //Title: 2620. Counter 23 | //Link: https://leetcode.com/problems/counter 24 | //Tags: JavaScript 25 | var createCounter = function (n) { 26 | return function () { 27 | return n++; 28 | }; 29 | }; 30 | //Title: 2665. Counter II 31 | //Link: https://leetcode.com/problems/counter-ii 32 | //Tags: JavaScript 33 | var createCounter = function (init) { 34 | let val = init; 35 | function increment() { 36 | val++; 37 | return val; 38 | }; 39 | function decrement() { 40 | val--; 41 | return val; 42 | }; 43 | function reset() { 44 | val = init; 45 | return val; 46 | }; 47 | return { increment, decrement, reset }; 48 | }; 49 | //Title: 2727. Is Object Empty 50 | //Link: https://leetcode.com/problems/is-object-empty 51 | //Tags: JavaScript 52 | var isEmpty = function (obj) { 53 | return _.isEmpty(obj) 54 | }; -------------------------------------------------------------------------------- /LeetCode/LeetCode.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {DFD4F070-0A1B-4390-9DA2-45968000A055} 8 | Exe 9 | LeetCode 10 | LeetCode 11 | v4.7.2 12 | 512 13 | true 14 | true 15 | publish\ 16 | true 17 | Disk 18 | false 19 | Foreground 20 | 7 21 | Days 22 | false 23 | false 24 | true 25 | 0 26 | 1.0.0.%2a 27 | false 28 | false 29 | true 30 | 31 | 32 | AnyCPU 33 | true 34 | full 35 | false 36 | bin\Debug\ 37 | DEBUG;TRACE 38 | prompt 39 | 4 40 | 41 | 42 | AnyCPU 43 | pdbonly 44 | true 45 | bin\Release\ 46 | TRACE 47 | prompt 48 | 4 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 | False 76 | Microsoft .NET Framework 4.7.2 %28x86 and x64%29 77 | true 78 | 79 | 80 | False 81 | .NET Framework 3.5 SP1 82 | false 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /LeetCode/Pandas/Easy.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | #Title: 2879. Display the First Three Rows 3 | #Link: https://leetcode.com/problems/display-the-first-three-rows 4 | #Tags: Database 5 | def selectFirstRows(employees: pd.DataFrame) -> pd.DataFrame: 6 | df = pd.DataFrame(employees) 7 | return df.head(3) 8 | #Title: 2881. Create a New Column 9 | #Link: https://leetcode.com/problems/create-a-new-column 10 | #Tags: Database 11 | def createBonusColumn(employees: pd.DataFrame) -> pd.DataFrame: 12 | df = pd.DataFrame(employees) 13 | df['bonus'] = df.apply(lambda column: column.salary * 2, axis=1) 14 | return df 15 | #Title: 2884. Modify Columns 16 | #Link: https://leetcode.com/problems/modify-columns 17 | #Tags: Database 18 | def modifySalaryColumn(employees: pd.DataFrame) -> pd.DataFrame: 19 | df = pd.DataFrame(employees) 20 | df.salary *= 2 21 | return df 22 | #Title: 2880. Select Data 23 | #Link: https://leetcode.com/problems/select-data 24 | #Tags: Database 25 | def selectData(students: pd.DataFrame) -> pd.DataFrame: 26 | df = pd.DataFrame(students) 27 | nameage = df[["name", "age"]] 28 | nameage = nameage.loc[df['student_id'] == 101] 29 | return nameage 30 | #Title: 2877. Create a DataFrame from List 31 | #Link: https://leetcode.com/problems/create-a-dataframe-from-list 32 | #Tags: Database 33 | def createDataframe(student_data: List[List[int]]) -> pd.DataFrame: 34 | lst = student_data 35 | df = pd.DataFrame(lst, columns =['student_id', 'age']) 36 | return df 37 | #Title: 2878. Get the Size of a DataFrame 38 | #Link: https://leetcode.com/problems/get-the-size-of-a-dataframe 39 | #Tags: Database 40 | def getDataframeSize(players: pd.DataFrame) -> List[int]: 41 | df = pd.DataFrame(players) 42 | vals = [len(df.index), len(df.columns)] 43 | return vals 44 | #Title: 2885. Rename Columns 45 | #Link: https://leetcode.com/problems/rename-columns 46 | #Tags: Database 47 | def renameColumns(students: pd.DataFrame) -> pd.DataFrame: 48 | df = pd.DataFrame(students) 49 | df = df.rename(columns={'id': 'student_id', 'first': 'first_name', 'last': 'last_name', 'age': 'age_in_years'}) 50 | return df 51 | #Title: 2886. Change Data Type 52 | #Link: https://leetcode.com/problems/change-data-type 53 | #Tags: Database 54 | def changeDatatype(students: pd.DataFrame) -> pd.DataFrame: 55 | df = pd.DataFrame(students) 56 | df[["grade"]] = df[["grade"]].astype('int') 57 | return df 58 | #Title: 2883. Drop Missing Data 59 | #Link: https://leetcode.com/problems/drop-missing-data 60 | #Tags: Database 61 | def dropMissingData(students: pd.DataFrame) -> pd.DataFrame: 62 | df = pd.DataFrame(students) 63 | df = df[~df['name'].isnull()] 64 | return df 65 | #Title: 2882. Drop Duplicate Rows 66 | #Link: https://leetcode.com/problems/drop-duplicate-rows 67 | #Tags: Database 68 | def dropDuplicateEmails(customers: pd.DataFrame) -> pd.DataFrame: 69 | df = pd.DataFrame(customers) 70 | df = df.drop_duplicates(subset='email', keep="first") 71 | return df 72 | #Title: 2887. Fill Missing Data 73 | #Link: https://leetcode.com/problems/fill-missing-data 74 | #Tags: Database 75 | def fillMissingValues(products: pd.DataFrame) -> pd.DataFrame: 76 | df = pd.DataFrame(products) 77 | df["quantity"].fillna(0, inplace = True) 78 | return df 79 | #Title: 2888. Reshape Data: Concatenate 80 | #Link: https://leetcode.com/problems/reshape-data-concatenate 81 | #Tags: Database 82 | def concatenateTables(df1: pd.DataFrame, df2: pd.DataFrame) -> pd.DataFrame: 83 | df1 = pd.DataFrame(df1) 84 | df2 = pd.DataFrame(df2) 85 | frames = [df1, df2] 86 | result = pd.concat(frames) 87 | return result 88 | #Title: 2891. Method Chaining 89 | #Link: https://leetcode.com/problems/method-chaining 90 | #Tags: Database 91 | def findHeavyAnimals(animals: pd.DataFrame) -> pd.DataFrame: 92 | df = pd.DataFrame(animals) 93 | df = df[df['weight'] > 100].sort_values('weight', ascending=False) 94 | df = df[["name"]] 95 | return df 96 | #Title: 2889. Reshape Data: Pivot 97 | #Link: https://leetcode.com/problems/reshape-data-pivot 98 | #Tags: Database 99 | def pivotTable(weather: pd.DataFrame) -> pd.DataFrame: 100 | df = pd.DataFrame(weather) 101 | df = pd.pivot_table(df, values = 'temperature', index='month', columns = 'city', aggfunc="max") 102 | return df 103 | #Title: 2890. Reshape Data: Melt 104 | #Link: https://leetcode.com/problems/reshape-data-melt 105 | #Tags: Database 106 | def meltTable(report: pd.DataFrame) -> pd.DataFrame: 107 | df = pd.DataFrame(report) 108 | df = pd.melt(df, id_vars=['product'], value_vars=['quarter_1', 'quarter_2', 'quarter_3', 'quarter_4'], var_name='quarter', value_name='sales') 109 | return df -------------------------------------------------------------------------------- /LeetCode/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace LeetCode 9 | { 10 | internal class Program 11 | { 12 | #region "Notes" 13 | //The following list contains common time complexities of algorithms: 14 | //https://en.wikipedia.org/wiki/Big_O_notation 15 | //https://en.wikipedia.org/wiki/Time_complexity#Table_of_common_time_complexities 16 | 17 | //* O(1) The running time of a constant-time algorithm does not depend on the 18 | //input size.A typical constant-time algorithm is a direct formula that 19 | //calculates the answer. 20 | 21 | //* O(log n) A logarithmic algorithm often halves the input size at each step.The 22 | //running time of such an algorithm is logarithmic, because log2 n equals the 23 | //number of times n must be divided by 2 to get 1. 24 | 25 | //* O(pn) A square root algorithm is slower than O(log n) but faster than O(n). 26 | //A special property of square roots is that pn = n / pn, so the square root pn 27 | //lies, in some sense, in the middle of the input. 28 | 29 | //* O(n) A linear algorithm goes through the input a constant number of times.This 30 | //is often the best possible time complexity, because it is usually necessary to 31 | //access each input element at least once before reporting the answer. 32 | 33 | //* O(n log n) This time complexity often indicates that the algorithm sorts the input, 34 | //because the time complexity of efficient sorting algorithms is O(n log n). 35 | //Another possibility is that the algorithm uses a data structure where each 36 | //operation takes O(log n) time. 37 | 38 | //* O(n2) A quadratic algorithm often contains two nested loops.It is possible to 39 | //go through all pairs of the input elements in O(n2) time. 40 | 41 | //* O(n3) A cubic algorithm often contains three nested loops.It is possible to go 42 | //through all triplets of the input elements in O(n3) time. 43 | 44 | //* O(2n) This time complexity often indicates that the algorithm iterates through 45 | //all subsets of the input elements.For example, the subsets of { 1, 2, 3} are ;, 46 | //{1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3} and {1, 2, 3}. 47 | 48 | //* O(n!) This time complexity often indicates that the algorithm iterates through 49 | //all permutations of the input elements. For example, the permutations of 50 | //{ 1, 2, 3} are (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2) and (3, 2, 1). 51 | 52 | //* Optimize your code: Review your code and look for any inefficiencies, such as nested loops or redundant computations.By optimizing your code, you can reduce the time complexity and avoid TLE. 53 | 54 | //* Use data structures and algorithms: Efficient data structures and algorithms can help you solve problems faster.Familiarize yourself with common data structures like arrays, linked lists, and trees, as well as algorithms like binary search, dynamic programming, and divide and conquer. 55 | 56 | //* Practice and improve your problem-solving skills: The more you practice, the better you'll get at solving problems efficiently. LeetCode offers a wide range of problems to practice with, so make sure to try different problems to improve your skills. 57 | 58 | //* Understand the problem: Make sure you fully understand the problem you're trying to solve. Misunderstanding the problem can lead to inefficient or incorrect solutions. 59 | 60 | //* Use memoization: Memoization is a technique where you store the results of expensive function calls and return the cached result when the same inputs occur again.This can help reduce the time complexity of certain problems. Precomputing. 61 | 62 | //* Be mindful of language-specific optimizations: Different programming languages have different strengths and weaknesses. Choose a language that suits the problem you're trying to solve and make use of any language-specific optimizations. 63 | 64 | //* Consider parallel processing: If the problem allows for it, you can try parallel processing to speed up the solution.This involves breaking the problem into smaller sub-problems and solving them simultaneously using multiple threads or processes. 65 | 66 | //* Use LeetCode's hints and discussions: LeetCode provides hints and discussions for each problem. These can help you understand the problem better and find more efficient solutions. 67 | #endregion 68 | #region "Main" 69 | static void Main(string[] args) 70 | { 71 | //Dummy Data: 72 | char[][] u = new char[9][]; 73 | u[0] = new char[] { '.', '.', '9', '7', '4', '8', '.', '.', '.' }; 74 | u[1] = new char[] { '7', '.', '.', '.', '.', '.', '.', '.', '.' }; 75 | u[2] = new char[] { '.', '2', '.', '1', '.', '9', '.', '.', '.' }; 76 | u[3] = new char[] { '.', '.', '7', '.', '.', '.', '2', '4', '.' }; 77 | u[4] = new char[] { '.', '6', '4', '.', '1', '.', '5', '9', '.' }; 78 | u[5] = new char[] { '.', '9', '8', '.', '.', '.', '3', '.', '.' }; 79 | u[6] = new char[] { '.', '.', '.', '8', '.', '3', '.', '2', '.' }; 80 | u[7] = new char[] { '.', '.', '.', '.', '.', '.', '.', '.', '6' }; 81 | u[8] = new char[] { '.', '.', '.', '2', '7', '5', '9', '.', '.' }; 82 | int[][] q = new int[10][]; 83 | q[0] = new int[] { 1, 5 }; 84 | q[1] = new int[] { 10, 4 }; 85 | q[2] = new int[] { 4, 3 }; 86 | q[3] = new int[] { 7, 3 }; 87 | q[4] = new int[] { 3, 10 }; 88 | q[5] = new int[] { 9, 8 }; 89 | q[6] = new int[] { 8, 10 }; 90 | q[7] = new int[] { 4, 3 }; 91 | q[8] = new int[] { 1, 5 }; 92 | q[9] = new int[] { 1, 5 }; 93 | int k = 4; 94 | int f = 1000000000; 95 | string r = "s z z z s"; 96 | string v = "s z ejt"; 97 | string[] a = new string[] { "time", "to", "code" }; 98 | int[] b = new int[] { 41, 8467, 6334, 6500, 9169, 5724, 1478 }; 99 | char[] c = new char[] { 'h', 'e', 'l', 'l', 'o' }; 100 | int[] d = new int[] { 174, 188, 377, 437, 54, 498, 455, 239, 183, 347, 59, 199, 52, 488, 147, 82 }; 101 | int[] e = new int[] { 1, 2, 3 }; 102 | List> z = new List>(); 103 | z.Add(new List() { -1 }); 104 | z.Add(new List() { 2, 3 }); 105 | z.Add(new List() { 1, -1, -3 }); 106 | Stopwatch stopwatch = new Stopwatch(); 107 | stopwatch.Start(); 108 | //Execute Method Here 109 | stopwatch.Stop(); 110 | Console.WriteLine("Time taken: " + stopwatch.ElapsedMilliseconds + "ms"); 111 | Console.WriteLine("Done."); 112 | Console.ReadLine(); 113 | } 114 | #endregion 115 | } 116 | } -------------------------------------------------------------------------------- /LeetCode/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("LeetCode")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("LeetCode")] 13 | [assembly: AssemblyCopyright("Copyright © 2024")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("dfd4f070-0a1b-4390-9da2-45968000a055")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /LeetCode/SQL/Easy.sql: -------------------------------------------------------------------------------- 1 | --Title: 182. Duplicate Emails 2 | --Link: https://leetcode.com/problems/duplicate-emails 3 | --Tags: Database 4 | SELECT email FROM Person GROUP BY email HAVING COUNT(*) > 1; 5 | --Title: 196. Delete Duplicate Emails 6 | --Link: https://leetcode.com/problems/delete-duplicate-emails 7 | --Tags: Database 8 | DELETE FROM Person WHERE id NOT IN (SELECT MIN(id) FROM Person GROUP BY email) 9 | --Title: 584. Find Customer Referee 10 | --Link: https://leetcode.com/problems/find-customer-referee 11 | --Tags: Database 12 | SELECT name FROM Customer WHERE referee_id <> 2 OR referee_id IS NULL 13 | --Title: 595. Big Countries 14 | --Link: https://leetcode.com/problems/big-countries 15 | --Tags: Database 16 | SELECT name, population, area FROM World WHERE area >= 3000000 OR population >= 25000000 17 | --Title: 620. Not Boring Movies 18 | --Link: https://leetcode.com/problems/not-boring-movies 19 | --Tags: Database 20 | SELECT * FROM Cinema WHERE MOD(id, 2) <> 0 AND description <> 'boring' ORDER BY rating DESC 21 | --Title: 1068. Product Sales Analysis I 22 | --Link: https://leetcode.com/problems/product-sales-analysis-i 23 | --Tags: Database 24 | SELECT b.product_name, a.year, a.price FROM Sales AS a INNER JOIN Product AS b ON a.product_id = b.product_id 25 | --Title: 1148. Article Views I 26 | --Link: https://leetcode.com/problems/article-views-i 27 | --Tags: Database 28 | SELECT DISTINCT author_id AS id FROM Views WHERE viewer_id = author_id ORDER BY author_id ASC 29 | --Title: 1378. Replace Employee ID With The Unique Identifier 30 | --Link: https://leetcode.com/problems/replace-employee-id-with-the-unique-identifier 31 | --Tags: Database 32 | SELECT b.unique_id, a.name FROM Employees AS a LEFT JOIN EmployeeUNI AS b ON a.id = b.id 33 | --Title: 1527. Patients With a Condition 34 | --Link: https://leetcode.com/problems/patients-with-a-condition 35 | --Tags: Database 36 | SELECT patient_id, patient_name, conditions FROM Patients WHERE conditions like '%DIAB1%' AND conditions NOT IN ('SADIAB100') 37 | --Title: 1581. Customer Who Visited but Did Not Make Any Transactions 38 | --Link: https://leetcode.com/problems/customer-who-visited-but-did-not-make-any-transactions 39 | --Tags: Database 40 | SELECT customer_id, COUNT(*) AS [count_no_trans] FROM Visits WHERE visit_id NOT IN (SELECT visit_id FROM Transactions) GROUP BY customer_id 41 | --Title: 1667. Fix Names in a Table 42 | --Link: https://leetcode.com/problems/fix-names-in-a-table 43 | --Tags: Database 44 | SELECT user_id, UPPER(LEFT(name,1))+LOWER(SUBSTRING(name,2,LEN(name))) AS [name] FROM Users ORDER BY user_id 45 | --Title: 1683. Invalid Tweets 46 | --Link: https://leetcode.com/problems/invalid-tweets 47 | --Tags: Database 48 | SELECT tweet_id FROM Tweets WHERE LEN(content) > 15 49 | --Title: 1757. Recyclable and Low Fat Products 50 | --Link: https://leetcode.com/problems/recyclable-and-low-fat-products 51 | --Tags: Database 52 | SELECT product_id FROM Products WHERE low_fats = 'Y' AND recyclable = 'Y' 53 | --Title: 596. Classes More Than 5 Students 54 | --Link: https://leetcode.com/problems/classes-more-than-5-students 55 | --Tags: Database 56 | SELECT class FROM Courses GROUP BY class HAVING COUNT(class) > 4 57 | --Title: 1729. Find Followers Count 58 | --Link: https://leetcode.com/problems/find-followers-count 59 | --Tags: Database 60 | SELECT user_id, count(*) as [followers_count] FROM Followers GROUP BY user_id 61 | --Title: 619. Biggest Single Number 62 | --Link: https://leetcode.com/problems/biggest-single-number 63 | --Tags: Database 64 | SELECT MAX(num) AS [num] FROM (SELECT num FROM MyNumbers GROUP BY num HAVING COUNT(num) < 2) T 65 | --Title: 2356. Number of Unique Subjects Taught by Each Teacher 66 | --Link: https://leetcode.com/problems/number-of-unique-subjects-taught-by-each-teacher 67 | --Tags: Database 68 | SELECT teacher_id, count(*) as [cnt] FROM (SELECT teacher_id, subject_id FROM Teacher GROUP BY teacher_id, subject_id) T GROUP BY teacher_id 69 | --Title: 627. Swap Salary 70 | --Link: https://leetcode.com/problems/swap-salary 71 | --Tags: Database 72 | UPDATE Salary SET sex = CASE WHEN sex = 'f' THEN 'm' WHEN sex = 'm' THEN 'f' ELSE sex END WHERE sex IN ('f', 'm') -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Accepted LeetCode Solutions 2 | 3 | This repository contains all my solutions to LeetCode problems implemented in C#. 4 | 5 | Here is a link to my LeetCode [Account](https://leetcode.com/u/KylerCondran/). 6 | 7 | ## About LeetCode 8 | 9 | [LeetCode](https://leetcode.com/) is a popular online platform for practicing coding interview questions. It offers a vast array of problems across multiple difficulty levels, covering topics such as algorithms, data structures, and more. 10 | 11 | ## About This Repository 12 | 13 | The primary goal of this repository is to challenge myself and provide a resource for learning and understanding different problem-solving techniques in C#. By analyzing and implementing solutions to LeetCode problems, you can improve your problem-solving skills, understand various algorithms and data structures, and prepare for technical interviews. This code base is not perfect and could benefit from further optimization and cleanup, and some of the code I wrote may be downright silly, but each solution was accepted by the LeetCode judging software at the time of publishing. 14 | 15 | ## Structure 16 | 17 | In the project directory, I have a class file for each difficulty level of problems and an extra class file for helper methods. Each difficulty class file has two region tags, methods for individual problems are on top, and stand alone classes for design problems on bottom. The program class file contains the main run method, some dummy data, and helpful notes in case you wanted to run any of the solutions. There are also some folders for non C# related LeetCode categories. Each solution includes a numbered title, a link to the problem, tags associated with the problem, and the corresponding C# code that successfully solved the problem. 18 | 19 | ## Getting Started 20 | 21 | 1. Download 22 | ``` 23 | git clone https://github.com/KylerCondran/LeetCode.git 24 | ``` 25 | 26 | ## Things I Wish I Knew When First Starting 27 | 28 | - Question difficulties are often mislabeled, some easy's are quite hard, and there are hard problems which can be solved in 1 line of code. 29 | - Sometimes the question description is purposely misleading or confusing, leetcode problem writers are tricksters and trolls. Hints, discussion section, and topic labels are often great clues. Understanding the problem is literally half the battle. 30 | - It is better to do 100 easy's before you do a medium, and 100 medium's before you do a hard. 31 | - What is hard for some people may be easy to you and vica versa, everyone has a unique skill set and learning ability. 32 | - Non increasing just means decreasing but with duplicates, non decreasing means increasing but with duplicates. 33 | - If you are stumped on a question, instead of looking at the solution, look at a solution for a similar problem to find some starter code or get a better idea of what is needed. 34 | - Once you learn a new skill or data structure like linked lists, trees, or sliding window, you will get some starter code that can then be used to pop 20-30 questions quickly with minimal changes. 35 | - Spend some time exclusively hunting for problems you think you can accomplish, sort by difficulty / category / acceptance rate, use the browser bookmark toolbar and create folders, scan through questions and dump them into folders of different categories. 36 | - The constraints section provides valuable clues such as what ranges are valid for variables, this can give you clues that can allow you to skip calculations outside these ranges such as working with negative numbers or duplicates. 37 | - Acceptance rate does not mean difficulty level, it means it was the average amount of submits required to get accepted status. This number can be skewed by purposely obtuse test cases not mentioned in the problem. 38 | - Some test cases are hundreds of thousands of lines long, its best to copy these test case values into a text file and load the text file into an array rather than paste these values into the IDE for debugging. 39 | - The easiest way to start a GitHub portfolio is to just save your LeetCode solutions. 40 | - Its best to get comfy and drink coffee while LeetCoding. 41 | 42 | ## Examples 43 | 44 | Here is some super simple starter code to get you started working with common data structures. 45 | 46 | ### Building A Priority Queue 47 | ``` 48 | Dictionary a = new Dictionary(); 49 | for (int i = 0; i < nums.Length; i++) 50 | { 51 | int val = nums[i]; 52 | if (!a.ContainsKey(val)) 53 | { 54 | a.Add(val, 1); 55 | } 56 | else 57 | { 58 | a[val]++; 59 | } 60 | } 61 | ``` 62 | ### Parsing A Linked List 63 | ``` 64 | while (head != null) 65 | { 66 | int val = head.val; 67 | head = head.next; 68 | } 69 | ``` 70 | ### Parsing A Tree 71 | ``` 72 | Queue q = new Queue(); 73 | q.Enqueue(root); 74 | while (q.Count > 0) 75 | { 76 | TreeNode T = q.Dequeue(); 77 | if (T.left != null) 78 | { 79 | q.Enqueue(T.left); 80 | } 81 | if (T.right != null) 82 | { 83 | q.Enqueue(T.right); 84 | } 85 | } 86 | ``` 87 | ### Copying A 2D Jagged Array 88 | ``` 89 | int[][] targetArray = new int[3][]; 90 | targetArray[0] = new int[] { 1, 2, 3, 4 }; 91 | targetArray[1] = new int[] { 2, 1, 4, 3 }; 92 | targetArray[2] = new int[] { 3, 4, 1, 2 }; 93 | int len = targetArray.Length; 94 | int[][] newArray = new int[len][]; 95 | for (int x = 0; x < len; x++) 96 | { 97 | int[] inner = targetArray[x]; 98 | int ilen = inner.Length; 99 | int[] newer = new int[ilen]; 100 | Array.Copy(inner, newer, ilen); 101 | newArray[x] = newer; 102 | } 103 | ``` 104 | ### Find Lexicographically Larger String 105 | ``` 106 | string s1 = "StringA"; 107 | string s2 = "StringB"; 108 | int minlen = Math.Min(s1.Length, s2.Length); 109 | for (int x = 0; x < minlen; x++) 110 | { 111 | if (s1[x] > s2[x]) 112 | { 113 | return s1; 114 | } 115 | else if (s1[x] < s2[x]) 116 | { 117 | return s2; 118 | } 119 | } 120 | if (s1.Length > s2.Length) 121 | { 122 | return s1; 123 | } 124 | else if (s1.Length < s2.Length) 125 | { 126 | return s2; 127 | } 128 | ``` 129 | 130 | ## Submit Error Codes 131 | 132 | ### Time Limit Exceeded 133 | 134 | This error code means your application took too long to finish. LeetCode has a built in cut off switch that kills your application if it does not finish in a predetermined amount of time. This can mean a few things, it can mean your application is getting stuck in an infinite loop, it can also mean your application was not as efficient as required by the problem. Large test cases can cause your program to struggle to finish in a reasonable amount of time. Some things you can do to optimize your code: 135 | 136 | 1. Analyze the time complexity of your algorithm to understand its performance characteristics. 137 | 2. Identify potential bottlenecks in your code that may be causing the slowdown. 138 | 3. Consider using more efficient algorithms or data structures to solve the problem. 139 | 4. Optimize your code by eliminating unnecessary operations or reducing the number of iterations. 140 | 5. Experiment with different approaches and optimizations until you find a solution that runs within the time limit specified by LeetCode. 141 | 142 | The goal is to reduce calculations, calculate only what you need and do it once, use variables when you have finished the calculation and want to reuse the data, try to remove any nested loops or redundant computations, avoid expensive collection iteration calls like Dictionary.Count() / Dictionary.ElementAt(), use integer counter variables instead, precalculate data and hardcode if possible, use fast data structures like queues and stacks and hashsets and algorithms like binary search patterns, use a string builder instead of doing string concatenation ("stringa" + "stringb") because strings are immutable data types, cache the results of expensive calculations, minimize object creation, especially inside loops, and use for loops instead of foreach loops where possible. 143 | 144 | Do not get discouraged, often when you hit time limit exceeded instead of racking your brain on the problem for hours its best to immediately put it aside, take note and log it in an excel sheet with the title, link to the problem, and how many test cases you got through, save and store the code in a project, move on and come back later with a fresh mind and outlook after you have had a chance to ponder how it can be optimized. 145 | 146 | Some easy problems have time limits, more medium problems have time limits, and nearly all hard problems have time limits and brute force may not always be possible, some hard problems only have one solution which is a famous and obscure algorithm such as Kadane / Dijkstra / Euclid. 147 | 148 | Research Topics: 149 | [Time Complexity](https://en.wikipedia.org/wiki/Time_complexity) 150 | [Big O Notation](https://en.wikipedia.org/wiki/Big_O_notation) 151 | [Algorithms](https://en.wikipedia.org/wiki/List_of_algorithms) 152 | 153 | ### Memory Limit Exceeded 154 | 155 | This error code means you have a memory leak somewhere. One of your objects are getting too large to handle or you are not freeing resources after they are done being used. Consider using the data structures more efficiently, avoid allocating resources when unecessary, rethink the algorithm to use less space intensive techniques. 156 | 157 | ### Test Cases Passed But Took Too Long 158 | 159 | This is a frustrating error code but it is actually really good news, it means you are super close to having your solution accepted but the program still took longer to finish than allowed. Final tweaks need to be made to make your application faster. Optimize your code to make it run faster, it may be stuggling on a larger than average test case. 160 | 161 | ### Compile Error 162 | 163 | This means your code is not in the right format to be compiled. It will give you hints on what lines of code contain the illegal values. 164 | 165 | ### Runtime Error 166 | 167 | This means while your code did compile correctly, during operation it did something that was illegal. The most often causes can be something like an index going outside the bounds of an array, or trying to access a non existent or empty collection, or arguments given values outside of the acceptable ranges. You can read the error stack trace backwards to determine where the error occured. 168 | 169 | ### Wrong Answer 170 | 171 | This means your code did not return the correct output for the input it received. This requires going back and rewriting the logic to your program so it returns the correct answer for the given testcase. If you are confused on why your program returned the wrong answer it is most often helpful to debug the code and testcase externally from leetcode in an IDE. You can set break points and step through your code line by line and watch the variable values as they change to determine at what point do things go awry. 172 | 173 | ### Accepted 174 | 175 | Congratulations. Your code was accepted and you received credit for completion of the problem. 176 | 177 | ## Data Structure Pros/Cons 178 | 179 | 1. Array 180 | - Optimal Use Case: When the size is fixed and known in advance, and random access or iteration over elements is frequent. 181 | - Potential Drawbacks: Fixed size, inefficient for dynamic resizing, and costly insertions/deletions in the middle. 182 | 183 | 2. List 184 | - Optimal Use Case: When the size may change dynamically and frequent insertion/deletion at the end or random access to elements is required. 185 | - Potential Drawbacks: Dynamic resizing may lead to occasional memory reallocations and copying of elements, especially for large lists. 186 | 187 | 3. Dictionary 188 | - Optimal Use Case: When key-value pairs need to be stored and efficient lookups by key are required. 189 | - Potential Drawbacks: Hash collisions can degrade performance, especially for poorly distributed keys. Additionally, iteration order is not guaranteed. 190 | 191 | 4. HashSet 192 | - Optimal Use Case: When a collection of unique items needs to be stored, and fast membership tests (contains) are required. 193 | - Potential Drawbacks: Hash collisions and the need for a good hash function can impact performance. Iteration order is not guaranteed. 194 | 195 | 5. Queue 196 | - Optimal Use Case: When a first-in-first-out (FIFO) data structure is needed, such as task scheduling or breadth-first search algorithms. 197 | - Potential Drawbacks: Inefficient for random access to elements. Removing elements other than the head of the queue requires iterating through the entire queue. 198 | 199 | 6. Stack 200 | - Optimal Use Case: When a last-in-first-out (LIFO) data structure is needed, such as expression evaluation or backtracking algorithms. 201 | - Potential Drawbacks: Inefficient for random access to elements. Removing elements other than the top of the stack requires popping elements sequentially. 202 | 203 | 7. LinkedList 204 | - Optimal Use Case: When frequent insertion/deletion at arbitrary positions in the collection is required, and random access is not necessary. 205 | - Potential Drawbacks: Higher memory overhead compared to arrays due to additional pointers. Inefficient for random access to elements. 206 | 207 | 8. SortedDictionary 208 | - Optimal Use Case: When key-value pairs need to be stored, and iteration in sorted order by key is required. 209 | - Potential Drawbacks: Slower insertion and deletion compared to hash-based dictionaries due to maintaining sorted order. 210 | 211 | 9. SortedSet 212 | - Optimal Use Case: When a collection of unique items needs to be stored, and iteration in sorted order is required. 213 | - Potential Drawbacks: Slower insertion and deletion compared to hash-based sets due to maintaining sorted order. 214 | --------------------------------------------------------------------------------