[
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n  <img src=\"images/leetcode-repo-logo.png\" width=\"350\" height=\"200\">\n</p>\n<p align=\"center\">\n  <a href=\"https://blog.algomaster.io/\">Join Free Newsletter</a>\n</p>\n\nThis repository contains awesome LeetCode resources to learn Data Structures and Algorithms (DSA) and prepare for Coding interviews.\n\n👉 If you want to master DSA patterns, checkout [AlgoMaster.io](https://algomaster.io)\n\n## 💡 Tips\n- [How I Mastered DSA](https://blog.algomaster.io/p/how-i-mastered-data-structures-and-algorithms)\n- [How to Start LeetCode](https://blog.algomaster.io/p/how-to-start-leetcode-in-2025)\n- [15 Leetcode Patterns](https://blog.algomaster.io/p/15-leetcode-patterns)\n\n## 📌 Fundamental Concepts\n- [Algorithmic Complexity](https://blog.algomaster.io/p/57bd4963-462f-4294-a972-4012691fc729)\n- [Big-O Cheat Sheet](https://www.bigocheatsheet.com/)\n- [Arrays](https://www.youtube.com/watch?v=SlNq09scdWE&list=PLK63NuByH5o9odyBT7nfYkHZyvGQ5oVp2)\n- [Bit Manipulation Techniques](https://blog.algomaster.io/p/c650df76-f978-46ee-a572-eb13c354905d)\n- [Sorting Algorithms](https://medium.com/jl-codes/understanding-sorting-algorithms-af6222995c8)\n- [Linked List](https://www.youtube.com/watch?v=FbHf0ii0WDg&list=PLK63NuByH5o9odyBT7nfYkHZyvGQ5oVp2)\n- [Queues](https://medium.com/basecs/to-queue-or-not-to-queue-2653bcde5b04)\n- [Stacks](https://medium.com/basecs/stacks-and-overflows-dbcf7854dc67)\n- [Hash Tables](https://medium.com/basecs/taking-hash-tables-off-the-shelf-139cbf4752f0)\n- [Heaps](https://medium.com/basecs/learning-to-love-heaps-cef2b273a238)\n- [Recursion](https://leetcode.com/discuss/study-guide/1733447/become-master-in-recursion)\n- [Backtracking](https://medium.com/algorithms-and-leetcode/backtracking-e001561b9f28)\n- [Trees](https://leetcode.com/discuss/study-guide/1820334/Become-Master-in-Tree)\n- [Tries](https://medium.com/basecs/trying-to-understand-tries-3ec6bede0014)\n- [Binary Search](https://leetcode.com/discuss/study-guide/786126/Python-Powerful-Ultimate-Binary-Search-Template.-Solved-many-problems)\n- [Greedy Algorithm](https://www.freecodecamp.org/news/greedy-algorithms/)\n- [Dynamic Programming](https://medium.com/basecs/less-repetition-more-dynamic-programming-43d29830a630)\n- [Graph Theory](https://www.youtube.com/watch?v=xN5VGzK9_FQ&list=PLK63NuByH5o9odyBT7nfYkHZyvGQ5oVp2)\n- [Master Graph Algorithms](https://blog.algomaster.io/p/master-graph-algorithms-for-coding)\n- [DFS Traversal](https://medium.com/basecs/deep-dive-through-a-graph-dfs-traversal-8177df5d0f13)\n- [BFS Traversal](https://medium.com/basecs/going-broad-in-a-graph-bfs-traversal-959bd1a09255)\n- [Union-Find](https://leetcode.com/discuss/general-discussion/1072418/Disjoint-Set-Union-(DSU)Union-Find-A-Complete-Guide)\n- [Dijkstra Algorithm](https://leetcode.com/discuss/study-guide/1059477/A-guide-to-Dijkstra's-Algorithm)\n- [Minimum Spanning Tree](https://www.hackerearth.com/practice/algorithms/graphs/minimum-spanning-tree/tutorial/)\n\n## 🚀 Patterns\n- [15 Leetcode Patterns](https://blog.algomaster.io/p/15-leetcode-patterns)\n- [20 DP Patterns](https://blog.algomaster.io/p/20-patterns-to-master-dynamic-programming)\n- [Two Pointers Pattern](https://www.youtube.com/watch?v=QzZ7nmouLTI&list=PLK63NuByH5o9odyBT7nfYkHZyvGQ5oVp2)\n- [Sliding Window Pattern](https://www.youtube.com/watch?v=y2d0VHdvfdc&list=PLK63NuByH5o9odyBT7nfYkHZyvGQ5oVp2)\n- [Prefix Sum Pattern](https://www.youtube.com/watch?v=yuws7YK0Yng&list=PLK63NuByH5o9odyBT7nfYkHZyvGQ5oVp2)\n- [Fast and Slow Pointers Pattern](https://www.youtube.com/watch?v=b139yf7Ik-E&list=PLK63NuByH5o9odyBT7nfYkHZyvGQ5oVp2)\n- [Top 'K' Elements Pattern](https://www.youtube.com/watch?v=6_v6OoxvMOE&list=PLK63NuByH5o9odyBT7nfYkHZyvGQ5oVp2)\n- [Kadane's Algorithm](https://www.youtube.com/watch?v=NUWAXbSlsws&list=PLK63NuByH5o9odyBT7nfYkHZyvGQ5oVp2)\n- [Linked List In-place Reversal Pattern](https://www.youtube.com/watch?v=auoTGovuo9A&list=PLK63NuByH5o9odyBT7nfYkHZyvGQ5oVp2)\n- [Monotonic Stack Pattern](https://www.youtube.com/watch?v=DtJVwbbicjQ&list=PLK63NuByH5o9odyBT7nfYkHZyvGQ5oVp2)\n- [Overlapping Intervals Pattern](https://blog.algomaster.io/p/812e72f7-eced-4256-a4c1-00606ae50679)\n- [Backtracking Pattern](https://blog.algomaster.io/p/81d42ca2-600c-4252-aa33-a56462090048)\n- [Modified Binary Search Pattern](https://blog.algomaster.io/p/d0d81b04-4c2a-4b45-a101-5137c3146686)\n- [Tree Patterns](https://leetcode.com/discuss/study-guide/937307/Iterative-or-Recursive-or-DFS-and-BFS-Tree-Traversal-or-In-Pre-Post-and-LevelOrder-or-Views)\n  - [Tree Iterative Traversal](https://medium.com/leetcode-patterns/leetcode-pattern-0-iterative-traversals-on-trees-d373568eb0ec)\n  - [Tree Question Pattern](https://leetcode.com/discuss/study-guide/2879240/TREE-QUESTION-PATTERN-2023-oror-TREE-STUDY-GUIDE) \n- [Graph Patterns](https://leetcode.com/discuss/study-guide/655708/Graph-For-Beginners-Problems-or-Pattern-or-Sample-Solutions)\n- [DFS + BFS Patterns (1)](https://medium.com/leetcode-patterns/leetcode-pattern-1-bfs-dfs-25-of-the-problems-part-1-519450a84353)\n- [DFS + BFS Patterns (2)](https://medium.com/leetcode-patterns/leetcode-pattern-2-dfs-bfs-25-of-the-problems-part-2-a5b269597f52)\n\n## 📝 Must-Read Leetcode Articles\n- [Sliding Window Template](https://leetcode.com/problems/frequency-of-the-most-frequent-element/solutions/1175088/C++-Maximum-Sliding-Window-Cheatsheet-Template/)\n- [Two Pointers Patterns](https://leetcode.com/discuss/study-guide/1688903/Solved-all-two-pointers-problems-in-100-days)\n- [Collections of Important String Questions](https://leetcode.com/discuss/study-guide/2001789/Collections-of-Important-String-questions-Pattern)\n- [Substring Problem Template](https://leetcode.com/problems/minimum-window-substring/solutions/26808/Here-is-a-10-line-template-that-can-solve-most-'substring'-problems/)\n- [Binary Search Template](https://leetcode.com/discuss/study-guide/786126/Python-Powerful-Ultimate-Binary-Search-Template.-Solved-many-problems)\n- [A General Approach to Backtracking Questions](https://leetcode.com/problems/permutations/solutions/18239/A-general-approach-to-backtracking-questions-in-Java-(Subsets-Permutations-Combination-Sum-Palindrome-Partioning)/)\n- [Monotonic Stack Template](https://leetcode.com/discuss/study-guide/2347639/A-comprehensive-guide-and-template-for-monotonic-stack-based-problems)\n- [Heap Patterns](https://leetcode.com/discuss/general-discussion/1127238/master-heap-by-solving-23-questions-in-4-patterns-category)\n- [Bit Manipulation Patterns](https://leetcode.com/discuss/study-guide/4282051/all-types-of-patterns-for-bits-manipulations-and-how-to-use-it)\n- [Dynamic Programming Patterns](https://leetcode.com/discuss/study-guide/458695/Dynamic-Programming-Patterns)\n- [Stock Series Patterns](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/solutions/108870/most-consistent-ways-of-dealing-with-the-series-of-stock-problems/)\n\n## ✅ Curated Problems\n- [AlgoMaster 300](https://algomaster.io/practice/dsa-patterns)\n- [Blind 75](https://leetcode.com/discuss/general-discussion/460599/blind-75-leetcode-questions)\n- [Leetcode Top 100 Liked](https://leetcode.com/studyplan/top-100-liked/)\n- [Leetcode Top Interview 150](https://leetcode.com/studyplan/top-interview-150/)\n\n## 📺 YouTube Playlist\n- [AlgoMaster DSA Playlist](https://www.youtube.com/playlist?list=PLK63NuByH5o9odyBT7nfYkHZyvGQ5oVp2&pp=gAQB)\n- [AlgoMaster LeetCode Pattern Playlist](https://www.youtube.com/playlist?list=PLK63NuByH5o-tqaMUHRA4r8ObRW7PWz45)\n- [Abdul Bari's Algorithms Playlist](https://www.youtube.com/playlist?list=PLDN4rrl48XKpZkf03iYFl-O29szjTrs_O)\n- [William Fiset's Data Structure Playlist](https://www.youtube.com/playlist?list=PLDV1Zeh2NRsB6SWUrDFW2RmDotAfPbeHu)\n- [William Fiset's Graphs Playlist](https://www.youtube.com/playlist?list=PLDV1Zeh2NRsDGO4--qE8yH72HFL1Km93P)\n- [Tushar Roy's Dynamic Programming Playlist](https://www.youtube.com/playlist?list=PLrmLmBdmIlpsHaNTPP_jHHDx_os9ItYXr)\n\n## 📇 Courses\n- [Coursera - Algorithms, Part I](https://www.coursera.org/learn/algorithms-part1)\n- [Coursera - Algorithms, Part 2](https://www.coursera.org/learn/algorithms-part2)\n\n## 📚 Books\n- [Data Structures And Algorithms Made Easy](https://www.amazon.in/dp/B08CMLS7LZ)\n- [Cracking the Coding Interview](https://www.amazon.in/dp/0984782850)\n\n## 📩 Newsletter\n- [AlgoMaster Newsletter](https://blog.algomaster.io/)\n\n## 🔎 Visualization\n- [AlgoMaster DSA Animations](https://algomaster.io/animations/dsa)\n- [VisuAlgo](https://visualgo.net/en)\n\n## 📎 LeetCode Extensions\n- [LeetCode Timer](https://chromewebstore.google.com/detail/leetcode-timer/gfkgelnlcnomnahkfmhemgpahgmibofd): Easily time your leetcode practise sessions with automatic time setting based on difficulty.\n- [LeetCode Video Solutions](https://chromewebstore.google.com/detail/leetcode-video-solutions/ilnmgkahgjdpkoliooildngldmilhelm): Watch free LeetCode video ▶ solutions on the problem page itself.\n- [LeetCode Format](https://chromewebstore.google.com/detail/leetcode-format/imogghebhifnnlgogigikjecilkicfpp): Adds Format code button on leetcode to format the code using Prettier code formatter.\n- [LeetHub v2](https://chromewebstore.google.com/detail/leethub-v2/mhanfgfagplhgemhjfeolkkdidbakocm?hl=en): Automatically integrate your Leetcode & GeeksforGeeks submissions to GitHub.\n- [LeetCode VS Code Extension](https://marketplace.visualstudio.com/items?itemName=LeetCode.vscode-leetcode): Solve LeetCode problems in VS Code.\n\nYour contributions are most welcome!\n\n---\n\n<p align=\"center\">\n  <i>If you find this resource helpful, please give it a star ⭐️ and share it with others!</i>\n</p>\n"
  },
  {
    "path": "patterns/c#/FastAndSlowPointers.cs",
    "content": "using System;\nusing System.Collections.Generic;\n\npublic class ListNode {\n    public int val;\n    public ListNode next;\n    public ListNode(int x) {\n        val = x;\n        next = null;\n    }\n}\n\npublic class FastAndSlowPointers {\n    // LeetCode 141 - Linked List Cycle (HashSet Approach)\n    public bool HasCycleHashSetApproach(ListNode head) {\n        HashSet<ListNode> visited = new HashSet<ListNode>();\n        ListNode current = head;\n        while (current != null) {\n            if (visited.Contains(current)) {\n                return true; // Cycle detected\n            }\n            visited.Add(current);\n            current = current.next;\n        }\n        return false; // No cycle\n    }\n\n    // LeetCode 141 - Linked List Cycle (Fast and Slow Pointer Approach)\n    public bool HasCycleFastAndSlowPointersApproach(ListNode head) {\n        if (head == null || head.next == null) return false;\n        ListNode slow = head, fast = head;\n        while (fast != null && fast.next != null) {\n            slow = slow.next;\n            fast = fast.next.next;\n            if (slow == fast) return true;\n        }\n        return false;\n    }\n\n    // LeetCode 876 - Middle of the Linked List (Counting Approach)\n    public ListNode MiddleNodeCountingApproach(ListNode head) {\n        int count = 0;\n        ListNode current = head;\n        while (current != null) {\n            count++;\n            current = current.next;\n        }\n        current = head;\n        for (int i = 0; i < count / 2; i++) {\n            current = current.next;\n        }\n        return current;\n    }\n\n    // LeetCode 876 - Middle of the Linked List (Fast and Slow Pointer Approach)\n    public ListNode MiddleNodeFastAndSlowPointerApproach(ListNode head) {\n        ListNode slow = head, fast = head;\n        while (fast != null && fast.next != null) {\n            slow = slow.next;\n            fast = fast.next.next;\n        }\n        return slow;\n    }\n\n    // LeetCode 202 - Happy Number (HashSet Approach)\n    private int GetSumOfSquares(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int digit = n % 10;\n            sum += digit * digit;\n            n /= 10;\n        }\n        return sum;\n    }\n\n    public bool IsHappyHashSetApproach(int n) {\n        HashSet<int> seen = new HashSet<int>();\n        while (n != 1 && !seen.Contains(n)) {\n            seen.Add(n);\n            n = GetSumOfSquares(n);\n        }\n        return n == 1;\n    }\n\n    // LeetCode 202 - Happy Number (Fast and Slow Pointer Approach)\n    public bool IsHappyFastAndSlowPointersApproach(int n) {\n        int slow = n;\n        int fast = GetSumOfSquares(n);\n        while (fast != 1 && slow != fast) {\n            slow = GetSumOfSquares(slow);\n            fast = GetSumOfSquares(GetSumOfSquares(fast));\n        }\n        return fast == 1;\n    }\n}"
  },
  {
    "path": "patterns/c#/KadaneAlgorithm.cs",
    "content": "using System;\n\npublic class KadaneAlgorithm {\n    public int MaxSubArray(int[] nums) {\n        int currentSum = nums[0];\n        int maxSum = nums[0];\n\n        for (int i = 1; i < nums.Length; i++) {\n            currentSum = Math.Max(nums[i], currentSum + nums[i]);\n            maxSum = Math.Max(maxSum, currentSum);\n        }\n        return maxSum;\n    }\n}"
  },
  {
    "path": "patterns/c#/LevelOrderTraversal.cs",
    "content": "using System;\nusing System.Collections.Generic;\n\npublic class TreeNode {\n    public int val;\n    public TreeNode left;\n    public TreeNode right;\n\n    public TreeNode(int x) {\n        val = x;\n    }\n}\n\npublic class LevelOrderTraversal {\n    public void LevelOrder(TreeNode root) {\n        if (root == null) return;\n\n        Queue<TreeNode> queue = new Queue<TreeNode>();\n        queue.Enqueue(root);\n\n        while (queue.Count > 0) {\n            TreeNode node = queue.Dequeue();\n            Console.Write(node.val + \" \"); // Process the node by printing its value\n            \n            // Add the left and right children to the queue, if they exist\n            if (node.left != null) queue.Enqueue(node.left);\n            if (node.right != null) queue.Enqueue(node.right);\n        }\n    }\n}"
  },
  {
    "path": "patterns/c#/MonotonicStack.cs",
    "content": "using System;\nusing System.Collections.Generic;\n\npublic class MonotonicStack {\n    public int[] NextGreaterElement(int[] nums) {\n        int n = nums.Length;\n        int[] result = new int[n];\n        Array.Fill(result, -1); // Default to -1 if no greater element exists\n        Stack<int> stack = new Stack<int>(); // Stack stores indices\n\n        for (int i = 0; i < n; i++) {\n            while (stack.Count > 0 && nums[i] > nums[stack.Peek()]) {\n                int index = stack.Pop();\n                result[index] = nums[i];\n            }\n            stack.Push(i);\n        }\n        return result;\n    }\n\n    public int[] DailyTemperatures(int[] temperatures) {\n        int n = temperatures.Length;\n        int[] result = new int[n]; // Result array initialized with 0s\n        Stack<int> stack = new Stack<int>(); // Monotonic decreasing stack\n\n        for (int i = 0; i < n; i++) {\n            while (stack.Count > 0 && temperatures[i] > temperatures[stack.Peek()]) {\n                int prevIndex = stack.Pop();\n                result[prevIndex] = i - prevIndex;\n            }\n            stack.Push(i);\n        }\n        return result;\n    }\n}"
  },
  {
    "path": "patterns/c#/ReverseList.cs",
    "content": "public class ListNode {\n    public int val;\n    public ListNode next;\n    public ListNode(int val = 0, ListNode next = null) {\n        this.val = val;\n        this.next = next;\n    }\n}\n\npublic class Solution {\n    public ListNode ReverseList(ListNode head) {\n        ListNode prev = null;\n        ListNode curr = head;\n\n        while (curr != null) {\n            ListNode next = curr.next;\n            curr.next = prev;\n            prev = curr;\n            curr = next;\n        }\n        return prev;\n    }\n}"
  },
  {
    "path": "patterns/c#/SlidingWindow.cs",
    "content": "using System;\nusing System.Collections.Generic;\n\npublic class SlidingWindow {\n    public double FindMaxAverageBruteForce(int[] nums, int k) {\n        int n = nums.Length;\n        double maxAvg = double.MinValue;\n\n        for (int i = 0; i <= n - k; i++) {\n            int sum = 0;\n            for (int j = i; j < i + k; j++) {\n                sum += nums[j];\n            }\n            maxAvg = Math.Max(maxAvg, (double)sum / k);\n        }\n        return maxAvg;\n    }\n\n    public double FindMaxAverageSlidingWindow(int[] nums, int k) {\n        int n = nums.Length;\n        int sum = 0;\n\n        for (int i = 0; i < k; i++) {\n            sum += nums[i];\n        }\n\n        int maxSum = sum;\n\n        for (int i = k; i < n; i++) {\n            sum += nums[i];\n            sum -= nums[i - k];\n            maxSum = Math.Max(maxSum, sum);\n        }\n\n        return (double)maxSum / k;\n    }\n\n    public int LengthOfLongestSubstringSlidingWindow(string s) {\n        HashSet<char> seen = new HashSet<char>();\n        int maxLength = 0, left = 0;\n\n        for (int right = 0; right < s.Length; right++) {\n            while (seen.Contains(s[right])) {\n                seen.Remove(s[left]);\n                left++;\n            }\n            seen.Add(s[right]);\n            maxLength = Math.Max(maxLength, right - left + 1);\n        }\n        return maxLength;\n    }\n\n    public int LengthOfLongestSubstringSlidingWindowFrequencyArray(string s) {\n        int[] freq = new int[128];\n        int maxLength = 0, left = 0;\n\n        for (int right = 0; right < s.Length; right++) {\n            freq[s[right]]++;\n\n            while (freq[s[right]] > 1) {\n                freq[s[left]]--;\n                left++;\n            }\n\n            maxLength = Math.Max(maxLength, right - left + 1);\n        }\n        return maxLength;\n    }\n}"
  },
  {
    "path": "patterns/c#/TopKElements.cs",
    "content": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class TopKElements {\n    \n    // K Largest Elements using Sorting\n    public int[] KLargestElementsSortingApproach(int[] nums, int k) {\n        Array.Sort(nums, (a, b) => b.CompareTo(a));\n        return nums.Take(k).ToArray();\n    }\n\n    // K Largest Elements using Max Heap\n    public int[] KLargestElementsMaxHeapApproach(int[] nums, int k) {\n        PriorityQueue<int, int> maxHeap = new PriorityQueue<int, int>(Comparer<int>.Create((a, b) => b - a));\n        foreach (var num in nums) {\n            maxHeap.Enqueue(num, num);\n        }\n        var result = new int[k];\n        for (int i = 0; i < k; i++) {\n            result[i] = maxHeap.Dequeue();\n        }\n        return result;\n    }\n\n    // K Largest Elements using Min Heap\n    public int[] KLargestElementsMinHeapApproach(int[] nums, int k) {\n        PriorityQueue<int, int> minHeap = new PriorityQueue<int, int>();\n        for (int i = 0; i < k; i++) {\n            minHeap.Enqueue(nums[i], nums[i]);\n        }\n        for (int i = k; i < nums.Length; i++) {\n            minHeap.Enqueue(nums[i], nums[i]);\n            if (minHeap.Count > k) {\n                minHeap.Dequeue();\n            }\n        }\n        var result = new int[k];\n        for (int i = 0; i < k; i++) {\n            result[i] = minHeap.Dequeue();\n        }\n        return result;\n    }\n\n    // Top K Frequent Elements using Sorting\n    public int[] TopKFrequentElementsSortingApproach(int[] nums, int k) {\n        var frequencyMap = new Dictionary<int, int>();\n        foreach (var num in nums) {\n            if (!frequencyMap.ContainsKey(num)) {\n                frequencyMap[num] = 0;\n            }\n            frequencyMap[num]++;\n        }\n\n        var sortedEntries = frequencyMap.OrderByDescending(e => e.Value).Take(k).Select(e => e.Key).ToArray();\n        return sortedEntries;\n    }\n\n    // Top K Frequent Elements using Min Heap\n    public int[] TopKFrequentElementsMinHeapApproach(int[] nums, int k) {\n        var frequencyMap = new Dictionary<int, int>();\n        foreach (var num in nums) {\n            if (!frequencyMap.ContainsKey(num)) {\n                frequencyMap[num] = 0;\n            }\n            frequencyMap[num]++;\n        }\n\n        var minHeap = new PriorityQueue<int, int>(Comparer<int>.Create((a, b) => a.CompareTo(b)));\n        foreach (var entry in frequencyMap) {\n            minHeap.Enqueue(entry.Key, entry.Value);\n            if (minHeap.Count > k) {\n                minHeap.Dequeue();\n            }\n        }\n\n        var result = new int[k];\n        for (int i = 0; i < k; i++) {\n            result[i] = minHeap.Dequeue();\n        }\n        return result;\n    }\n\n    // K Closest Points to Origin using Max Heap\n    private int GetDistance(int[] point) {\n        return point[0] * point[0] + point[1] * point[1];\n    }\n\n    public int[][] KClosestPointsToOriginMaxHeapApproach(int[][] points, int k) {\n        PriorityQueue<int[], int> maxHeap = new PriorityQueue<int[], int>(Comparer<int>.Create((a, b) => b - a));\n        foreach (var point in points) {\n            maxHeap.Enqueue(point, GetDistance(point));\n            if (maxHeap.Count > k) {\n                maxHeap.Dequeue();\n            }\n        }\n        var result = new int[k][];\n        for (int i = 0; i < k; i++) {\n            result[i] = maxHeap.Dequeue();\n        }\n        return result;\n    }\n}"
  },
  {
    "path": "patterns/c#/TwoPointers.cs",
    "content": "using System;\n\npublic class TwoPointers {\n    // Move Zeroes using Two Pointers\n    public void MoveZeroesTwoPointers(int[] nums) {\n        int left = 0; // Pointer for placing non-zero elements\n\n        // Iterate with right pointer\n        for (int right = 0; right < nums.Length; right++) {\n            if (nums[right] != 0) {\n                // Swap elements if right pointer finds a non-zero\n                (nums[left], nums[right]) = (nums[right], nums[left]);\n                left++; // Move left pointer forward\n            }\n        }\n    }\n\n    // Brute Force approach for Container with Most Water\n    public int MaxAreaBruteForce(int[] height) {\n        int n = height.Length;\n        int maxArea = 0;\n\n        // Check all pairs (i, j)\n        for (int i = 0; i < n; i++) {\n            for (int j = i + 1; j < n; j++) {\n                // Compute the minimum height and width\n                int minHeight = Math.Min(height[i], height[j]);\n                int width = j - i;\n                int area = minHeight * width; // Compute water contained\n\n                maxArea = Math.Max(maxArea, area); // Update max water\n            }\n        }\n        return maxArea;\n    }\n\n    // Two Pointers approach for Container with Most Water\n    public int MaxAreaTwoPointers(int[] height) {\n        int left = 0, right = height.Length - 1;\n        int maxArea = 0;\n\n        // Move pointers toward each other\n        while (left < right) {\n            int width = right - left; // Distance between lines\n            int minHeight = Math.Min(height[left], height[right]); // Compute height\n            int area = minHeight * width; // Compute water contained\n\n            maxArea = Math.Max(maxArea, area); // Update max water\n\n            // Move the pointer pointing to the shorter height\n            if (height[left] < height[right]) {\n                left++; // Move left pointer forward\n            } else {\n                right--; // Move right pointer backward\n            }\n        }\n        return maxArea;\n    }\n}"
  },
  {
    "path": "patterns/c++/FastAndSlowPointers.cpp",
    "content": "#include <unordered_set>\nusing namespace std;\n\nclass ListNode {\npublic:\n    int val;\n    ListNode* next;\n    ListNode(int x) : val(x), next(nullptr) {}\n};\n\nclass FastAndSlowPointers {\npublic:\n    // LeetCode 141 - Linked List Cycle (HashSet Approach)\n    bool hasCycleHashSetApproach(ListNode* head) {\n        unordered_set<ListNode*> visited;\n        ListNode* current = head;\n        while (current != nullptr) {\n            if (visited.find(current) != visited.end()) {\n                return true; // Cycle detected\n            }\n            visited.insert(current);\n            current = current->next;\n        }\n        return false; // No cycle\n    }\n\n    // LeetCode 141 - Linked List Cycle (Fast and Slow Pointer Approach)\n    bool hasCycleFastAndSlowPointersApproach(ListNode* head) {\n        if (head == nullptr || head->next == nullptr) {\n            return false;\n        }\n        ListNode* slow = head;\n        ListNode* fast = head;\n        while (fast != nullptr && fast->next != nullptr) {\n            slow = slow->next;\n            fast = fast->next->next;\n            if (slow == fast) {\n                return true; // Cycle detected\n            }\n        }\n        return false; // No cycle\n    }\n\n    // LeetCode 876 - Middle of the Linked List (Counting Approach)\n    ListNode* middleNodeCountingApproach(ListNode* head) {\n        int count = 0;\n        ListNode* current = head;\n        while (current != nullptr) {\n            count++;\n            current = current->next;\n        }\n        current = head;\n        for (int i = 0; i < count / 2; i++) {\n            current = current->next;\n        }\n        return current;\n    }\n\n    // LeetCode 876 - Middle of the Linked List (Fast and Slow Pointer Approach)\n    ListNode* middleNodeFastAndSlowPointerApproach(ListNode* head) {\n        ListNode* slow = head;\n        ListNode* fast = head;\n        while (fast != nullptr && fast->next != nullptr) {\n            slow = slow->next;\n            fast = fast->next->next;\n        }\n        return slow;\n    }\n\n    // LeetCode 202 - Happy Number (HashSet Approach)\n    int getSumOfSquares(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int digit = n % 10;\n            sum += digit * digit;\n            n /= 10;\n        }\n        return sum;\n    }\n\n    bool isHappyHashSetApproach(int n) {\n        unordered_set<int> seen;\n        while (n != 1 && seen.find(n) == seen.end()) {\n            seen.insert(n);\n            n = getSumOfSquares(n);\n        }\n        return n == 1;\n    }\n\n    // LeetCode 202 - Happy Number (Fast and Slow Pointer Approach)\n    bool isHappyFastAndSlowPointersApproach(int n) {\n        int slow = n;\n        int fast = getSumOfSquares(n);\n        while (fast != 1 && slow != fast) {\n            slow = getSumOfSquares(slow);\n            fast = getSumOfSquares(getSumOfSquares(fast));\n        }\n        return fast == 1;\n    }\n};"
  },
  {
    "path": "patterns/c++/KadaneAlgorithm.cpp",
    "content": "#include <vector>\n#include <algorithm> // For std::max\n\nclass KadaneAlgorithm {\npublic:\n    int maxSubArray(std::vector<int>& nums) {\n        int currentSum = nums[0]; // Start with the first element\n        int maxSum = nums[0];     // Initialize maxSum with the first element\n\n        // Traverse the array from the second element\n        for (size_t i = 1; i < nums.size(); i++) {\n            // If currentSum is negative, reset to current element\n            currentSum = std::max(nums[i], currentSum + nums[i]);\n            // Update maxSum if currentSum is greater\n            maxSum = std::max(maxSum, currentSum);\n        }\n        return maxSum;\n    }\n};"
  },
  {
    "path": "patterns/c++/LevelOrderTraversal.cpp",
    "content": "#include <iostream>\n#include <queue>\nusing namespace std;\n\n// Definition for a binary tree node.\nstruct TreeNode {\n    int val;\n    TreeNode* left;\n    TreeNode* right;\n\n    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n};\n\nclass LevelOrderTraversal {\npublic:\n    void levelOrder(TreeNode* root) {\n        if (root == nullptr) return;\n\n        queue<TreeNode*> q;\n        q.push(root);\n\n        while (!q.empty()) {\n            TreeNode* node = q.front();\n            q.pop();\n            cout << node->val << \" \"; // Process the node by printing its value\n            \n            // Add the left and right children to the queue, if they exist\n            if (node->left != nullptr) q.push(node->left);\n            if (node->right != nullptr) q.push(node->right);\n        }\n    }\n};"
  },
  {
    "path": "patterns/c++/MonotonicStack.cpp",
    "content": "#include <vector>\n#include <stack>\n\nusing namespace std;\n\nclass MonotonicStack {\npublic:\n    vector<int> nextGreaterElement(vector<int>& nums) {\n        int n = nums.size();\n        vector<int> result(n, -1); // Default to -1 if no greater element exists\n        stack<int> stack; // Stack stores indices\n\n        for (int i = 0; i < n; i++) {\n            while (!stack.empty() && nums[i] > nums[stack.top()]) {\n                int index = stack.top();\n                stack.pop();\n                result[index] = nums[i];\n            }\n            stack.push(i);\n        }\n        return result;\n    }\n\n    vector<int> dailyTemperatures(vector<int>& temperatures) {\n        int n = temperatures.size();\n        vector<int> result(n, 0);\n        stack<int> stack; // Monotonic decreasing stack\n\n        for (int i = 0; i < n; i++) {\n            while (!stack.empty() && temperatures[i] > temperatures[stack.top()]) {\n                int prevIndex = stack.top();\n                stack.pop();\n                result[prevIndex] = i - prevIndex;\n            }\n            stack.push(i);\n        }\n        return result;\n    }\n};"
  },
  {
    "path": "patterns/c++/ReverseList.cpp",
    "content": "struct ListNode {\n    int val;\n    ListNode* next;\n    ListNode(int x) : val(x), next(nullptr) {}\n};\n\nListNode* reverseList(ListNode* head) {\n    ListNode* prev = nullptr;\n    ListNode* curr = head;\n\n    while (curr != nullptr) {\n        ListNode* next = curr->next;\n        curr->next = prev;\n        prev = curr;\n        curr = next;\n    }\n    return prev;\n}"
  },
  {
    "path": "patterns/c++/SlidingWindow.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <unordered_set>\n#include <algorithm>\n\nusing namespace std;\n\nclass SlidingWindow {\npublic:\n    double findMaxAverageBruteForce(vector<int>& nums, int k) {\n        int n = nums.size();\n        double maxAvg = INT_MIN;\n\n        for (int i = 0; i <= n - k; i++) {\n            int sum = 0;\n            for (int j = i; j < i + k; j++) {\n                sum += nums[j];\n            }\n            maxAvg = max(maxAvg, (double)sum / k);\n        }\n        return maxAvg;\n    }\n\n    double findMaxAverageSlidingWindow(vector<int>& nums, int k) {\n        int n = nums.size();\n        int sum = 0;\n\n        for (int i = 0; i < k; i++) {\n            sum += nums[i];\n        }\n\n        int maxSum = sum;\n\n        for (int i = k; i < n; i++) {\n            sum += nums[i];\n            sum -= nums[i - k];\n            maxSum = max(maxSum, sum);\n        }\n\n        return (double)maxSum / k;\n    }\n\n    int lengthOfLongestSubstringSlidingWindow(string s) {\n        unordered_set<char> seen;\n        int maxLength = 0, left = 0;\n\n        for (int right = 0; right < s.size(); right++) {\n            while (seen.count(s[right])) {\n                seen.erase(s[left]);\n                left++;\n            }\n            seen.insert(s[right]);\n            maxLength = max(maxLength, right - left + 1);\n        }\n        return maxLength;\n    }\n\n    int lengthOfLongestSubstringSlidingWindowFrequencyArray(string s) {\n        vector<int> freq(128, 0);\n        int maxLength = 0, left = 0;\n\n        for (int right = 0; right < s.size(); right++) {\n            freq[s[right]]++;\n\n            while (freq[s[right]] > 1) {\n                freq[s[left]]--;\n                left++;\n            }\n\n            maxLength = max(maxLength, right - left + 1);\n        }\n        return maxLength;\n    }\n};"
  },
  {
    "path": "patterns/c++/TopKElements.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <queue>\n#include <unordered_map>\n#include <algorithm>\n\nusing namespace std;\n\nclass TopKElements {\npublic:\n    // K Largest Elements using Sorting\n    vector<int> kLargestElementsSortingAppraoch(vector<int>& nums, int k) {\n        sort(nums.begin(), nums.end(), greater<int>());\n        return vector<int>(nums.begin(), nums.begin() + k);\n    }\n\n    // K Largest Elements using Max Heap\n    vector<int> kLargestElementsMaxHeapAppraoch(vector<int>& nums, int k) {\n        priority_queue<int> maxHeap(nums.begin(), nums.end());\n        vector<int> result;\n        for (int i = 0; i < k; i++) {\n            result.push_back(maxHeap.top());\n            maxHeap.pop();\n        }\n        return result;\n    }\n\n    // K Largest Elements using Min Heap\n    vector<int> kLargestElementsMinHeapAppraoch(vector<int>& nums, int k) {\n        priority_queue<int, vector<int>, greater<int>> minHeap;\n        for (int i = 0; i < k; i++) {\n            minHeap.push(nums[i]);\n        }\n        for (int i = k; i < nums.size(); i++) {\n            minHeap.push(nums[i]);\n            if (minHeap.size() > k) {\n                minHeap.pop();\n            }\n        }\n        vector<int> result;\n        while (!minHeap.empty()) {\n            result.push_back(minHeap.top());\n            minHeap.pop();\n        }\n        return result;\n    }\n\n    // Top K Frequent Elements using Sorting\n    vector<int> topKFrequentElementsSortingApproach(vector<int>& nums, int k) {\n        unordered_map<int, int> frequencyMap;\n        for (int num : nums) {\n            frequencyMap[num]++;\n        }\n\n        vector<pair<int, int>> freqVec(frequencyMap.begin(), frequencyMap.end());\n        sort(freqVec.begin(), freqVec.end(), [](pair<int, int>& a, pair<int, int>& b) {\n            return b.second < a.second;\n        });\n\n        vector<int> result;\n        for (int i = 0; i < k; i++) {\n            result.push_back(freqVec[i].first);\n        }\n        return result;\n    }\n\n    // Top K Frequent Elements using Min Heap\n    vector<int> topKFrequentElementsMinHeapApproach(vector<int>& nums, int k) {\n        unordered_map<int, int> frequencyMap;\n        for (int num : nums) {\n            frequencyMap[num]++;\n        }\n\n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> minHeap;\n        for (auto& entry : frequencyMap) {\n            minHeap.push({entry.second, entry.first});\n            if (minHeap.size() > k) {\n                minHeap.pop();\n            }\n        }\n\n        vector<int> result;\n        while (!minHeap.empty()) {\n            result.push_back(minHeap.top().second);\n            minHeap.pop();\n        }\n        return result;\n    }\n\n    // K Closest Points to Origin using Max Heap\n    int getDistance(vector<int>& point) {\n        return point[0] * point[0] + point[1] * point[1];\n    }\n\n    vector<vector<int>> kClosestPointsToOriginMaxHeapApproach(vector<vector<int>>& points, int k) {\n        priority_queue<pair<int, vector<int>>> maxHeap;\n        for (vector<int>& point : points) {\n            maxHeap.push({getDistance(point), point});\n            if (maxHeap.size() > k) {\n                maxHeap.pop();\n            }\n        }\n\n        vector<vector<int>> result;\n        while (!maxHeap.empty()) {\n            result.push_back(maxHeap.top().second);\n            maxHeap.pop();\n        }\n        return result;\n    }\n};"
  },
  {
    "path": "patterns/c++/TwoPointers.cpp",
    "content": "#include <iostream>\n#include <vector>\n#include <algorithm>\n\nusing namespace std;\n\nclass TwoPointers {\npublic:\n    // Move Zeroes using Two Pointers\n    void moveZeroesTwoPointers(vector<int>& nums) {\n        int left = 0; // Pointer for placing non-zero elements\n\n        // Iterate with right pointer\n        for (int right = 0; right < nums.size(); right++) {\n            if (nums[right] != 0) {\n                // Swap elements if right pointer finds a non-zero\n                swap(nums[left], nums[right]);\n                left++; // Move left pointer forward\n            }\n        }\n    }\n\n    // Brute Force approach for Container with Most Water\n    int maxAreaBruteForce(vector<int>& height) {\n        int n = height.size();\n        int maxArea = 0;\n\n        // Check all pairs (i, j)\n        for (int i = 0; i < n; i++) {\n            for (int j = i + 1; j < n; j++) {\n                // Compute the minimum height and width\n                int minHeight = min(height[i], height[j]);\n                int width = j - i;\n                int area = minHeight * width; // Compute water contained\n\n                maxArea = max(maxArea, area); // Update max water\n            }\n        }\n        return maxArea;\n    }\n\n    // Two Pointers approach for Container with Most Water\n    int maxAreaTwoPointers(vector<int>& height) {\n        int left = 0, right = height.size() - 1;\n        int maxArea = 0;\n\n        // Move pointers toward each other\n        while (left < right) {\n            int width = right - left; // Distance between lines\n            int minHeight = min(height[left], height[right]); // Compute height\n            int area = minHeight * width; // Compute water contained\n\n            maxArea = max(maxArea, area); // Update max water\n\n            // Move the pointer pointing to the shorter height\n            if (height[left] < height[right]) {\n                left++; // Move left pointer forward\n            } else {\n                right--; // Move right pointer backward\n            }\n        }\n        return maxArea;\n    }\n};"
  },
  {
    "path": "patterns/go/fast_and_slow_pointers.go",
    "content": "package main\n\nimport \"fmt\"\n\ntype ListNode struct {\n    Val  int\n    Next *ListNode\n}\n\n// LeetCode 141 - Linked List Cycle (HashSet Approach)\nfunc hasCycleHashSetApproach(head *ListNode) bool {\n    visited := map[*ListNode]bool{}\n    current := head\n    for current != nil {\n        if visited[current] {\n            return true\n        }\n        visited[current] = true\n        current = current.Next\n    }\n    return false\n}\n\n// LeetCode 141 - Linked List Cycle (Fast and Slow Pointer Approach)\nfunc hasCycleFastAndSlowPointersApproach(head *ListNode) bool {\n    if head == nil || head.Next == nil {\n        return false\n    }\n    slow, fast := head, head\n    for fast != nil && fast.Next != nil {\n        slow = slow.Next\n        fast = fast.Next.Next\n        if slow == fast {\n            return true\n        }\n    }\n    return false\n}\n\n// LeetCode 876 - Middle of the Linked List (Counting Approach)\nfunc middleNodeCountingApproach(head *ListNode) *ListNode {\n    count := 0\n    current := head\n    for current != nil {\n        count++\n        current = current.Next\n    }\n    current = head\n    for i := 0; i < count/2; i++ {\n        current = current.Next\n    }\n    return current\n}\n\n// LeetCode 876 - Middle of the Linked List (Fast and Slow Pointer Approach)\nfunc middleNodeFastAndSlowPointerApproach(head *ListNode) *ListNode {\n    slow, fast := head, head\n    for fast != nil && fast.Next != nil {\n        slow = slow.Next\n        fast = fast.Next.Next\n    }\n    return slow\n}\n\n// LeetCode 202 - Happy Number (HashSet Approach)\nfunc getSumOfSquares(n int) int {\n    sum := 0\n    for n > 0 {\n        digit := n % 10\n        sum += digit * digit\n        n /= 10\n    }\n    return sum\n}\n\nfunc isHappyHashSetApproach(n int) bool {\n    seen := map[int]bool{}\n    for n != 1 && !seen[n] {\n        seen[n] = true\n        n = getSumOfSquares(n)\n    }\n    return n == 1\n}\n\n// LeetCode 202 - Happy Number (Fast and Slow Pointer Approach)\nfunc isHappyFastAndSlowPointersApproach(n int) bool {\n    slow := n\n    fast := getSumOfSquares(n)\n    for fast != 1 && slow != fast {\n        slow = getSumOfSquares(slow)\n        fast = getSumOfSquares(getSumOfSquares(fast))\n    }\n    return fast == 1\n}\n\nfunc main() {\n    // You can test the implementations here\n}"
  },
  {
    "path": "patterns/go/kadane_algorithm.go",
    "content": "package main\n\nimport \"math\"\n\nfunc maxSubArray(nums []int) int {\n\tcurrentSum := nums[0]\n\tmaxSum := nums[0]\n\n\tfor i := 1; i < len(nums); i++ {\n\t\tcurrentSum = int(math.Max(float64(nums[i]), float64(currentSum+nums[i])))\n\t\tmaxSum = int(math.Max(float64(maxSum), float64(currentSum)))\n\t}\n\n\treturn maxSum\n}\n"
  },
  {
    "path": "patterns/go/level_order_traversal.go",
    "content": "package main\n\nimport \"fmt\"\n\n// Definition for a binary tree node.\ntype TreeNode struct {\n    Val   int\n    Left  *TreeNode\n    Right *TreeNode\n}\n\nfunc levelOrder(root *TreeNode) {\n    if root == nil {\n        return\n    }\n\n    queue := []*TreeNode{root}\n\n    for len(queue) > 0 {\n        node := queue[0]\n        queue = queue[1:]\n        fmt.Print(node.Val, \" \") // Process the node by printing its value\n        \n        // Add the left and right children to the queue, if they exist\n        if node.Left != nil {\n            queue = append(queue, node.Left)\n        }\n        if node.Right != nil {\n            queue = append(queue, node.Right)\n    }\n}\n\nfunc main() {\n    // Example usage\n    root := &TreeNode{Val: 1}\n    root.Left = &TreeNode{Val: 2}\n    root.Right = &TreeNode{Val: 3}\n    levelOrder(root) // Output: 1 2 3\n}"
  },
  {
    "path": "patterns/go/monotonic_stack.go",
    "content": "package main\n\nimport \"fmt\"\n\nfunc nextGreaterElement(nums []int) []int {\n\tn := len(nums)\n\tresult := make([]int, n)\n\tfor i := range result {\n\t\tresult[i] = -1 // Default to -1 if no greater element exists\n\t}\n\tstack := []int{} // Stack stores indices\n\n\tfor i := 0; i < n; i++ {\n\t\tfor len(stack) > 0 && nums[i] > nums[stack[len(stack)-1]] {\n\t\t\tindex := stack[len(stack)-1]\n\t\t\tstack = stack[:len(stack)-1]\n\t\t\tresult[index] = nums[i]\n\t\t}\n\t\tstack = append(stack, i)\n\t}\n\treturn result\n}\n\nfunc dailyTemperatures(temperatures []int) []int {\n\tn := len(temperatures)\n\tresult := make([]int, n) // Result array initialized with 0s\n\tstack := []int{}         // Monotonic decreasing stack\n\n\tfor i := 0; i < n; i++ {\n\t\tfor len(stack) > 0 && temperatures[i] > temperatures[stack[len(stack)-1]] {\n\t\t\tprevIndex := stack[len(stack)-1]\n\t\t\tstack = stack[:len(stack)-1]\n\t\t\tresult[prevIndex] = i - prevIndex\n\t\t}\n\t\tstack = append(stack, i)\n\t}\n\treturn result\n}\n\nfunc main() {\n\tnums := []int{2, 1, 5, 6, 2, 3}\n\tfmt.Println(nextGreaterElement(nums))\n\n\ttemperatures := []int{73, 74, 75, 71, 69, 72, 76, 73}\n\tfmt.Println(dailyTemperatures(temperatures))\n}\n"
  },
  {
    "path": "patterns/go/reverse_list.go",
    "content": "package main\n\ntype ListNode struct {\n\tVal  int\n\tNext *ListNode\n}\n\nfunc reverseList(head *ListNode) *ListNode {\n\tvar prev *ListNode = nil\n\tcurr := head\n\n\tfor curr != nil {\n\t\tnext := curr.Next\n\t\tcurr.Next = prev\n\t\tprev = curr\n\t\tcurr = next\n\t}\n\treturn prev\n}\n"
  },
  {
    "path": "patterns/go/sliding_window.go",
    "content": "package main\n\nimport (\n\t\"math\"\n)\n\n// Brute Force Approach - O(n * k)\nfunc findMaxAverageBruteForce(nums []int, k int) float64 {\n\tn := len(nums)\n\tmaxAvg := math.Inf(-1)\n\n\tfor i := 0; i <= n-k; i++ {\n\t\tsum := 0\n\t\tfor j := i; j < i+k; j++ {\n\t\t\tsum += nums[j]\n\t\t}\n\t\tmaxAvg = math.Max(maxAvg, float64(sum)/float64(k))\n\t}\n\treturn maxAvg\n}\n\n// Sliding Window Approach - O(n)\nfunc findMaxAverageSlidingWindow(nums []int, k int) float64 {\n\tsum := 0\n\tfor i := 0; i < k; i++ {\n\t\tsum += nums[i]\n\t}\n\n\tmaxSum := sum\n\n\tfor i := k; i < len(nums); i++ {\n\t\tsum += nums[i] - nums[i-k]\n\t\tif sum > maxSum {\n\t\t\tmaxSum = sum\n\t\t}\n\t}\n\n\treturn float64(maxSum) / float64(k)\n}\n\n// Sliding Window for Longest Substring Without Repeating Characters\nfunc lengthOfLongestSubstringSlidingWindow(s string) int {\n\tseen := make(map[byte]bool)\n\tmaxLength, left := 0, 0\n\n\tfor right := 0; right < len(s); right++ {\n\t\tfor seen[s[right]] {\n\t\t\tdelete(seen, s[left])\n\t\t\tleft++\n\t\t}\n\t\tseen[s[right]] = true\n\t\tmaxLength = max(maxLength, right-left+1)\n\t}\n\treturn maxLength\n}\n\n// Sliding Window using Frequency Array\nfunc lengthOfLongestSubstringSlidingWindowFrequencyArray(s string) int {\n\tfreq := make([]int, 128)\n\tmaxLength, left := 0, 0\n\n\tfor right := 0; right < len(s); right++ {\n\t\tfreq[s[right]]++\n\n\t\tfor freq[s[right]] > 1 {\n\t\t\tfreq[s[left]]--\n\t\t\tleft++\n\t\t}\n\n\t\tmaxLength = max(maxLength, right-left+1)\n\t}\n\treturn maxLength\n}\n\n// Helper function to get max of two numbers\nfunc max(a, b int) int {\n\tif a > b {\n\t\treturn a\n\t}\n\treturn b\n}\n"
  },
  {
    "path": "patterns/go/top_k_elements.go",
    "content": "package main\n\nimport (\n\t\"container/heap\"\n\t\"sort\"\n)\n\n// ********** K Largest Elements **********\n// K Largest Elements using Sorting\nfunc kLargestElementsSortingApproach(nums []int, k int) []int {\n\tsort.Sort(sort.Reverse(sort.IntSlice(nums)))\n\treturn nums[:k]\n}\n\n// K Largest Elements using Max Heap\nfunc kLargestElementsMaxHeapApproach(nums []int, k int) []int {\n\th := &MaxHeap{}\n\theap.Init(h)\n\tfor _, num := range nums {\n\t\theap.Push(h, num)\n\t}\n\tresult := make([]int, k)\n\tfor i := 0; i < k; i++ {\n\t\tresult[i] = heap.Pop(h).(int)\n\t}\n\treturn result\n}\n\n// K Largest Elements using Min Heap\nfunc kLargestElementsMinHeapApproach(nums []int, k int) []int {\n\th := &MinHeap{}\n\theap.Init(h)\n\tfor i := 0; i < k; i++ {\n\t\theap.Push(h, nums[i])\n\t}\n\tfor i := k; i < len(nums); i++ {\n\t\theap.Push(h, nums[i])\n\t\tif h.Len() > k {\n\t\t\theap.Pop(h)\n\t\t}\n\t}\n\tresult := make([]int, k)\n\tfor i := 0; i < k; i++ {\n\t\tresult[i] = heap.Pop(h).(int)\n\t}\n\treturn result\n}\n\n// ********** Helper Structures **********\n\ntype MaxHeap []int\ntype MinHeap []int\n\nfunc (h MaxHeap) Len() int            { return len(h) }\nfunc (h MaxHeap) Less(i, j int) bool  { return h[i] > h[j] } // Max heap\nfunc (h MaxHeap) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }\nfunc (h *MaxHeap) Push(x interface{}) { *h = append(*h, x.(int)) }\nfunc (h *MaxHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}\n\nfunc (h MinHeap) Len() int            { return len(h) }\nfunc (h MinHeap) Less(i, j int) bool  { return h[i] < h[j] } // Min heap\nfunc (h MinHeap) Swap(i, j int)       { h[i], h[j] = h[j], h[i] }\nfunc (h *MinHeap) Push(x interface{}) { *h = append(*h, x.(int)) }\nfunc (h *MinHeap) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}\n\n// ********** Main **********\n\nfunc main() {\n\t// Example test cases\n\tnums := []int{3, 2, 1, 5, 6, 4}\n\tk := 2\n\n\t// Sorting Approach\n\tresult := kLargestElementsSortingApproach(nums, k)\n\tfmt.Println(\"K Largest Elements (Sorting Approach):\", result)\n\n\t// Max Heap Approach\n\tresult = kLargestElementsMaxHeapApproach(nums, k)\n\tfmt.Println(\"K Largest Elements (Max Heap Approach):\", result)\n\n\t// Min Heap Approach\n\tresult = kLargestElementsMinHeapApproach(nums, k)\n\tfmt.Println(\"K Largest Elements (Min Heap Approach):\", result)\n}"
  },
  {
    "path": "patterns/go/two_pointers.go",
    "content": "package main\n\n// Move Zeroes using Two Pointers\nfunc moveZeroesTwoPointers(nums []int) {\n\tleft := 0 // Pointer for placing non-zero elements\n\n\t// Iterate with right pointer\n\tfor right := 0; right < len(nums); right++ {\n\t\tif nums[right] != 0 {\n\t\t\t// Swap elements if right pointer finds a non-zero\n\t\t\tnums[left], nums[right] = nums[right], nums[left]\n\t\t\tleft++ // Move left pointer forward\n\t\t}\n\t}\n}\n\n// Brute Force approach for Container with Most Water\nfunc maxAreaBruteForce(height []int) int {\n\tn := len(height)\n\tmaxArea := 0\n\n\t// Check all pairs (i, j)\n\tfor i := 0; i < n; i++ {\n\t\tfor j := i + 1; j < n; j++ {\n\t\t\t// Compute the minimum height and width\n\t\t\tminHeight := min(height[i], height[j])\n\t\t\twidth := j - i\n\t\t\tarea := minHeight * width // Compute water contained\n\n\t\t\tif area > maxArea {\n\t\t\t\tmaxArea = area // Update max water\n\t\t\t}\n\t\t}\n\t}\n\treturn maxArea\n}\n\n// Two Pointers approach for Container with Most Water\nfunc maxAreaTwoPointers(height []int) int {\n\tleft, right := 0, len(height)-1\n\tmaxArea := 0\n\n\t// Move pointers toward each other\n\tfor left < right {\n\t\twidth := right - left                         // Distance between lines\n\t\tminHeight := min(height[left], height[right]) // Compute height\n\t\tarea := minHeight * width                     // Compute water contained\n\n\t\tif area > maxArea {\n\t\t\tmaxArea = area // Update max water\n\t\t}\n\n\t\t// Move the pointer pointing to the shorter height\n\t\tif height[left] < height[right] {\n\t\t\tleft++ // Move left pointer forward\n\t\t} else {\n\t\t\tright-- // Move right pointer backward\n\t\t}\n\t}\n\treturn maxArea\n}\n\n// Helper function to return the minimum of two integers\nfunc min(a, b int) int {\n\tif a < b {\n\t\treturn a\n\t}\n\treturn b\n}\n"
  },
  {
    "path": "patterns/java/FastAndSlowPointers.java",
    "content": "package patterns.java;\n\nimport java.util.HashSet;\n\npublic class FastAndSlowPointers {\n\n    class ListNode {\n        int val;\n        ListNode next;\n        ListNode(int x) {\n            val = x;\n            next = null;\n        }\n    }\n\n/*\n * ********** LeetCode 141 - Linked List Cycle (https://leetcode.com/problems/linked-list-cycle/) **********\n*/    \n    \n    public boolean hasCycleHashSetAppraoch(ListNode head) {\n        HashSet<ListNode> visited = new HashSet<>();\n        ListNode current = head;\n        while (current != null) {\n            if (visited.contains(current)) {\n                return true; // Cycle detected\n            }\n            visited.add(current);\n            current = current.next;\n        }\n        return false; // No cycle\n    }\n\n    public boolean hasCycleFastAndSlowPointersAppraoch(ListNode head) {\n        if (head == null || head.next == null) {\n            return false; // No cycle if the list is empty or has only one node\n        }\n\n        ListNode slow = head;\n        ListNode fast = head;\n\n        while (fast != null && fast.next != null) {\n            slow = slow.next;        // Move slow pointer by 1 step\n            fast = fast.next.next;   // Move fast pointer by 2 steps\n\n            if (slow == fast) {\n                return true; // Cycle detected\n            }\n        }\n\n        return false; // No cycle\n    }\n\n/*\n * ********** LeetCode 876 - Middle of the Linked List (https://leetcode.com/problems/middle-of-the-linked-list/description/) **********\n*/\n\n    public ListNode middleNodeCountingApproach(ListNode head) {\n        int count = 0;\n        ListNode current = head;\n\n        // First pass to count the number of nodes\n        while (current != null) {\n            count++;\n            current = current.next;\n        }\n\n        // Second pass to find the middle node\n        current = head;\n        for (int i = 0; i < count / 2; i++) {\n            current = current.next;\n        }\n\n        return current; // This will be the middle node\n    }\n\n    public ListNode middleNodeFastAndSlowPointerApproach(ListNode head) {\n        ListNode slow = head;\n        ListNode fast = head;\n\n        // Move slow by 1 and fast by 2 steps\n        while (fast != null && fast.next != null) {\n            slow = slow.next;\n            fast = fast.next.next;\n        }\n\n        return slow; // Slow will be at the middle node\n    }\n\n/*\n * ********** LeetCode 202 - Happy Number (https://leetcode.com/problems/happy-number/description/) **********\n*/\n\n    private int getSumOfSquares(int n) {\n        int sum = 0;\n        while (n > 0) {\n            int digit = n % 10;\n            sum += digit * digit;\n            n /= 10;\n        }\n        return sum;\n    }\n\n    public boolean isHappyHashSetApproach(int n) {\n        HashSet<Integer> seen = new HashSet<>();\n        while (n != 1 && !seen.contains(n)) {\n            seen.add(n);\n            n = getSumOfSquares(n);\n        }\n        return n == 1;\n    }\n\n    public boolean isHappyFastAndSlowPointersApproach(int n) {\n        int slow = n;\n        int fast = getSumOfSquares(n);\n\n        while (fast != 1 && slow != fast) {\n            slow = getSumOfSquares(slow);        // Move slow by 1 step\n            fast = getSumOfSquares(getSumOfSquares(fast)); // Move fast by 2 steps\n        }\n\n        return fast == 1;\n    }\n}"
  },
  {
    "path": "patterns/java/KadaneAlgorithm.java",
    "content": "package patterns.java;\n\npublic class KadaneAlgorithm {\n    public int maxSubArray(int[] nums) {\n        int currentSum = nums[0]; // Start with the first element\n        int maxSum = nums[0];     // Initialize maxSum with the first element\n\n        // Traverse the array from the second element\n        for (int i = 1; i < nums.length; i++) {\n            // If currentSum is negative, reset to current element\n            currentSum = Math.max(nums[i], currentSum + nums[i]);\n            // Update maxSum if currentSum is greater\n            maxSum = Math.max(maxSum, currentSum);\n        }\n        return maxSum;\n    }    \n}"
  },
  {
    "path": "patterns/java/LevelOrderTraversal.java",
    "content": "package patterns.java;\n\nimport java.util.LinkedList;\nimport java.util.Queue;\n\n// Definition for a binary tree node.\nclass TreeNode {\n    int val;\n    TreeNode left;\n    TreeNode right;\n    \n    TreeNode(int x) { \n        val = x; \n    }\n}\n\npublic class LevelOrderTraversal {\n    public void levelOrder(TreeNode root) {\n        if (root == null) return;\n\n        Queue<TreeNode> queue = new LinkedList<>();\n        queue.add(root);\n\n        while (!queue.isEmpty()) {\n            TreeNode node = queue.poll();\n            System.out.print(node.val + \" \"); // Process the node by printing its value\n            \n            // Add the left and right children to the queue, if they exist\n            if (node.left != null) queue.add(node.left);\n            if (node.right != null) queue.add(node.right);\n        }\n    }\n}\n"
  },
  {
    "path": "patterns/java/MonotonicStack.java",
    "content": "package patterns.java;\n\nimport java.util.Arrays;\nimport java.util.Stack;\n\npublic class MonotonicStack {\n\n    public int[] nextGreaterElement(int[] nums) {\n        int n = nums.length;\n        int[] result = new int[n]; // Output array\n        Arrays.fill(result, -1); // Default to -1 if no greater element exists\n        Stack<Integer> stack = new Stack<>(); // Stack stores indices\n\n        // Iterate through the array\n        for (int i = 0; i < n; i++) {\n            // While stack is not empty and current element is greater than stack top\n            while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) {\n                int index = stack.pop(); // Pop the top element\n                result[index] = nums[i]; // The current element is the Next Greater Element\n            }\n            stack.push(i); // Push the current index onto the stack\n        }\n        return result;\n    }\n\n    public int[] dailyTemperatures(int[] temperatures) {\n        int n = temperatures.length;\n        int[] result = new int[n]; // Result array initialized with 0s\n        Stack<Integer> stack = new Stack<>(); // Monotonic decreasing stack (stores indices)\n\n        // Iterate through the temperature array\n        for (int i = 0; i < n; i++) {\n            // While stack is not empty AND the current temperature is warmer than the temperature at stack top\n            while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {\n                int prevIndex = stack.pop(); // Pop the previous day's index\n                result[prevIndex] = i - prevIndex; // Calculate the wait time\n            }\n            stack.push(i); // Push current index onto the stack\n        }\n\n        return result; // Return the computed results\n    }    \n}"
  },
  {
    "path": "patterns/java/ReverseLinkedList.java",
    "content": "package patterns.java;\n\nclass ListNode {\n    int val;\n    ListNode next;\n}\n\npublic class ReverseLinkedList {\n    public ListNode reverseList(ListNode head) {\n        ListNode prev = null; // Previous node, initially null\n        ListNode curr = head; // Current node starts from the head\n        while (curr != null) {\n            ListNode next = curr.next; // Store next node\n            curr.next = prev; // Reverse the current node's pointer\n            prev = curr; // Move prev to current\n            curr = next; // Move curr to next\n        }\n        return prev; // New head of the reversed list\n    }    \n}\n"
  },
  {
    "path": "patterns/java/SlidingWindow.java",
    "content": "package patterns.java;\n\nimport java.util.HashSet;\n\npublic class SlidingWindow {\n    public double findMaxAverageBruteForce(int[] nums, int k) {\n        int n = nums.length;\n        double maxAvg = Integer.MIN_VALUE;\n\n        // Iterate through all possible subarrays of length k\n        for (int i = 0; i <= n - k; i++) {\n            int sum = 0;\n\n            // Calculate sum of subarray starting at index i\n            for (int j = i; j < i + k; j++) {\n                sum += nums[j];\n            }\n\n            // Compute average and update maxAvg\n            maxAvg = Math.max(maxAvg, (double) sum / k);\n        }\n        return maxAvg;\n    }\n\n    public double findMaxAverageSlidingWindow(int[] nums, int k) {\n        int n = nums.length;\n        \n        // Compute the sum of the first 'k' elements\n        int sum = 0;\n        for (int i = 0; i < k; i++) {\n            sum += nums[i];\n        }\n        \n        // Initialize maxSum as the sum of the first window\n        int maxSum = sum;\n\n        // Slide the window across the array\n        for (int i = k; i < n; i++) {\n            sum += nums[i];      // Add new element entering window\n            sum -= nums[i - k];  // Remove element leaving window\n            maxSum = Math.max(maxSum, sum); // Update maxSum\n        }\n        \n        // Return maximum average\n        return (double) maxSum / k;\n    }\n\n    public int lengthOfLongestSubstringSlidingWindow(String s) {\n        int n = s.length();\n        HashSet<Character> seen = new HashSet<>(); // Store characters in the current window\n        int maxLength = 0;\n        int left = 0;        \n\n        // Expand window by moving 'right'\n        for (int right = 0; right < n; right++) {\n            // If a duplicate is found, shrink the window from the left\n            while (seen.contains(s.charAt(right))) {\n                seen.remove(s.charAt(left));\n                left++;\n            }\n            // Add current character to window and update max length\n            seen.add(s.charAt(right));\n            maxLength = Math.max(maxLength, right - left + 1);\n        }\n        return maxLength;\n    }\n\n    public int lengthOfLongestSubstringSlidingWindowFrequencyArray(String s) {\n        int n = s.length();\n        int[] freq = new int[128]; // ASCII character frequency array\n        int maxLength = 0;\n        int left = 0;        \n\n        // Expand window by moving 'right'\n        for (int right = 0; right < n; right++) {\n            char currentChar = s.charAt(right);\n            freq[currentChar]++; // Increase frequency of the current character\n\n            // If there is a duplicate, shrink the window from the left\n            while (freq[currentChar] > 1) {\n                freq[s.charAt(left)]--; // Remove character at left pointer\n                left++; // Shrink window\n            }\n\n            // Update maximum window size\n            maxLength = Math.max(maxLength, right - left + 1);\n        }\n        return maxLength;\n    }    \n}"
  },
  {
    "path": "patterns/java/TopKElements.java",
    "content": "package patterns.java;\n\nimport patterns.java.FastAndSlowPointers.ListNode;\nimport java.util.*;\n\npublic class TopKElements {\n\n    /*\n    * ********** K Largest Elements **********\n    */\n    \n    public int[] kLargestElementsSortingAppraoch(int[] nums, int k) {\n        // Step 1: Sort the array in descending order\n        Integer[] numsArray = Arrays.stream(nums).boxed().toArray(Integer[]::new);\n        Arrays.sort(numsArray, Collections.reverseOrder());\n\n        // Step 2: Extract the first K elements\n        int[] result = new int[k];\n        for (int i = 0; i < k; i++) {\n            result[i] = numsArray[i];\n        }\n        return result;\n    }\n\n    public int[] kLargestElementsMaxHeapAppraoch(int[] nums, int k) {\n        // Max heap\n        PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());\n\n        // Add all numbers to the max heap\n        for (int num : nums) {\n            maxHeap.add(num);\n        }\n\n        // Extract the top K largest elements\n        int[] result = new int[k];\n        for (int i = 0; i < k; i++) {\n            result[i] = maxHeap.poll();  // Extracts the largest element\n        }\n        return result;\n    }\n\n    public int[] kLargestElementsMinHeapAppraoch(int[] nums, int k) {\n        // Min heap\n        PriorityQueue<Integer> minHeap = new PriorityQueue<>();\n\n        // Add first K elements into the min heap\n        for(int i = 0; i < k; i++) {\n            minHeap.add(nums[i]);\n        }\n\n        // Process the remaining elements\n        for (int i = k; i < nums.length; i++) {\n            minHeap.add(nums[i]);\n            if (minHeap.size() > k) {\n                minHeap.poll();\n            }\n        }\n\n        // Extract the top K largest elements from the min heap\n        int[] result = new int[k];\n        for (int i = 0; i < k; i++) {\n            result[i] = minHeap.poll();\n        }\n        return result;\n    }\n\n    /*\n    * ********** LeetCode 347 - Top K Frequent Elements (https://leetcode.com/problems/top-k-frequent-elements/description/) **********\n    */\n\n    public int[] topKFrequentElementsSortingApproach(int[] nums, int k) {\n        // Step 1: Build the frequency map\n        Map<Integer, Integer> frequencyMap = new HashMap<>();\n        for (int num : nums) {\n            frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);\n        }\n\n        // Step 2: Sort the entries by frequency in descending order\n        List<Map.Entry<Integer, Integer>> entryList = new ArrayList<>(frequencyMap.entrySet());\n        entryList.sort((a, b) -> b.getValue() - a.getValue());\n\n        // Step 3: Extract the top K elements\n        int[] result = new int[k];\n        for (int i = 0; i < k; i++) {\n            result[i] = entryList.get(i).getKey();\n        }\n\n        return result;\n    }\n\n    public int[] topKFrequentElementsMinHeapApproach(int[] nums, int k) {\n        // Step 1: Build the frequency map\n        Map<Integer, Integer> frequencyMap = new HashMap<>();\n        for (int num : nums) {\n            frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);\n        }\n\n        // Step 2: Use a min heap to keep track of the top K elements\n        PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>(\n            (a, b) -> a.getValue() - b.getValue()  // Compare by frequency\n        );\n\n        // Step 3: Add each entry to the heap, and maintain size K\n        for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {\n            minHeap.add(entry);\n            if (minHeap.size() > k) {\n                minHeap.poll();  // Remove the element with the lowest frequency\n            }\n        }\n\n        // Step 4: Extract the elements from the heap\n        int[] result = new int[k];\n        for (int i = 0; i < k; i++) {\n            result[i] = minHeap.poll().getKey();  // Get the element (key) from the heap\n        }\n\n        return result;\n    }\n\n    /*\n    * ********** LeetCode 973 - K Closest Points to Origin (https://leetcode.com/problems/k-closest-points-to-origin/description/) **********\n    */\n    private int getDistance(int[] point) {\n        return point[0] * point[0] + point[1] * point[1];  // Squared distance to avoid floating-point operations\n    }\n\n    public int[][] kClosestPointsToOriginMaxHeapApproach(int[][] points, int k) {\n        // Max heap with custom comparator to compare by distance\n        PriorityQueue<int[]> maxHeap = new PriorityQueue<>(\n            (a, b) -> Integer.compare(getDistance(b), getDistance(a))\n        );\n\n        // Iterate through all points\n        for (int[] point : points) {\n            maxHeap.add(point);  // Add the current point to the heap\n\n            // If the heap exceeds size K, remove the farthest point\n            if (maxHeap.size() > k) {\n                maxHeap.poll();  // Remove the point with the largest distance (root of max heap)\n            }\n        }\n\n        // Convert the remaining points in the heap to the result array\n        int[][] result = new int[k][2];\n        for (int i = 0; i < k; i++) {\n            result[i] = maxHeap.poll();\n        }\n\n        return result;\n    }\n}\n"
  },
  {
    "path": "patterns/java/TwoPointers.java",
    "content": "package patterns.java;\n\npublic class TwoPointers {\n\n    public void moveZeroesTwoPointers(int[] nums) {\n        int left = 0; // Pointer for placing non-zero elements\n\n        // Iterate with right pointer\n        for (int right = 0; right < nums.length; right++) {\n            if (nums[right] != 0) {\n                // Swap elements if right pointer finds a non-zero\n                int temp = nums[left];\n                nums[left] = nums[right];\n                nums[right] = temp;\n                left++; // Move left pointer forward\n            }\n        }\n    }\n\n    public int maxAreaBruteForce(int[] height) {\n        int n = height.length;\n        int maxArea = 0;\n\n        // Check all pairs (i, j)\n        for (int i = 0; i < n; i++) {\n            for (int j = i + 1; j < n; j++) {\n                // Height of the container\n                int minHeight = Math.min(height[i], height[j]);\n                int width = j - i; // Distance between lines\n                int area = minHeight * width; // Compute water contained\n\n                maxArea = Math.max(maxArea, area); // Update max water\n            }\n        }\n        return maxArea;\n    }\n\n    public int maxAreaTwoPointers(int[] height) {\n        int left = 0, right = height.length - 1;\n        int maxArea = 0;\n\n        // Move pointers toward each other\n        while (left <= right) {\n            int width = right - left; // Distance between lines\n            int minHeight = Math.min(height[left], height[right]);\n            int area = minHeight * width; // Compute water contained\n\n            maxArea = Math.max(maxArea, area); // Update max water\n\n            // Move the pointer pointing to the shorter height\n            if (height[left] < height[right]) {\n                left++; // Move left pointer forward\n            } else {\n                right--; // Move right pointer backward\n            }\n        }\n        return maxArea;\n    }    \n}"
  },
  {
    "path": "patterns/javascript/fastAndSlowPointers.js",
    "content": "class ListNode {\n    constructor(x) {\n        this.val = x;\n        this.next = null;\n    }\n}\n\nclass FastAndSlowPointers {\n    // LeetCode 141 - Linked List Cycle (HashSet Approach)\n    hasCycleHashSetApproach(head) {\n        const visited = new Set();\n        let current = head;\n        while (current) {\n            if (visited.has(current)) {\n                return true;\n            }\n            visited.add(current);\n            current = current.next;\n        }\n        return false;\n    }\n\n    // LeetCode 141 - Linked List Cycle (Fast and Slow Pointer Approach)\n    hasCycleFastAndSlowPointersApproach(head) {\n        if (!head || !head.next) return false;\n        let slow = head, fast = head;\n        while (fast && fast.next) {\n            slow = slow.next;\n            fast = fast.next.next;\n            if (slow === fast) return true;\n        }\n        return false;\n    }\n\n    // LeetCode 876 - Middle of the Linked List (Counting Approach)\n    middleNodeCountingApproach(head) {\n        let count = 0;\n        let current = head;\n        while (current) {\n            count++;\n            current = current.next;\n        }\n        current = head;\n        for (let i = 0; i < Math.floor(count / 2); i++) {\n            current = current.next;\n        }\n        return current;\n    }\n\n    // LeetCode 876 - Middle of the Linked List (Fast and Slow Pointer Approach)\n    middleNodeFastAndSlowPointerApproach(head) {\n        let slow = head, fast = head;\n        while (fast && fast.next) {\n            slow = slow.next;\n            fast = fast.next.next;\n        }\n        return slow;\n    }\n\n    // LeetCode 202 - Happy Number (HashSet Approach)\n    getSumOfSquares(n) {\n        return String(n).split('').reduce((sum, digit) => sum + digit * digit, 0);\n    }\n\n    isHappyHashSetApproach(n) {\n        const seen = new Set();\n        while (n !== 1 && !seen.has(n)) {\n            seen.add(n);\n            n = this.getSumOfSquares(n);\n        }\n        return n === 1;\n    }\n\n    // LeetCode 202 - Happy Number (Fast and Slow Pointer Approach)\n    isHappyFastAndSlowPointersApproach(n) {\n        let slow = n;\n        let fast = this.getSumOfSquares(n);\n        while (fast !== 1 && slow !== fast) {\n            slow = this.getSumOfSquares(slow);\n            fast = this.getSumOfSquares(this.getSumOfSquares(fast));\n        }\n        return fast === 1;\n    }\n}"
  },
  {
    "path": "patterns/javascript/kadaneAlgorithm.js",
    "content": "class KadaneAlgorithm {\n    maxSubArray(nums) {\n        let currentSum = nums[0];\n        let maxSum = nums[0];\n\n        for (let i = 1; i < nums.length; i++) {\n            currentSum = Math.max(nums[i], currentSum + nums[i]);\n            maxSum = Math.max(maxSum, currentSum);\n        }\n        return maxSum;\n    }\n}"
  },
  {
    "path": "patterns/javascript/levelOrderTraversal.js",
    "content": "// Definition for a binary tree node.\nclass TreeNode {\n    constructor(val) {\n        this.val = val;\n        this.left = this.right = null;\n    }\n}\n\nclass LevelOrderTraversal {\n    levelOrder(root) {\n        if (root === null) return;\n\n        const queue = [root];\n\n        while (queue.length > 0) {\n            const node = queue.shift();\n            console.log(node.val); // Process the node by printing its value\n            \n            // Add the left and right children to the queue, if they exist\n            if (node.left !== null) queue.push(node.left);\n            if (node.right !== null) queue.push(node.right);\n        }\n    }\n}"
  },
  {
    "path": "patterns/javascript/monotonicStack.js",
    "content": "class MonotonicStack {\n    nextGreaterElement(nums) {\n        let n = nums.length;\n        let result = new Array(n).fill(-1); // Default to -1 if no greater element exists\n        let stack = []; // Stack stores indices\n\n        for (let i = 0; i < n; i++) {\n            while (stack.length > 0 && nums[i] > nums[stack[stack.length - 1]]) {\n                let index = stack.pop();\n                result[index] = nums[i];\n            }\n            stack.push(i);\n        }\n        return result;\n    }\n\n    dailyTemperatures(temperatures) {\n        let n = temperatures.length;\n        let result = new Array(n).fill(0); // Result array initialized with 0s\n        let stack = []; // Monotonic decreasing stack\n\n        for (let i = 0; i < n; i++) {\n            while (stack.length > 0 && temperatures[i] > temperatures[stack[stack.length - 1]]) {\n                let prevIndex = stack.pop();\n                result[prevIndex] = i - prevIndex;\n            }\n            stack.push(i);\n        }\n        return result;\n    }\n}"
  },
  {
    "path": "patterns/javascript/reverseList.js",
    "content": "class ListNode {\n    constructor(val = 0, next = null) {\n        this.val = val;\n        this.next = next;\n    }\n}\n\nfunction reverseList(head) {\n    let prev = null;\n    let curr = head;\n\n    while (curr !== null) {\n        let next = curr.next;\n        curr.next = prev;\n        prev = curr;\n        curr = next;\n    }\n    return prev;\n}"
  },
  {
    "path": "patterns/javascript/slidingWindow.js",
    "content": "class SlidingWindow {\n    // Brute Force Approach - O(n * k)\n    findMaxAverageBruteForce(nums, k) {\n        let maxAvg = -Infinity;\n\n        for (let i = 0; i <= nums.length - k; i++) {\n            let sum = 0;\n            for (let j = i; j < i + k; j++) {\n                sum += nums[j];\n            }\n            maxAvg = Math.max(maxAvg, sum / k);\n        }\n        return maxAvg;\n    }\n\n    // Sliding Window Approach - O(n)\n    findMaxAverageSlidingWindow(nums, k) {\n        let sum = nums.slice(0, k).reduce((a, b) => a + b, 0);\n        let maxSum = sum;\n\n        for (let i = k; i < nums.length; i++) {\n            sum += nums[i] - nums[i - k];\n            maxSum = Math.max(maxSum, sum);\n        }\n\n        return maxSum / k;\n    }\n\n    // Sliding Window for Longest Substring Without Repeating Characters\n    lengthOfLongestSubstringSlidingWindow(s) {\n        let seen = new Set();\n        let maxLength = 0, left = 0;\n\n        for (let right = 0; right < s.length; right++) {\n            while (seen.has(s[right])) {\n                seen.delete(s[left]);\n                left++;\n            }\n            seen.add(s[right]);\n            maxLength = Math.max(maxLength, right - left + 1);\n        }\n        return maxLength;\n    }\n\n    // Sliding Window using Frequency Array\n    lengthOfLongestSubstringSlidingWindowFrequencyArray(s) {\n        let freq = new Array(128).fill(0);\n        let maxLength = 0, left = 0;\n\n        for (let right = 0; right < s.length; right++) {\n            freq[s.charCodeAt(right)]++;\n\n            while (freq[s.charCodeAt(right)] > 1) {\n                freq[s.charCodeAt(left)]--;\n                left++;\n            }\n\n            maxLength = Math.max(maxLength, right - left + 1);\n        }\n        return maxLength;\n    }\n}"
  },
  {
    "path": "patterns/javascript/topKElements.js",
    "content": "class TopKElements {\n\n    // K Largest Elements using Sorting\n    kLargestElementsSortingApproach(nums, k) {\n        nums.sort((a, b) => b - a);\n        return nums.slice(0, k);\n    }\n\n    // K Largest Elements using Max Heap\n    kLargestElementsMaxHeapApproach(nums, k) {\n        const maxHeap = new MaxPriorityQueue({ priority: x => x });\n        for (const num of nums) {\n            maxHeap.enqueue(num);\n        }\n        const result = [];\n        for (let i = 0; i < k; i++) {\n            result.push(maxHeap.dequeue().element);\n        }\n        return result;\n    }\n\n    // K Largest Elements using Min Heap\n    kLargestElementsMinHeapApproach(nums, k) {\n        const minHeap = new MinPriorityQueue({ priority: x => x });\n        for (let i = 0; i < k; i++) {\n            minHeap.enqueue(nums[i]);\n        }\n        for (let i = k; i < nums.length; i++) {\n            minHeap.enqueue(nums[i]);\n            if (minHeap.size() > k) {\n                minHeap.dequeue();\n            }\n        }\n        const result = [];\n        for (let i = 0; i < k; i++) {\n            result.push(minHeap.dequeue().element);\n        }\n        return result;\n    }\n\n    // Top K Frequent Elements using Sorting\n    topKFrequentElementsSortingApproach(nums, k) {\n        const frequencyMap = new Map();\n        nums.forEach(num => frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1));\n        return Array.from(frequencyMap)\n            .sort((a, b) => b[1] - a[1])\n            .slice(0, k)\n            .map(entry => entry[0]);\n    }\n\n    // Top K Frequent Elements using Min Heap\n    topKFrequentElementsMinHeapApproach(nums, k) {\n        const frequencyMap = new Map();\n        nums.forEach(num => frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1));\n        const minHeap = new MinPriorityQueue({ priority: x => x[1] });\n        frequencyMap.forEach((value, key) => {\n            minHeap.enqueue([key, value]);\n            if (minHeap.size() > k) {\n                minHeap.dequeue();\n            }\n        });\n        const result = [];\n        for (let i = 0; i < k; i++) {\n            result.push(minHeap.dequeue().element[0]);\n        }\n        return result;\n    }\n\n    // K Closest Points to Origin using Max Heap\n    getDistance(point) {\n        return point[0] ** 2 + point[1] ** 2;\n    }\n\n    kClosestPointsToOriginMaxHeapApproach(points, k) {\n        const maxHeap = new MaxPriorityQueue({ priority: point => -this.getDistance(point) });\n        points.forEach(point => {\n            maxHeap.enqueue(point);\n            if (maxHeap.size() > k) {\n                maxHeap.dequeue();\n            }\n        });\n        const result = [];\n        for (let i = 0; i < k; i++) {\n            result.push(maxHeap.dequeue().element);\n        }\n        return result;\n    }\n}"
  },
  {
    "path": "patterns/javascript/twoPointers.js",
    "content": "class TwoPointers {\n    /**\n     * Move Zeroes using Two Pointers\n     * @param {number[]} nums - Input array\n     */\n    moveZeroesTwoPointers(nums) {\n        let left = 0; // Pointer for placing non-zero elements\n\n        // Iterate with right pointer\n        for (let right = 0; right < nums.length; right++) {\n            if (nums[right] !== 0) {\n                // Swap elements if right pointer finds a non-zero\n                [nums[left], nums[right]] = [nums[right], nums[left]];\n                left++; // Move left pointer forward\n            }\n        }\n    }\n\n    /**\n     * Brute Force approach for Container with Most Water\n     * @param {number[]} height - Array of heights\n     * @return {number} - Maximum water that can be contained\n     */\n    maxAreaBruteForce(height) {\n        let maxArea = 0;\n        let n = height.length;\n\n        // Check all pairs (i, j)\n        for (let i = 0; i < n; i++) {\n            for (let j = i + 1; j < n; j++) {\n                // Compute the minimum height and width\n                let minHeight = Math.min(height[i], height[j]);\n                let width = j - i;\n                let area = minHeight * width; // Compute water contained\n\n                maxArea = Math.max(maxArea, area); // Update max water\n            }\n        }\n        return maxArea;\n    }\n\n    /**\n     * Two Pointers approach for Container with Most Water\n     * @param {number[]} height - Array of heights\n     * @return {number} - Maximum water that can be contained\n     */\n    maxAreaTwoPointers(height) {\n        let left = 0, right = height.length - 1;\n        let maxArea = 0;\n\n        // Move pointers toward each other\n        while (left < right) {\n            let width = right - left; // Distance between lines\n            let minHeight = Math.min(height[left], height[right]); // Compute height\n            let area = minHeight * width; // Compute water contained\n\n            maxArea = Math.max(maxArea, area); // Update max water\n\n            // Move the pointer pointing to the shorter height\n            if (height[left] < height[right]) {\n                left++; // Move left pointer forward\n            } else {\n                right--; // Move right pointer backward\n            }\n        }\n        return maxArea;\n    }\n}"
  },
  {
    "path": "patterns/python/fast_and_slow_pointers.py",
    "content": "class ListNode:\n    def __init__(self, x):\n        self.val = x\n        self.next = None\n\nclass FastAndSlowPointers:\n    # LeetCode 141 - Linked List Cycle (HashSet Approach)\n    def hasCycleHashSetApproach(self, head):\n        visited = set()\n        current = head\n        while current:\n            if current in visited:\n                return True\n            visited.add(current)\n            current = current.next\n        return False\n\n    # LeetCode 141 - Linked List Cycle (Fast and Slow Pointer Approach)\n    def hasCycleFastAndSlowPointersApproach(self, head):\n        if not head or not head.next:\n            return False\n        slow, fast = head, head\n        while fast and fast.next:\n            slow = slow.next\n            fast = fast.next.next\n            if slow == fast:\n                return True\n        return False\n\n    # LeetCode 876 - Middle of the Linked List (Counting Approach)\n    def middleNodeCountingApproach(self, head):\n        count = 0\n        current = head\n        while current:\n            count += 1\n            current = current.next\n        current = head\n        for _ in range(count // 2):\n            current = current.next\n        return current\n\n    # LeetCode 876 - Middle of the Linked List (Fast and Slow Pointer Approach)\n    def middleNodeFastAndSlowPointerApproach(self, head):\n        slow, fast = head, head\n        while fast and fast.next:\n            slow = slow.next\n            fast = fast.next.next\n        return slow\n\n    # LeetCode 202 - Happy Number (HashSet Approach)\n    def getSumOfSquares(self, n):\n        return sum(int(digit)**2 for digit in str(n))\n\n    def isHappyHashSetApproach(self, n):\n        seen = set()\n        while n != 1 and n not in seen:\n            seen.add(n)\n            n = self.getSumOfSquares(n)\n        return n == 1\n\n    # LeetCode 202 - Happy Number (Fast and Slow Pointer Approach)\n    def isHappyFastAndSlowPointersApproach(self, n):\n        slow = n\n        fast = self.getSumOfSquares(n)\n        while fast != 1 and slow != fast:\n            slow = self.getSumOfSquares(slow)\n            fast = self.getSumOfSquares(self.getSumOfSquares(fast))\n        return fast == 1"
  },
  {
    "path": "patterns/python/kadane_algorithm.py",
    "content": "class KadaneAlgorithm:\n    def max_sub_array(self, nums):\n        current_sum = nums[0]\n        max_sum = nums[0]\n\n        for i in range(1, len(nums)):\n            current_sum = max(nums[i], current_sum + nums[i])\n            max_sum = max(max_sum, current_sum)\n        \n        return max_sum"
  },
  {
    "path": "patterns/python/level_order_traversal.py",
    "content": "from collections import deque\n\n# Definition for a binary tree node.\nclass TreeNode:\n    def __init__(self, x):\n        self.val = x\n        self.left = None\n        self.right = None\n\nclass LevelOrderTraversal:\n    def level_order(self, root):\n        if root is None:\n            return\n\n        queue = deque([root])\n\n        while queue:\n            node = queue.popleft()\n            print(node.val, end=\" \")  # Process the node by printing its value\n            \n            # Add the left and right children to the queue, if they exist\n            if node.left:\n                queue.append(node.left)\n            if node.right:\n                queue.append(node.right)"
  },
  {
    "path": "patterns/python/monotonic_stack.py",
    "content": "class MonotonicStack:\n    def next_greater_element(self, nums):\n        n = len(nums)\n        result = [-1] * n  # Default to -1 if no greater element exists\n        stack = []  # Stack stores indices\n\n        for i in range(n):\n            while stack and nums[i] > nums[stack[-1]]:\n                index = stack.pop()\n                result[index] = nums[i]\n            stack.append(i)\n        \n        return result\n\n    def daily_temperatures(self, temperatures):\n        n = len(temperatures)\n        result = [0] * n  # Result array initialized with 0s\n        stack = []  # Monotonic decreasing stack\n\n        for i in range(n):\n            while stack and temperatures[i] > temperatures[stack[-1]]:\n                prev_index = stack.pop()\n                result[prev_index] = i - prev_index\n            stack.append(i)\n\n        return result"
  },
  {
    "path": "patterns/python/reverse_list.py",
    "content": "class ListNode:\n    def __init__(self, val=0, next=None):\n        self.val = val\n        self.next = next\n\ndef reverse_list(head):\n    prev = None\n    curr = head\n\n    while curr:\n        next_node = curr.next\n        curr.next = prev\n        prev = curr\n        curr = next_node\n\n    return prev"
  },
  {
    "path": "patterns/python/sliding_window.py",
    "content": "class SlidingWindow:\n    def find_max_average_brute_force(self, nums, k):\n        max_avg = float('-inf')\n\n        for i in range(len(nums) - k + 1):\n            max_avg = max(max_avg, sum(nums[i:i + k]) / k)\n\n        return max_avg\n\n    def find_max_average_sliding_window(self, nums, k):\n        sum_window = sum(nums[:k])\n        max_sum = sum_window\n\n        for i in range(k, len(nums)):\n            sum_window += nums[i] - nums[i - k]\n            max_sum = max(max_sum, sum_window)\n\n        return max_sum / k\n\n    def length_of_longest_substring_sliding_window(self, s):\n        seen = set()\n        max_length = left = 0\n\n        for right in range(len(s)):\n            while s[right] in seen:\n                seen.remove(s[left])\n                left += 1\n            seen.add(s[right])\n            max_length = max(max_length, right - left + 1)\n\n        return max_length\n\n    def length_of_longest_substring_sliding_window_frequency_array(self, s):\n        freq = [0] * 128\n        max_length = left = 0\n\n        for right in range(len(s)):\n            freq[ord(s[right])] += 1\n\n            while freq[ord(s[right])] > 1:\n                freq[ord(s[left])] -= 1\n                left += 1\n\n            max_length = max(max_length, right - left + 1)\n\n        return max_length"
  },
  {
    "path": "patterns/python/top_k_elements.py",
    "content": "import heapq\nfrom collections import Counter\n\nclass TopKElements:\n    \n    # K Largest Elements using Sorting\n    def k_largest_elements_sorting_approach(self, nums, k):\n        return sorted(nums, reverse=True)[:k]\n\n    # K Largest Elements using Max Heap\n    def k_largest_elements_max_heap_approach(self, nums, k):\n        return heapq.nlargest(k, nums)\n\n    # K Largest Elements using Min Heap\n    def k_largest_elements_min_heap_approach(self, nums, k):\n        min_heap = nums[:k]\n        heapq.heapify(min_heap)\n        for num in nums[k:]:\n            heapq.heappush(min_heap, num)\n            if len(min_heap) > k:\n                heapq.heappop(min_heap)\n        return [heapq.heappop(min_heap) for _ in range(k)][::-1]\n\n    # Top K Frequent Elements using Sorting\n    def top_k_frequent_elements_sorting_approach(self, nums, k):\n        count = Counter(nums)\n        return [num for num, freq in count.most_common(k)]\n\n    # Top K Frequent Elements using Min Heap\n    def top_k_frequent_elements_min_heap_approach(self, nums, k):\n        count = Counter(nums)\n        min_heap = []\n        for num, freq in count.items():\n            heapq.heappush(min_heap, (freq, num))\n            if len(min_heap) > k:\n                heapq.heappop(min_heap)\n        return [heapq.heappop(min_heap)[1] for _ in range(k)][::-1]\n\n    # K Closest Points to Origin using Max Heap\n    def get_distance(self, point):\n        return point[0] ** 2 + point[1] ** 2\n\n    def k_closest_points_to_origin_max_heap_approach(self, points, k):\n        max_heap = []\n        for point in points:\n            heapq.heappush(max_heap, (-self.get_distance(point), point))\n            if len(max_heap) > k:\n                heapq.heappop(max_heap)\n        return [heapq.heappop(max_heap)[1] for _ in range(k)][::-1]"
  },
  {
    "path": "patterns/python/two_pointers.py",
    "content": "class TwoPointers:\n    # Move Zeroes using Two Pointers\n    def move_zeroes_two_pointers(self, nums):\n        left = 0  # Pointer for placing non-zero elements\n\n        # Iterate with right pointer\n        for right in range(len(nums)):\n            if nums[right] != 0:\n                # Swap elements if right pointer finds a non-zero\n                nums[left], nums[right] = nums[right], nums[left]\n                left += 1  # Move left pointer forward\n\n    # Brute Force approach for Container with Most Water\n    def max_area_brute_force(self, height):\n        n = len(height)\n        max_area = 0\n\n        # Check all pairs (i, j)\n        for i in range(n):\n            for j in range(i + 1, n):\n                # Compute the minimum height and width\n                min_height = min(height[i], height[j])\n                width = j - i\n                area = min_height * width  # Compute water contained\n\n                max_area = max(max_area, area)  # Update max water\n        return max_area\n\n    # Two Pointers approach for Container with Most Water\n    def max_area_two_pointers(self, height):\n        left, right = 0, len(height) - 1\n        max_area = 0\n\n        # Move pointers toward each other\n        while left < right:\n            width = right - left  # Distance between lines\n            min_height = min(height[left], height[right])  # Compute height\n            area = min_height * width  # Compute water contained\n\n            max_area = max(max_area, area)  # Update max water\n\n            # Move the pointer pointing to the shorter height\n            if height[left] < height[right]:\n                left += 1  # Move left pointer forward\n            else:\n                right -= 1  # Move right pointer backward\n\n        return max_area"
  },
  {
    "path": "patterns/typescript/fastAndSlowPointers.ts",
    "content": "class ListNode {\n    val: number;\n    next: ListNode | null = null;\n    constructor(x: number) {\n        this.val = x;\n    }\n}\n\nclass FastAndSlowPointers {\n    // LeetCode 141 - Linked List Cycle (HashSet Approach)\n    hasCycleHashSetApproach(head: ListNode | null): boolean {\n        const visited = new Set<ListNode>();\n        let current = head;\n        while (current) {\n            if (visited.has(current)) {\n                return true;\n            }\n            visited.add(current);\n            current = current.next;\n        }\n        return false;\n    }\n\n    // LeetCode 141 - Linked List Cycle (Fast and Slow Pointer Approach)\n    hasCycleFastAndSlowPointersApproach(head: ListNode | null): boolean {\n        if (!head || !head.next) return false;\n        let slow: ListNode | null = head;\n        let fast: ListNode | null = head;\n        while (fast && fast.next) {\n            slow = slow!.next;\n            fast = fast.next.next;\n            if (slow === fast) return true;\n        }\n        return false;\n    }\n\n    // LeetCode 876 - Middle of the Linked List (Counting Approach)\n    middleNodeCountingApproach(head: ListNode | null): ListNode | null {\n        let count = 0;\n        let current = head;\n        while (current) {\n            count++;\n            current = current.next;\n        }\n        current = head;\n        for (let i = 0; i < Math.floor(count / 2); i++) {\n            current = current!.next;\n        }\n        return current;\n    }\n\n    // LeetCode 876 - Middle of the Linked List (Fast and Slow Pointer Approach)\n    middleNodeFastAndSlowPointerApproach(head: ListNode | null): ListNode | null {\n        let slow = head, fast = head;\n        while (fast && fast.next) {\n            slow = slow!.next;\n            fast = fast.next.next;\n        }\n        return slow;\n    }\n\n    // LeetCode 202 - Happy Number (HashSet Approach)\n    getSumOfSquares(n: number): number {\n        return String(n).split('').reduce((sum, digit) => sum + Number(digit) ** 2, 0);\n    }\n\n    isHappyHashSetApproach(n: number): boolean {\n        const seen = new Set<number>();\n        while (n !== 1 && !seen.has(n)) {\n            seen.add(n);\n            n = this.getSumOfSquares(n);\n        }\n        return n === 1;\n    }\n\n    // LeetCode 202 - Happy Number (Fast and Slow Pointer Approach)\n    isHappyFastAndSlowPointersApproach(n: number): boolean {\n        let slow = n;\n        let fast = this.getSumOfSquares(n);\n        while (fast !== 1 && slow !== fast) {\n            slow = this.getSumOfSquares(slow);\n            fast = this.getSumOfSquares(this.getSumOfSquares(fast));\n        }\n        return fast === 1;\n    }\n}"
  },
  {
    "path": "patterns/typescript/kadaneAlgorithm.ts",
    "content": "class KadaneAlgorithm {\n    maxSubArray(nums: number[]): number {\n        let currentSum: number = nums[0];\n        let maxSum: number = nums[0];\n\n        for (let i = 1; i < nums.length; i++) {\n            currentSum = Math.max(nums[i], currentSum + nums[i]);\n            maxSum = Math.max(maxSum, currentSum);\n        }\n        return maxSum;\n    }\n}"
  },
  {
    "path": "patterns/typescript/levelOrderTraversal.ts",
    "content": "// Definition for a binary tree node.\nclass BinaryTreeNode {\n    val: number;\n    left: TreeNode | null;\n    right: TreeNode | null;\n\n    constructor(val: number) {\n        this.val = val;\n        this.left = this.right = null;\n    }\n}\n\nclass BinaryTreeLevelOrderTraversal {\n    levelOrder(root: BinaryTreeNode | null): void {\n        if (root === null) return;\n\n        const queue: BinaryTreeNode[] = [root];\n\n        while (queue.length > 0) {\n            const node = queue.shift()!;\n            console.log(node.val); // Process the node by printing its value\n            \n            // Add the left and right children to the queue, if they exist\n            if (node.left !== null) queue.push(node.left);\n            if (node.right !== null) queue.push(node.right);\n        }\n    }\n}"
  },
  {
    "path": "patterns/typescript/monotonicStack.ts",
    "content": "class MonotonicStack {\n    nextGreaterElement(nums: number[]): number[] {\n        let n = nums.length;\n        let result: number[] = new Array(n).fill(-1); // Default to -1 if no greater element exists\n        let stack: number[] = []; // Stack stores indices\n\n        for (let i = 0; i < n; i++) {\n            while (stack.length > 0 && nums[i] > nums[stack[stack.length - 1]]) {\n                let index = stack.pop()!;\n                result[index] = nums[i];\n            }\n            stack.push(i);\n        }\n        return result;\n    }\n\n    dailyTemperatures(temperatures: number[]): number[] {\n        let n = temperatures.length;\n        let result: number[] = new Array(n).fill(0); // Result array initialized with 0s\n        let stack: number[] = []; // Monotonic decreasing stack\n\n        for (let i = 0; i < n; i++) {\n            while (stack.length > 0 && temperatures[i] > temperatures[stack[stack.length - 1]]) {\n                let prevIndex = stack.pop()!;\n                result[prevIndex] = i - prevIndex;\n            }\n            stack.push(i);\n        }\n        return result;\n    }\n}"
  },
  {
    "path": "patterns/typescript/reverseList.ts",
    "content": "class ListNode {\n    val: number;\n    next: ListNode | null;\n\n    constructor(val: number = 0, next: ListNode | null = null) {\n        this.val = val;\n        this.next = next;\n    }\n}\n\nfunction reverseList(head: ListNode | null): ListNode | null {\n    let prev: ListNode | null = null;\n    let curr: ListNode | null = head;\n\n    while (curr !== null) {\n        let next: ListNode | null = curr.next;\n        curr.next = prev;\n        prev = curr;\n        curr = next;\n    }\n    return prev;\n}"
  },
  {
    "path": "patterns/typescript/slidingWindow.ts",
    "content": "class SlidingWindow {\n    // Brute Force Approach - O(n * k)\n    findMaxAverageBruteForce(nums: number[], k: number): number {\n        let maxAvg = -Infinity;\n\n        for (let i = 0; i <= nums.length - k; i++) {\n            let sum = 0;\n            for (let j = i; j < i + k; j++) {\n                sum += nums[j];\n            }\n            maxAvg = Math.max(maxAvg, sum / k);\n        }\n        return maxAvg;\n    }\n\n    // Sliding Window Approach - O(n)\n    findMaxAverageSlidingWindow(nums: number[], k: number): number {\n        let sum = nums.slice(0, k).reduce((a, b) => a + b, 0);\n        let maxSum = sum;\n\n        for (let i = k; i < nums.length; i++) {\n            sum += nums[i] - nums[i - k];\n            maxSum = Math.max(maxSum, sum);\n        }\n\n        return maxSum / k;\n    }\n\n    // Sliding Window for Longest Substring Without Repeating Characters\n    lengthOfLongestSubstringSlidingWindow(s: string): number {\n        let seen = new Set<string>();\n        let maxLength = 0, left = 0;\n\n        for (let right = 0; right < s.length; right++) {\n            while (seen.has(s[right])) {\n                seen.delete(s[left]);\n                left++;\n            }\n            seen.add(s[right]);\n            maxLength = Math.max(maxLength, right - left + 1);\n        }\n        return maxLength;\n    }\n\n    // Sliding Window using Frequency Array\n    lengthOfLongestSubstringSlidingWindowFrequencyArray(s: string): number {\n        let freq = new Array(128).fill(0);\n        let maxLength = 0, left = 0;\n\n        for (let right = 0; right < s.length; right++) {\n            freq[s.charCodeAt(right)]++;\n\n            while (freq[s.charCodeAt(right)] > 1) {\n                freq[s.charCodeAt(left)]--;\n                left++;\n            }\n\n            maxLength = Math.max(maxLength, right - left + 1);\n        }\n        return maxLength;\n    }\n}"
  },
  {
    "path": "patterns/typescript/topKElements.ts",
    "content": "class TopKElements {\n    \n    // K Largest Elements using Sorting\n    kLargestElementsSortingApproach(nums: number[], k: number): number[] {\n        nums.sort((a, b) => b - a);\n        return nums.slice(0, k);\n    }\n\n    // K Largest Elements using Max Heap\n    kLargestElementsMaxHeapApproach(nums: number[], k: number): number[] {\n        const maxHeap = new MaxPriorityQueue({ priority: (x: number) => x });\n        for (const num of nums) {\n            maxHeap.enqueue(num);\n        }\n        const result: number[] = [];\n        for (let i = 0; i < k; i++) {\n            result.push(maxHeap.dequeue().element);\n        }\n        return result;\n    }\n\n    // K Largest Elements using Min Heap\n    kLargestElementsMinHeapApproach(nums: number[], k: number): number[] {\n        const minHeap = new MinPriorityQueue({ priority: (x: number) => x });\n        for (let i = 0; i < k; i++) {\n            minHeap.enqueue(nums[i]);\n        }\n        for (let i = k; i < nums.length; i++) {\n            minHeap.enqueue(nums[i]);\n            if (minHeap.size() > k) {\n                minHeap.dequeue();\n            }\n        }\n        const result: number[] = [];\n        for (let i = 0; i < k; i++) {\n            result.push(minHeap.dequeue().element);\n        }\n        return result;\n    }\n\n    // Top K Frequent Elements using Sorting\n    topKFrequentElementsSortingApproach(nums: number[], k: number): number[] {\n        const frequencyMap = new Map<number, number>();\n        nums.forEach(num => frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1));\n        return Array.from(frequencyMap)\n            .sort((a, b) => b[1] - a[1])\n            .slice(0, k)\n            .map(entry => entry[0]);\n    }\n\n    // Top K Frequent Elements using Min Heap\n    topKFrequentElementsMinHeapApproach(nums: number[], k: number): number[] {\n        const frequencyMap = new Map<number, number>();\n        nums.forEach(num => frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1));\n        const minHeap = new MinPriorityQueue({ priority: (x: [number, number]) => x[1] });\n        frequencyMap.forEach((value, key) => {\n            minHeap.enqueue([key, value]);\n            if (minHeap.size() > k) {\n                minHeap.dequeue();\n            }\n        });\n        const result: number[] = [];\n        for (let i = 0; i < k; i++) {\n            result.push(minHeap.dequeue().element[0]);\n        }\n        return result;\n    }\n\n    // K Closest Points to Origin using Max Heap\n    getDistance(point: number[]): number {\n        return point[0] ** 2 + point[1] ** 2;\n    }\n\n    kClosestPointsToOriginMaxHeapApproach(points: number[][], k: number): number[][] {\n        const maxHeap = new MaxPriorityQueue({ priority: (point: number[]) => -this.getDistance(point) });\n        points.forEach(point => {\n            maxHeap.enqueue(point);\n            if (maxHeap.size() > k) {\n                maxHeap.dequeue();\n            }\n        });\n        const result: number[][] = [];\n        for (let i = 0; i < k; i++) {\n            result.push(maxHeap.dequeue().element);\n        }\n        return result;\n    }\n}"
  },
  {
    "path": "patterns/typescript/twoPointers.ts",
    "content": "class TwoPointers {\n    // Move Zeroes using Two Pointers\n    moveZeroesTwoPointers(nums: number[]): void {\n        let left = 0; // Pointer for placing non-zero elements\n\n        // Iterate with right pointer\n        for (let right = 0; right < nums.length; right++) {\n            if (nums[right] !== 0) {\n                // Swap elements if right pointer finds a non-zero\n                [nums[left], nums[right]] = [nums[right], nums[left]];\n                left++; // Move left pointer forward\n            }\n        }\n    }\n\n    // Brute Force approach for Container with Most Water\n    maxAreaBruteForce(height: number[]): number {\n        let maxArea = 0;\n        let n = height.length;\n\n        // Check all pairs (i, j)\n        for (let i = 0; i < n; i++) {\n            for (let j = i + 1; j < n; j++) {\n                // Compute the minimum height and width\n                let minHeight = Math.min(height[i], height[j]);\n                let width = j - i;\n                let area = minHeight * width; // Compute water contained\n\n                maxArea = Math.max(maxArea, area); // Update max water\n            }\n        }\n        return maxArea;\n    }\n\n    // Two Pointers approach for Container with Most Water\n    maxAreaTwoPointers(height: number[]): number {\n        let left = 0, right = height.length - 1;\n        let maxArea = 0;\n\n        // Move pointers toward each other\n        while (left < right) {\n            let width = right - left; // Distance between lines\n            let minHeight = Math.min(height[left], height[right]); // Compute height\n            let area = minHeight * width; // Compute water contained\n\n            maxArea = Math.max(maxArea, area); // Update max water\n\n            // Move the pointer pointing to the shorter height\n            if (height[left] < height[right]) {\n                left++; // Move left pointer forward\n            } else {\n                right--; // Move right pointer backward\n            }\n        }\n        return maxArea;\n    }\n}"
  }
]