[
  {
    "path": ".gitignore",
    "content": ".DS_Store\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright (C) <2015> <leetcode.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# leetcode\nLeetCode solutions.\nLeetCode solutions in English.\nLeetCode中文解答。\n\nI uploaded some codes [here](https://zhenchaogan.gitbook.io/leetcode-solution/)\n\n[Video solutions](https://www.youtube.com/watch?v=iZHDx-k2Mxw&list=PLSY2q1ZYmTARCSZvXIwO79Lb9LB5EBX-a&index=2) [中文解答](https://www.youtube.com/watch?v=6S1eKneFu8I&list=PLSY2q1ZYmTATCxSnwd_NohDmmt8PTBzrq) [中文bilibili解答](https://space.bilibili.com/1551381295/channel/detail?cid=167862)\n\n<table class=\"table table-bordered table-striped table-condensed\">\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\">Problem</font></td>\n        <td colspan='20'><font size=\"4px\" color=\"#0x888888\">Video Solution</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/001-010/Two%20Sum.cpp\">LeetCode 1. Two Sum</font></td>\n        <td align=\"center\"><a href=\"https://www.youtube.com/watch?v=WbSOR-Qewt0&feature=youtu.be\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://www.youtube.com/watch?v=GKM0IByXKkk&feature=youtu.be\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1dy4y1n7AS/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/001-010/Add%20Two%20Numbers.cpp\">LeetCode 2. Add Two Numbers</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/nrT4oGpOLfk\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/LVhNH1BdGGM\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1h54y1W7iR/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/001-010/Longest%20Substring%20Without%20Repeating%20Characters.cpp\">LeetCode 3. Longest Substring Without Repeating Characters</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/51tTP5RJlQ0\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/BUXpASogwZw\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV17A411g7xk/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/001-010/Median%20of%20Two%20Sorted%20Arrays.cpp\">LeetCode 4. Median of Two Sorted Arrays</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/12mkeVQIiQc\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/iQ1oxyXPJCY\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1HU4y1x7dt/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/001-010/Longest%20Palindromic%20Substring.cpp\">LeetCode 5. Longest Palindromic Substring</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/l0FR5x5dNvs\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/7jkLvTSyyy4\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV12541177cx/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/001-010/ZigZag%20Conversion.cpp\">LeetCode 6. ZigZag Conversion</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/1v4c3nj_8jc\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/eG9JVMAhKz8\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1iv4y1Z7M9/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/001-010/Reverse%20Integer.cpp\">LeetCode 7. Reverse Integer</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/9Uoze4Wfesg\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/2Wrdfm0FBOs\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Ry4y1E7mA/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/001-010/String%20to%20Integer%20(atoi).cpp\">LeetCode 8. String to Integer (atoi)</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/VMr_bFDLXrA\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/1EwgseajIOE\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1kV411i7kM/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/001-010/Palindrome%20Number.cpp\">LeetCode 9. Palindrome Number</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/99fQ34HHTuw\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/obBNRAfHsno\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1vU4y1W7Zf/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/001-010/Regular%20Expression%20Matching.cpp\">LeetCode 10. Regular Expression Matching</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/_U3vZCgLhXE\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/cHwEdvY8rRg\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Tb4y1R7Fs/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/011-020/Container%20With%20Most%20Water.cpp\">LeetCode 11. Container With Most Water</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/veZhNuviRtg\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/HK5-nhR0Jtc\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Ef4y1z75r/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/011-020/Integer%20to%20Roman.cpp\">LeetCode 12. Integer to Roman</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/oL1hreAAFc0\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/d80x6Ruh1Ic\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1bK4y1Q7mc/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/011-020/Roman%20to%20Integer.cpp\">LeetCode 13. Roman to Integer</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/53XFEgtot7g\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/LA3qRG3qS48\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1AN411d7bX/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/011-020/Longest%20Common%20Prefix.cpp\">LeetCode 14. Longest Common Prefix</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/ukfzYlQPwsY\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/qdLc68w9X5c\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Rz4y127Bs/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/011-020/3Sum.cpp\">LeetCode 15. 3Sum</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/3Szdf-_uRRE\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/v86W0cgvO5Y\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1cy4y1J71A/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/011-020/3Sum%20Closest.cpp\">LeetCode 16. 3Sum Closest</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/G9x8UqE_F2k\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/ovkcwjUUapw\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV19V411e74N/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/011-020/Letter%20Combinations%20of%20a%20Phone%20Number.cpp\">LeetCode 17. Letter Combinations of a Phone Number</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/czE2XcQjYyE\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/PvKXodU6irA\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1tZ4y1A7Vg/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/011-020/4Sum.cpp\">LeetCode 18. 4Sum</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/zM8yfKADVfM\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/HJ8rgwmO1L0\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1by4y1J7GF/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/011-020/Remove%20Nth%20Node%20From%20End%20of%20List.cpp\">LeetCode 19. Remove Nth Node From End of List</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/YKi_YM9Ih_I\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/aTSVLDJduBM\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1qi4y1T7NE/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/011-020/Valid%20Parentheses.cpp\">LeetCode 20. Valid Parentheses</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/rh4T1sI8krU\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/oAu0zWo3fNw\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Ty4y1e7dQ/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/021-030/Merge%20Two%20Sorted%20Lists.cpp\">LeetCode 21. Merge Two Sorted Lists</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/LsaQUAQacZA\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Darw7d-fg6U\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1EN41197Fo/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/021-030/Generate%20Parentheses.cpp\">LeetCode 22. Generate Parentheses</font></td>\n        <td align=\"center\"><a href=\"https://www.youtube.com/watch?v=7UnrtxdII2g\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://www.youtube.com/watch?v=AfCUpUedBgU\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV15N41197Qq/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/021-030/Merge%20k%20Sorted%20Lists.cpp\">LeetCode 23. Merge k Sorted Lists</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Xequ4LCiHgM\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/BHoY6wjfx4g\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1ki4y1T77r/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/021-030/Swap%20Nodes%20in%20Pairs.cpp\">LeetCode 24. Swap Nodes in Pairs</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/xHD8uzI3D3Y\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/eeV5zbeqous\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Wp4y1H72Z/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/021-030/Reverse%20Nodes%20in%20k-Group.cpp\">LeetCode 25. Reverse Nodes in k-Group</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/dc4gxhpCrPY\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/goNpyRA02jw\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV18K4y1J7Fm/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/021-030/Remove%20Duplicates%20from%20Sorted%20Array.cpp\">LeetCode 26. Remove Duplicates from Sorted Array</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/ifVpYbnm05A\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Dy9uPt-HvYQ\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Gy4y1a7AB/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/021-030/Remove%20Element.cpp\">LeetCode 27. Remove Element</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/dUENPWnea6g\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/OFiDGVXm7ko\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1ZX4y1G7EE/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/021-030/Implement%20strStr().cpp\">LeetCode 28. Implement strStr()</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/G9c18kcusBY\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/2XJeC0eVNrc\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1CA411K7f8/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/021-030/Divide%20Two%20Integers.cpp\">LeetCode 29. Divide Two Integers</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/7-_MeN35y6M\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/0BdG-hLtDZ4\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV16N41197Go/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/021-030/Substring%20with%20Concatenation%20of%20All%20Words.cpp\">LeetCode 30. Substring with Concatenation of All Words</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/eebtefMRvjQ\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/n9fYwG3dC_Q\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1up4y1h7AC/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/031-040/Next%20Permutation.cpp\">LeetCode 31. Next Permutation</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/0_eyN3VnTxc\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/JBX8rktJr3Y\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1DV411v7MM/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/031-040/Longest%20Valid%20Parentheses.cpp\">LeetCode 32. Longest Valid Parentheses</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/APvAgoFcFYQ\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/7sLZoD05uxw\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV13z4y117uv/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/031-040/Search%20in%20Rotated%20Sorted%20Array.cpp\">LeetCode 33. Search in Rotated Sorted Array</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/_0_8c6kZlxM\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/gSevuT3fvZU\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1154y187P5/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/041-050/Trapping%20Rain%20Water.cpp\">LeetCode 42. Trapping Rain Water</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/1LXscFcXkOk\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/vzNQr6ocvt4\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1BK4y1N75u/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/051-060/Merge%20Intervals.cpp\">LeetCode 56. Merge Intervals</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/TBw99kT-r6A\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/WKEZOVgYVjI\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1fK4y1N77s/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/061-070/Add%20Binary.cpp\">LeetCode 67. Add Binary</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/LIe-KekRmGE\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/rZUpzKi0w50\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1LQ4y1Z7MB/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/081-090/Search%20in%20Rotated%20Sorted%20Array%20II.cpp\">LeetCode 81. Search in Rotated Sorted Array II</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/SobfkJqBFYk\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/tBfnbjEw6RQ\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1g54y187cX/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/121-130/Valid%20Palindrome.cpp\">LeetCode 125. Valid Palindrome</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/TczseY1HaXI\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/4o2yZy_-iV0\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1TK4y1o7aa/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/151-160/Find%20Minimum%20in%20Rotated%20Sorted%20Array.cpp\">LeetCode 153. Find Minimum in Rotated Sorted Array</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/sNP3mg6dGAU\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/PTS5CXXBT1s\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV15h411X72i/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/151-160/Find%20Minimum%20in%20Rotated%20Sorted%20Array%20II.cpp\">LeetCode 154. Find Minimum in Rotated Sorted Array II</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/rR5M-Z0R3QE\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/w_OIDPaf_eI\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV12p4y1b74Q/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/151-160/Read%20N%20Characters%20Given%20Read4.cpp\">LeetCode 157. Read N Characters Given Read4</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/bziuNha1nXw\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Zw2UzFsMfZI\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1rX4y137FB/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/151-160/Read%20N%20Characters%20Given%20Read4%20II%20-%20Call%20multiple%20times.cpp\">LeetCode 158. Read N Characters Given Read4 II - Call multiple times</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/FYEfiWkkSEo\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/E-UIXA6LTIc\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1RV411Y7P3/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/231-240/Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree.cpp\">LeetCode 236. Lowest Common Ancestor of a Binary Tree</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/XhLMEiZWEZ4\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/T-PGz0jnAHA\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV14B4y1P7PF/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/231-240/Product%20of%20Array%20Except%20Self.cpp\">LeetCode 238. Product of Array Except Self</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/_M6LXQqd33w\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/hdCuT7xxNAY\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1rK4y1K72x/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/261-270/Alien%20Dictionary.cpp\">LeetCode 269. Alien Dictionary</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/OsjodfsorBs\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/5slT8ZfVKrQ\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1NU4y1h7Ww/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/291-300/Find%20Median%20from%20Data%20Stream.cpp\">Leetcode 295. Find Median from Data Stream</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/sSUCgilaVJ4\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/ByZgcvujtSA\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV16v411s7KH/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/291-300/Serialize%20and%20Deserialize%20Binary%20Tree.cpp\">Leetcode 297. Serialize and Deserialize Binary Tree</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/iZHDx-k2Mxw\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/8_JSg4RWvhY\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1rN411d7K1/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/291-300/Longest%20Increasing%20Subsequence.cpp\">LeetCode 300. Longest Increasing Subsequence</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/MGoFqowsxbU\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/7g3uoteFKug\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Vh411C7if/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/301-310/Remove%20Invalid%20Parentheses.cpp\">LeetCode 301. Remove Invalid Parentheses</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/hFGjMV851OU\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/I91977216Hk\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1i54y1a7g9/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/331-340/Palindrome%20Pairs.cpp\">LeetCode 336. Palindrome Pairs</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/bNXpdDNjKjM\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/P5-bM5g4m5Q\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1vb4y1D7Mq/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/401-410/Trapping%20Rain%20Water%20II.cpp\">LeetCode 407. Trapping Rain Water II</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/fqgqhRItdD4\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/GM2a2KalLYA\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1wK4y1K7t3/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/411-420/Add%20Strings.cpp\">LeetCode 415. Add Strings</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/UUhGJVIXFOQ\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/jOBZnOcjBQc\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Z54y1L7Ho/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/421-430/Convert%20Binary%20Search%20Tree%20to%20Sorted%20Doubly%20Linked%20List.cpp\">LeetCode 426. Convert Binary Search Tree to Sorted Doubly Linked List</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/SLT9NasJo4U\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/-TSxiyrOwIQ\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Cf4y147qd/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/481-490/Robot%20Room%20Cleaner.cpp\">LeetCode 489. Robot Room Cleaner</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/lXEBnevMfLg\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/AkLu58eJQPc\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1nZ4y1A7Rp/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/551-560/Subarray%20Sum%20Equals%20K.cpp\">LeetCode 560. Subarray Sum Equals K</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/l0dLq-qI588\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/cBGP5zAzom0\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1aK4y1U7jb/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/671-680/Valid%20Palindrome%20II.cpp\">LeetCode 680. Valid Palindrome II</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/rNTH2DSW8z0\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/w18su7VGwUQ\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Rf4y1W7GE/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/701-710/Random%20Pick%20with%20Blacklist.cpp\">LeetCode 710. Random Pick with Blacklist</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Bq3M4itMpbs\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/vJPVDzVrMSE\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1FK4y1S7g6/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/721-730/Accounts%20Merge.cpp\">LeetCode 721. Accounts Merge</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/pqvyyDQ9yIo\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/YAtoN4NikWM\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1RN411Q7Vk/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/861-870/All%20Nodes%20Distance%20K%20in%20Binary%20Tree.cpp\">LeetCode 863. All Nodes Distance K in Binary Tree</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/81kQSmLwtDA\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/KMIEWurYs10\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1QA411N7Ns/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/911-920/Maximum%20Sum%20Circular%20Subarray.cpp\">LeetCode 918. Maximum Sum Circular Subarray</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/oCDQ3JMZXw4\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/o_qM8AJUjt4\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1G5411A7H3/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/951-960/Verifying%20an%20Alien%20Dictionary.cpp\">LeetCode 953. Verifying an Alien Dictionary</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/jwL1Q70YNso\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Ou-28FTq00g\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1gK4y1U7Bp/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/971-980/K%20Closest%20Points%20to%20Origin.cpp\">LeetCode 973. K Closest Points to Origin</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/V2pdqKe2mjY\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/HaRE_RS70IQ\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1s54y1a7iQ/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1241-1250/Minimum%20Remove%20to%20Make%20Valid%20Parentheses.cpp\">LeetCode 1249. Minimum Remove to Make Valid Parentheses</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/S4LLF3uT-EY\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/vxMmmvdnuNs\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1n64y1v7Nm/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1421-1430/Leftmost%20Column%20with%20at%20Least%20a%20One.cpp\">LeetCode 1428. Leftmost Column with at Least a One</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/O3KQIh0J89g\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/koAFGCKT-Hw\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1ef4y1478d/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1561-1570/Dot%20Product%20of%20Two%20Sparse%20Vectors.cpp\">LeetCode 1570. Dot Product of Two Sparse Vectors</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/yzaZJCCjV7M\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Ns_gNGRhGd8\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1FZ4y1w7tQ/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1641-1650/Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree%20II.cpp\">LeetCode 1644. Lowest Common Ancestor of a Binary Tree II</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/d1b1WcKOGkU\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/NP9n3ebk620\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1sf4y1x7Kn/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1641-1650/Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree%20III.cpp\">LeetCode 1650. Lowest Common Ancestor of a Binary Tree III</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/8hrKhABmle8\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/31KtJn5IS9Q\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1sy4y1h7Ap/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1671-1680/Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree%20IV.cpp\">LeetCode 1676. Lowest Common Ancestor of a Binary Tree IV</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/_cJSRjNDn9s\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/6-q4KywBGAY\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1yb4y1Q7Ns/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1721-1730/Largest%20Submatrix%20With%20Rearrangements.cpp\">LeetCode 1727. Largest Submatrix With Rearrangements</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/DDN9ROQPwzA\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/6S1eKneFu8I\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1654y1W7hY/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1751-1760/Maximum%20Number%20of%20Events%20That%20Can%20Be%20Attended%20II.cpp\">LeetCode 1751. Maximum Number of Events That Can Be Attended II</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Az2GoGzOSEQ\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/DBsANiXd0LA\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV13y4y1Y7SW/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1751-1760/Largest%20Merge%20Of%20Two%20Strings.cpp\">LeetCode 1754. Largest Merge Of Two Strings</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/l5gKIfFbCIY\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/69YytzC_g_w\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1C541177NK/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1751-1760/Closest%20Subsequence%20Sum.cpp\">LeetCode 1755. Closest Subsequence Sum</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/K_CB32_SQFs\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/R_fDIPryG78\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Fz4y1U7zu/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1751-1760/Minimum%20Limit%20of%20Balls%20in%20a%20Bag.cpp\">LeetCode 1760. Minimum Limit of Balls in a Bag</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/5RLgPa7TWMY\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/C2s5lMLwyBE\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1wb4y1R7F5/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1761-1770/Minimum%20Degree%20of%20a%20Connected%20Trio%20in%20a%20Graph.cpp\">LeetCode 1761. Minimum Degree of a Connected Trio in a Graph</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/gSLz62X1eUY\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/8ud2wbNKPrM\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1T54y1Y7QD/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1761-1770/Form%20Array%20by%20Concatenating%20Subarrays%20of%20Another%20Array.cpp\">LeetCode 1764. Form Array by Concatenating Subarrays of Another Array</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/h6vQbNpfHbc\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/x8Hjo8C4_mA\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1WA411M7MH/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1761-1770/Map%20of%20Highest%20Peak.cpp\">LeetCode 1765. Map of Highest Peak</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/rMH2WLcD-Tc\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/9bFC2CLXynM\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://member.bilibili.com/platform/upload-manager/article\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1761-1770/Tree%20of%20Coprimes.cpp\">LeetCode 1766. Tree of Coprimes</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/l4sZZ0NJiCE\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/riLoVJ3ROEM\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1vb4y1R7Ji/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1761-1770/Maximum%20Score%20from%20Performing%20Multiplication%20Operations.cpp\">LeetCode 1770. Maximum Score from Performing Multiplication Operations</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/ggv0pK4BRuI\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/SBOp20CzqK0\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1QA411M7Da/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1771-1780/Maximize%20Palindrome%20Length%20From%20Subsequences.cpp\">LeetCode 1771. Maximize Palindrome Length From Subsequences</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/BJBdt7izITY\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/8KW1YYn2Puw\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1AK4y1H7jA/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1771-1780/Closest%20Dessert%20Cost.cpp\">LeetCode 1774. Closest Dessert Cost</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/0XCq29SOhNQ\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/fE-ZdhJF5Dc\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV12U4y1H7mX/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1771-1780/Equal%20Sum%20Arrays%20With%20Minimum%20Number%20of%20Operations.cpp\">LeetCode 1775. Equal Sum Arrays With Minimum Number of Operations</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/HkMyTGrBQxU\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/b-5bi-GA8_o\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1254y1h7ao/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1771-1780/Car%20Fleet%20II.cpp\">LeetCode 1776. Car Fleet II</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/iGxc4hgBM4c\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/0tB6Ozo40Kk\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Qi4y1T7jR/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1771-1780/Shortest%20Path%20in%20a%20Hidden%20Grid.cpp\">LeetCode 1778. Shortest Path in a Hidden Grid</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/P8H-oxAQAuY\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/tfNTJtdOW6c\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1i54y1a74m/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1771-1780/Find%20Nearest%20Point%20That%20Has%20the%20Same%20X%20or%20Y%20Coordinate.cpp\">LeetCode 1779. Find Nearest Point That Has the Same X or Y Coordinate</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1771-1780/Check%20if%20Number%20is%20a%20Sum%20of%20Powers%20of%20Three.cpp\">LeetCode 1780. Check if Number is a Sum of Powers of Three</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1781-1790/Sum%20of%20Beauty%20of%20All%20Substrings.cpp\">LeetCode 1781. Sum of Beauty of All Substrings</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1781-1790/Count%20Pairs%20Of%20Nodes.cpp\">LeetCode 1782. Count Pairs Of Nodes</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Ubch4urToXI\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/7tU017USVLw\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1z54y1a7WT/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1781-1790/Check%20if%20Binary%20String%20Has%20at%20Most%20One%20Segment%20of%20Ones.cpp\">LeetCode 1784. Check if Binary String Has at Most One Segment of Ones</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1781-1790/Minimum%20Elements%20to%20Add%20to%20Form%20a%20Given%20Sum.cpp\">LeetCode 1785. Minimum Elements to Add to Form a Given Sum</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1781-1790/Number%20of%20Restricted%20Paths%20From%20First%20to%20Last%20Node.cpp\">LeetCode 1786. Number of Restricted Paths From First to Last Node</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/b0YQ-IQbX1k\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/_NW5IRZtdOY\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Xv411h74T/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1781-1790/Make%20the%20XOR%20of%20All%20Segments%20Equal%20to%20Zero.cpp\">LeetCode 1787. Make the XOR of All Segments Equal to Zero</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/IjzRWhLIaqA\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/iMKtxo3N2r8\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Wb4y197Fx/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1781-1790/Maximize%20the%20Beauty%20of%20the%20Garden.cpp\">LeetCode 1788. Maximize the Beauty of the Garden</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/3eHQSpIGvwE\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/GPgHycs-VTg\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1uh411Q7nt/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1781-1790/Check%20if%20One%20String%20Swap%20Can%20Make%20Strings%20Equal.cpp\">LeetCode 1790. Check if One String Swap Can Make Strings Equal</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1791-1800/Find%20Center%20of%20Star%20Graph.cpp\">LeetCode 1791. Find Center of Star Graph</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1791-1800/Maximum%20Average%20Pass%20Ratio.cpp\">LeetCode 1792. Maximum Average Pass Ratio</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/sZBuARv5F2k\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/PMV8u4d87r0\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV12f4y1471N/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1791-1800/Maximum%20Score%20of%20a%20Good%20Subarray.cpp\">LeetCode 1793. Maximum Score of a Good Subarray</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/An3r5pFOKLc\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Xiznf9co2sM\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV14V411Y7kr/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1791-1800/Count%20Pairs%20of%20Equal%20Substrings%20With%20Minimum%20Difference.cpp\">LeetCode 1794. Count Pairs of Equal Substrings With Minimum Difference</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/1fnPLW5Tbxc\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/oXm_wtSecxs\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV12B4y1A7e1/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1791-1800/Second%20Largest%20Digit%20in%20a%20String.cpp\">LeetCode 1796. Second Largest Digit in a String</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1791-1800/Design%20Authentication%20Manager.cpp\">LeetCode 1797. Design Authentication Manager</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1791-1800/Maximum%20Number%20of%20Consecutive%20Values%20You%20Can%20Make.cpp\">LeetCode 1798. Maximum Number of Consecutive Values You Can Make</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/nx2ewP-wF6M\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/ZOE8TPrRG3M\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1G5411P7sT/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1791-1800/Maximize%20Score%20After%20N%20Operations.cpp\">LeetCode 1799. Maximize Score After N Operations</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/iYUoydllPc4\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/94vDosERuiI\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1g64y1D7j6/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1791-1800/Maximum%20Ascending%20Subarray%20Sum.cpp\">LeetCode 1800. Maximum Ascending Subarray Sum</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1801-1810/Number%20of%20Orders%20in%20the%20Backlog.cpp\">LeetCode 1801. Number of Orders in the Backlog</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1801-1810/Maximum%20Value%20at%20a%20Given%20Index%20in%20a%20Bounded%20Array.cpp\">LeetCode 1802. Maximum Value at a Given Index in a Bounded Array</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/YaxcdotEiwY\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/zDcsb9GYsC8\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1oz4y117Yb/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1801-1810/Count%20Pairs%20With%20XOR%20in%20a%20Range.cpp\">LeetCode 1803. Count Pairs With XOR in a Range</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/liaiLNNgOmo\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/iS1_e8vsXz4\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV16Z4y1w7pB/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1801-1810/Implement%20Trie%20II%20(Prefix%20Tree).cpp\">LeetCode 1804. Implement Trie II (Prefix Tree)</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/_3ReIHJeTT4\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/PAvVIROaw-Q\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1jv41187qN/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1801-1810/Number%20of%20Different%20Integers%20in%20a%20String.cpp\">LeetCode 1805. Number of Different Integers in a String</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1801-1810/Evaluate%20the%20Bracket%20Pairs%20of%20a%20String.cpp\">LeetCode 1807. Evaluate the Bracket Pairs of a String</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1801-1810/Maximize%20Number%20of%20Nice%20Divisors.cpp\">LeetCode 1808. Maximize Number of Nice Divisors</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/kYm4bYrktkw\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/xkqcceTrGJw\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Si4y1P7wF/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1801-1810/Minimum%20Path%20Cost%20in%20a%20Hidden%20Grid.cpp\">LeetCode 1810. Minimum Path Cost in a Hidden Grid</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/qtKlnHso4BU\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/6Id3jgq6FHg\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Gp4y187nM/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1811-1820/Determine%20Color%20of%20a%20Chessboard%20Square.cpp\">LeetCode 1812. Determine Color of a Chessboard Square</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1811-1820/Sentence%20Similarity%20III.cpp\">LeetCode 1813. Sentence Similarity III</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1811-1820/Count%20Nice%20Pairs%20in%20an%20Array.cpp\">LeetCode 1814. Count Nice Pairs in an Array</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1811-1820/Maximum%20Number%20of%20Groups%20Getting%20Fresh%20Donuts.cpp\">LeetCode 1815. Maximum Number of Groups Getting Fresh Donuts</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/h7U1S7Ut3ws\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/0FduysByEmE\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1Ly4y1b7bq/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1811-1820/Truncate%20Sentence.cpp\">LeetCode 1816. Truncate Sentence</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1811-1820/Finding%20the%20Users%20Active%20Minutes.cpp\">LeetCode 1817. Finding the Users Active Minutes</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1811-1820/Minimum%20Absolute%20Sum%20Difference.cpp\">LeetCode 1818. Minimum Absolute Sum Difference</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1811-1820/Number%20of%20Different%20Subsequences%20GCDs.cpp\">LeetCode 1819. Number of Different Subsequences GCDs</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Jbs6p2MLZjQ\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/ptaC4X0hC2Q\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1WX4y1g7sQ/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1811-1820/Maximum%20Number%20of%20Accepted%20Invitations.cpp\">LeetCode 1820. Maximum Number of Accepted Invitations</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/70cuAeXs6rk\"><font color=\"black\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/beVpSBo7FZk\"><font color=\"black\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1F5411A7dx/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1821-1830/Sign%20of%20the%20Product%20of%20an%20Array.cpp\">LeetCode 1822. Sign of the Product of an Array</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1821-1830/Minimum%20Sideway%20Jumps.cpp\">LeetCode 1824. Minimum Sideway Jumps</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/6-49f0eystc\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/PtYI0c8x8lY\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1HK4y1K7nk/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1821-1830/Finding%20MK%20Average.cpp\">LeetCode 1825. Finding MK Average</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/tHMWcAikcnY\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Nr_XX-joVm4\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1uy4y147Pi/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1821-1830/Faulty%20Sensor.cpp\">LeetCode 1826. Faulty Sensor</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1821-1830/Minimum%20Operations%20to%20Make%20the%20Array%20Increasing.cpp\">LeetCode 1827. Minimum Operations to Make the Array Increasing</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1821-1830/Queries%20on%20Number%20of%20Points%20Inside%20a%20Circle.cpp\">LeetCode 1828. Queries on Number of Points Inside a Circle</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1821-1830/Maximum%20XOR%20for%20Each%20Query.cpp\">LeetCode 1829. Maximum XOR for Each Query</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1821-1830/Minimum%20Number%20of%20Operations%20to%20Make%20String%20Sorted.cpp\">LeetCode 1830. Minimum Number of Operations to Make String Sorted</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/6u6l5Jd-HQc\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/0yxk667NXgw\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1uA411V7Tr/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1831-1840/Check%20if%20the%20Sentence%20Is%20Pangram.cpp\">LeetCode 1832. Check if the Sentence Is Pangram</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1831-1840/Maximum%20Ice%20Cream%20Bars.cpp\">LeetCode 1833. Maximum Ice Cream Bars</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1831-1840/Single-Threaded%20CPU.cpp\">LeetCode 1834. Single-Threaded CPU</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1831-1840/Find%20XOR%20Sum%20of%20All%20Pairs%20Bitwise%20AND.cpp\">LeetCode 1835. Find XOR Sum of All Pairs Bitwise AND</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/H09_S0dbphs\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/d0cbmU9v-Pc\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1B64y1y7TY/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1831-1840/Remove%20Duplicates%20From%20an%20Unsorted%20Linked%20List.cpp\">LeetCode 1836. Remove Duplicates From an Unsorted Linked List</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1831-1840/Sum%20of%20Digits%20in%20Base%20K.cpp\">LeetCode 1837. Sum of Digits in Base K</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1831-1840/Longest%20Substring%20Of%20All%20Vowels%20in%20Order.cpp\">LeetCode 1839. Longest Substring Of All Vowels in Order</font></td>\n        <td align=\"center\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1831-1840/Maximum%20Building%20Height.cpp\">LeetCode 1840. Maximum Building Height</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/gQSwu5TVD8A\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Gfv8tNiizCw\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1uQ4y1f7QH/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1841-1850/Closest%20Room.cpp\">LeetCode 1847. Closest Room</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Q1WGr7fxA6g\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/6QW31b5CeoQ\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV13B4y1w7wS/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1841-1850/Minimum%20Adjacent%20Swaps%20to%20Reach%20the%20Kth%20Smallest%20Number.cpp\">LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/5-GdjgRc4P0\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/LMmWq6j73vU\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV1j64y127Cx/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n    <tr>\n        <td colspan='40'><font size=\"4px\" color=\"#0x888888\"><a href=\"https://github.com/gzc/leetcode/blob/master/cpp/1001-10000/1851-1860/Minimum%20Interval%20to%20Include%20Each%20Query.cpp\">LeetCode 1851. Minimum Interval to Include Each Query</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/Z7qiynScOPA\"><font color=\"black\">English</font></td>\n        <td align=\"center\"><a href=\"https://youtu.be/q5jHwTw139s\"><font color=\"black\">中文Youtube</font></td>\n        <td align=\"center\"><a href=\"https://www.bilibili.com/video/BV14h411m7GA/\"><font color=\"black\">中文b站</font></td>\n    </tr>\n</table>\n"
  },
  {
    "path": "Solve the Equation.cpp",
    "content": "// https://discuss.leetcode.com/topic/95378/concise-c-solution-with-regular-expression-12-lines\nclass Solution {\npublic:\n    string solveEquation(string equation) {\n    // normalize the equation, add 1 for x's which have no coefficient: x => 1x\n    equation = regex_replace(equation, regex(\"(^|[+=-])x\"), \"$011x\");\n\n    // calculate coefficients for both sides\n    auto pos = equation.find('=');\n    auto l = coef(equation.substr(0, pos));\n    auto r = coef(equation.substr(pos + 1));\n\n    // l.first x + l.second = r.first x + r.second => ax = b\n    int a = l.first - r.first;\n    int b = r.second - l.second;\n\n    return a != 0 ? \"x=\" + to_string(b/a) : b != 0 ? \"No solution\" : \"Infinite solutions\";\n}\n\npair<int, int> coef(string s) {\n    // split the side into form of (+/-)123x\n    auto e = regex(\"(^|[+-])\\\\d+x?\");\n    regex_token_iterator<string::iterator> it(s.begin(), s.end(), e), end;\n\n    int a = 0, b = 0;\n    for (; it != end; it++)\n        (it->str().back() == 'x' ? a : b) += stoi(*it);\n\n    return {a, b};\n}\n};\n"
  },
  {
    "path": "TODO",
    "content": "4 Median of Two Sorted Arrays\n5 Longest Palindromic Substring \n9 Palindrome Number\n10 Regular Expression Matching(花了挺多时间，30分钟)\n12 Integer to Roman 醉了啊\n42 review later\n43 need more practice\n44 tricky"
  },
  {
    "path": "cpp/001-010/Add Two Numbers.cpp",
    "content": "class Solution {\npublic:\n    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {\n        ListNode *head = new ListNode(0);\n        ListNode *pre = head;\n        int carry = 0;\n        \n        while(l1 || l2 || carry) {\n            int a = (l1 == NULL? 0 : l1->val);\n            int b = (l2 == NULL? 0 : l2->val);\n            int c = a + b + carry;\n            carry = c > 9? 1 : 0;\n            int v = c%10;\n            ListNode *cur = new ListNode(v);\n            pre->next = cur;\n            pre = pre->next;\n            if(l1) l1 = l1->next;\n            if(l2) l2 = l2->next;\n        }\n\n        return head->next;\n    }\n};\n"
  },
  {
    "path": "cpp/001-010/Longest Palindromic Substring.cpp",
    "content": "class Solution {\npublic:\n    string longestPalindrome(string s) {\n        int n = s.length();\n        int longestBegin = 0;\n        int maxLen = 1;\n        bool table[1000][1000] = {false};\n        for (int i = 0; i < n; i++)\n            table[i][i] = true;\n  \n        for (int len = 2; len <= n; len++) {\n            for (int i = 0; i < n-len+1; i++) {\n                int j = i+len-1;\n                if (s[i] == s[j] && (j-i == 1 || table[i+1][j-1])) {\n                    table[i][j] = true;\n                    longestBegin = i;\n                    maxLen = len;\n                }\n            }\n        }\n        return s.substr(longestBegin, maxLen);\n    }\n};\n"
  },
  {
    "path": "cpp/001-010/Longest Substring Without Repeating Characters.cpp",
    "content": "class Solution {\npublic:\n    int lengthOfLongestSubstring(string s) {\n        unordered_map<char, int> mymap;\n        int start = 0;\n        int ans = 0;\n        \n        for (int i = 0; i < s.length(); i++) {\n            char ch = s[i];\n            auto it = mymap.find(ch);\n            if (it != mymap.end()) {\n                start = max(start, it->second + 1);\n            }\n            \n            mymap[ch] = i;\n            ans = max(ans, i - start + 1);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/001-010/Median of Two Sorted Arrays.cpp",
    "content": "class Solution {\npublic:\n    double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {\n        int m = nums1.size(), n = nums2.size();\n        if ((m + n) % 2 == 1) {\n            return findKthElement((m + n) / 2 + 1, nums1, 0, nums2, 0);\n        } else {\n            return (findKthElement((m + n) / 2, nums1, 0 ,nums2, 0) + findKthElement((m + n) / 2 + 1, nums1, 0 ,nums2, 0)) / 2;\n        }\n    }\n    \n    double findKthElement(int k, const vector<int>& nums1, int idx1, const vector<int>& nums2, int idx2) {\n        int l1 = nums1.size() - idx1;\n        int l2 = nums2.size() - idx2;\n        if (l1 > l2) {\n            return findKthElement(k, nums2, idx2, nums1, idx1);\n        }\n        if (l1 == 0) {\n            return nums2[idx2 + k - 1];\n        }\n        if (k == 1) {\n            return min(nums1[idx1], nums2[idx2]);\n        }\n        int cut1 = min(k/2, l1);\n        int cut2 = k - cut1;\n        if (nums1[idx1 + cut1 - 1] > nums2[idx2 + cut2 - 1]) {\n            return findKthElement(k - cut2, nums1, idx1, nums2, idx2 + cut2);\n        } else {\n            return findKthElement(k - cut1, nums1, idx1 + cut1, nums2, idx2);\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/001-010/Palindrome Number.cpp",
    "content": "class Solution {\npublic:\n    bool isPalindrome(int x) {\n        if (x == 0) return true;\n        if (x < 0) return false;\n        if (x % 10 == 0) return false;\n        \n        int sum = 0;\n        while (x > sum) {\n            sum = sum * 10 + x % 10;\n            x /= 10;\n        }\n        return (x == sum) || (x == sum / 10);\n    }\n    \n};\n"
  },
  {
    "path": "cpp/001-010/Regular Expression Matching.cpp",
    "content": "class Solution {\n    \n    bool isMatch(const string& s, int sidx, const string& p, int pidx) {\n        if (pidx >= p.length()) {\n            return sidx == s.length();\n        }\n        if ((pidx + 1) < p.length() && p[pidx + 1] == '*') {\n            if (isMatch(s, sidx, p, pidx + 2)) {\n                return true;\n            }\n            if (sidx < s.length() && (p[pidx] == '.' || s[sidx] == p[pidx])) {\n                return isMatch(s, sidx + 1, p, pidx);\n            }\n        } else if (sidx < s.length() && (p[pidx] == '.' || s[sidx] == p[pidx])) {\n            return isMatch(s, sidx + 1, p, pidx + 1);\n        }\n        return false;\n    }\n    \npublic:\n    bool isMatch(string s, string p) {\n        return isMatch(s, 0, p, 0);\n    }\n};\n"
  },
  {
    "path": "cpp/001-010/Reverse Integer.cpp",
    "content": "class Solution {\npublic:\n    int reverse(int x) {\n        // INT_MAX: 2147483647\n        // INT_MIN: -2147483648\n        int result = 0;\n        \n        while (x != 0) {\n            int mod = x % 10;\n            \n            if (result > 214748364 || (result == 214748364 && mod > 7)) {\n                return 0;\n            }\n            if (result < -214748364 || (result == -214748364 && mod == -9)) {\n                return 0;\n            }\n            \n            result = 10 * result + mod;\n            x /= 10;\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/001-010/String to Integer (atoi).cpp",
    "content": "class Solution {\npublic:\n    int myAtoi(string str) {\n        while (str[0] == ' ') {\n            str.erase(0, 1);\n        }\n        \n        int sign = 1;\n        if (str[0] == '+' || str[0] == '-') {\n            if (str[0] == '-') sign = -1;\n            str.erase(0, 1);\n        }\n        \n        int result = 0;\n        for (int i = 0; i < str.length(); i++) {\n            if (!isdigit(str[i])) {\n                break;\n            }\n            int v = str[i] - '0';\n\n            if (result > INT_MAX/10) {\n                if (sign == 1) return INT_MAX;\n                if (sign == -1) return INT_MIN;\n            } else if (result == INT_MAX/10) {\n                if (sign == 1 && v >= 7) return INT_MAX;\n                if (sign == -1 && v >= 8) return INT_MIN;\n            }\n            result = 10 * result + v;\n        }\n        \n        return result * sign;\n    }\n};\n"
  },
  {
    "path": "cpp/001-010/Two Sum.cpp",
    "content": "class Solution {\npublic:\n    vector<int> twoSum(vector<int> &numbers, int target) {\n        unordered_map<int, int> m;\n        vector<int> result;\n        for (int i = 0;i < numbers.size();i++) {\n            int remain = target - numbers[i];\n            if (m.count(remain) > 0) {\n                result.push_back(m[remain]);\n                result.push_back(i);\n                return result;\n            }\n            m[numbers[i]] = i;\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/001-010/ZigZag Conversion.cpp",
    "content": "class Solution {\npublic:\n    string convert(string s, int numRows) {\n        if (numRows == 1) {\n            return s;\n        }\n        \n        vector<string> rows(numRows);\n        int row = 0;\n        int step = 1;\n        for (char ch : s) {\n            rows[row].push_back(ch);\n            \n            if (row == (numRows - 1)) {\n                step = -1;\n            } else if (row == 0) {\n                step = 1;\n            }\n            row += step;\n        }\n        \n        stringstream ss;\n        for (const string& row : rows) {\n            ss << row;\n        }\n        return ss.str();\n    }\n};\n"
  },
  {
    "path": "cpp/011-020/3Sum Closest.cpp",
    "content": "class Solution {\npublic:\n    int threeSumClosest(vector<int>& nums, int target) {\n        int ans = 0;\n        int diff = INT_MAX;\n        sort(nums.begin(), nums.end());\n        \n        for (int i = 0; i < nums.size(); i++) {\n            if (i > 0 && nums[i - 1] == nums[i]) {\n                continue;\n            }\n            \n            int j = i + 1;\n            int k = nums.size() - 1;\n            \n            while (j < k) {\n                int sum = nums[i] + nums[j] + nums[k];\n                if (abs(sum - target) < diff) {\n                    ans = sum;\n                    diff = abs(sum - target);\n                }\n                if (sum < target) {\n                    j++;\n                } else if (sum > target) {\n                    k--;\n                } else {\n                    return target;\n                }\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/011-020/3Sum.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> threeSum(vector<int>& nums) {\n        vector<vector<int>> result;\n            \n        sort(nums.begin(), nums.end());\n        \n        for (int i = 0; i < nums.size(); i++) {\n            if (i > 0 && nums[i - 1] == nums[i]) {\n                continue;\n            }\n            \n            int j = i + 1;\n            int k = nums.size() - 1;\n            \n            while (j < k) {\n                int sum = nums[i] + nums[j] + nums[k];\n                if (sum < 0) {\n                    j++;\n                } else if (sum > 0) {\n                    k--;\n                } else {\n                    result.push_back({nums[i], nums[j], nums[k]});\n                    while ((j + 1) < nums.size() && nums[j] == nums[j+1]) j++;\n                    j++;\n                    while ((k - 1) >= 0 && nums[k] == nums[k - 1]) k--;\n                    k--;\n                }\n            }\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/011-020/4Sum.cpp",
    "content": "class Solution {\n    \npublic:\n    vector<vector<int> > fourSum(vector<int> &num, int target) {\n        vector<vector<int>>result;\n        int n = num.size();\n        sort(num.begin(), num.end());\n        \n        for (int i = 0; i < n; i++) {\n            if (i > 0 && num[i-1] == num[i]) {\n                continue;\n            }\n            for (int j = i + 1; j < n; j++) {\n                if (j > (i + 1) && num[j-1] == num[j]) {\n                    continue;\n                }\n                int l = j + 1, r = n - 1;\n                int partial_sum = num[i] + num[j];\n                while (l < r) {\n                    int sum = partial_sum + num[l] + num[r];\n                    if (sum < target) {\n                        l++;\n                    } else if (sum > target) {\n                        r--;\n                    } else {\n                        result.push_back({num[i], num[j], num[l], num[r]});\n                        while ((l + 1) < num.size() && num[l] == num[l+1]) l++;\n                        l++;\n                        while ((r - 1) >= 0 && num[r] == num[r - 1]) r--;\n                        r--;\n                    }\n                }\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/011-020/Container With Most Water.cpp",
    "content": "class Solution {\npublic:\n    int maxArea(vector<int>& height) {\n        int i(0), j(height.size()-1);\n        int area(0);\n        while (i < j) {\n            area = max(area, (j-i)*min(height[i], height[j]));\n            height[i] > height[j] ? j-- : i++;\n        }\n        return area;\n    }\n};\n"
  },
  {
    "path": "cpp/011-020/Integer to Roman.cpp",
    "content": "class Solution {\npublic:\n    string intToRoman(int num) {\n        map<int, string> mymap{\n            {1, \"I\"}, {5, \"V\"}, {10, \"X\"}, {50, \"L\"},\n            {100, \"C\"}, {500, \"D\"}, {1000, \"M\"},\n            {4, \"IV\"}, {9, \"IX\"},\n            {40, \"XL\"}, {90, \"XC\"},\n            {400, \"CD\"}, {900, \"CM\"}\n        };\n        \n        stringstream ss;\n        for (auto it = mymap.rbegin(); it != mymap.rend(); it++) {\n            int key = it->first;\n            const string& code = it->second;\n            while (num >= key) {\n                num -= key;\n                ss << code;\n            }\n        }\n        \n        return ss.str();\n    }\n};\n"
  },
  {
    "path": "cpp/011-020/Letter Combinations of a Phone Number.cpp",
    "content": "class Solution {\n    \npublic:\n    vector<string> letterCombinations(string digits) {\n        string symbols[10] = {\"\", \"\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"};\n        vector<string> result;\n        if (digits.empty()) {\n            return result;\n        }\n        result.push_back(\"\");\n        \n        for (char ch : digits) {\n            int num = ch - '0';\n            vector<string> new_result;\n            for (const string& s : result) {\n                for (char symbol : symbols[num]) {\n                    string tmp = s + symbol;\n                    new_result.push_back(tmp);\n                }\n            }\n            result.swap(new_result);\n        }\n        \n        return result;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/011-020/Longest Common Prefix.cpp",
    "content": "class Solution {\npublic:\n    string longestCommonPrefix(vector<string>& strs) {\n        if (strs.empty()) {\n            return \"\";\n        }\n        string prefix = strs[0];\n        \n        for (int i = 1; i < strs.size(); i++) {\n            const string& str = strs[i];\n            \n            int k = 0;\n            while (k < min(prefix.length(), str.length())) {\n                if (prefix[k] != str[k]) {\n                    break;\n                }\n                k++;\n            }\n            \n            prefix = prefix.substr(0, k);\n        }\n        \n        return prefix;\n    }\n};\n"
  },
  {
    "path": "cpp/011-020/Remove Nth Node From End of List.cpp",
    "content": "class Solution {\npublic:\n    ListNode* removeNthFromEnd(ListNode* head, int n) {\n        int len = 0;\n        ListNode* head_copy = head;\n        \n        while (head_copy != nullptr) {\n            head_copy = head_copy->next;\n            len++;\n        }\n        \n        if (n == len) {\n            ListNode* new_head = head->next;\n            delete head;\n            return new_head;\n        }\n        \n        head_copy = head;\n        for (int i = 1; i < (len - n); i++) {\n            head_copy = head_copy->next;\n        }\n        \n        ListNode* to_delete = head_copy->next;\n        head_copy->next = head_copy->next->next;\n        delete to_delete;\n        return head;\n    }\n};\n"
  },
  {
    "path": "cpp/011-020/Roman to Integer.cpp",
    "content": "class Solution {\npublic:\n    \n    int romanToInt(string s) {\n        map<char, int> table { \n            {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50},\n            {'C', 100}, {'D', 500}, {'M', 1000}\n        };\n        \n        int result = 0;\n        for (int i = 0;i < s.length();i++) {\n            if (i < s.length()-1 && table[s[i]] < table[s[i+1]] ) {\n                result -= table[s[i]];\n            } else {\n                result += table[s[i]];\n            }\n        }\n        \n        return result;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/011-020/Valid Parentheses.cpp",
    "content": "class Solution {\npublic:\n    bool isValid(string s) {\n        stack<char> container;\n        for (int i = 0;i < s.length();i++)\n        {\n            if (container.empty())\n                container.push(s[i]);\n            else\n            {\n                char c = s[i];\n                char v = container.top();\n                if (c == '(' || c == '{' || c == '[')\n                    container.push(c);\n                else\n                {\n                    if ( (c == ')' && v == '(') || (c == '}' && v == '{') || (c == ']' && v == '['))\n                        container.pop();\n                    else\n                        return false;\n                }\n            }\n        }\n        return container.empty();\n    }\n};\n"
  },
  {
    "path": "cpp/021-030/Divide Two Integers.cpp",
    "content": "/*\n * Solution 1:\n * Use long type\n */\nclass Solution {\npublic:\n    int divide(int dividend, int divisor) {\n        if (dividend == INT_MIN && divisor == -1) {\n            return INT_MAX;\n        }\n        bool positive = true;\n        if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) {\n            positive = false;\n        }\n\n        long new_dividend = abs((long)dividend);\n        long new_divisor = abs((long)divisor);\n        long result = 0;\n\n        int power = 0;\n        while (new_divisor <= (new_dividend >> 1)) {\n            new_divisor = new_divisor << 1;\n            power++;\n        }\n        \n        while (power >= 0) {\n            if (new_dividend >= new_divisor) {\n                result += (1 << power);\n                new_dividend -= new_divisor;\n            }\n            power--;\n            new_divisor = new_divisor >> 1;\n        }\n        \n        return positive ? result : -result;\n    }\n};\n\n/*\n * Solution 2:\n * Don't use long type\n */\nclass Solution {\npublic:\n    int divide(int dividend, int divisor) {\n        if (dividend == INT_MIN) {\n            if (divisor == -1) {\n                return INT_MAX;\n            } \n            if (divisor > 0) {\n                return -1 + divide(dividend + divisor, divisor);\n            } else {\n                return 1 + divide(dividend - divisor, divisor);\n            }\n        }\n        if (divisor == INT_MIN) {\n            return dividend == INT_MIN ? 1 : 0;\n        }\n        bool positive = true;\n        if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) {\n            positive = false;\n        }\n\n        int new_dividend = abs(dividend);\n        int new_divisor = abs(divisor);\n        int result = 0;\n\n        int power = 0;\n        while (new_divisor <= (new_dividend >> 1)) {\n            new_divisor = new_divisor << 1;\n            power++;\n        }\n        \n        while (power >= 0) {\n            if (new_dividend >= new_divisor) {\n                result += (1 << power);\n                new_dividend -= new_divisor;\n            }\n            power--;\n            new_divisor = new_divisor >> 1;\n        }\n        \n        return positive ? result : -result;\n    }\n};\n"
  },
  {
    "path": "cpp/021-030/Generate Parentheses.cpp",
    "content": "class Solution {\n    \n    void dfs(string s, int open, int close, vector<string>& parentheses) {\n        if (close < open) {\n            return;\n        }\n        \n        if (open == 0) {\n            string temp(close, ')');\n            s += temp;\n            parentheses.push_back(s);\n        } else {\n            dfs(s + \"(\", open - 1, close, parentheses);\n            dfs(s + \")\", open, close - 1, parentheses);\n        }\n    }\n    \npublic:\n    vector<string> generateParenthesis(int n) {\n        vector<string> parentheses;\n        dfs(\"\", n, n, parentheses);\n        return parentheses;\n    }\n};\n"
  },
  {
    "path": "cpp/021-030/Implement strStr().cpp",
    "content": "class Solution {\npublic:\n    int strStr(string haystack, string needle) {\n        int m = haystack.length(), n = needle.length();\n        for (int i = 0; i < m - n + 1; i++) {\n            int j = 0;\n            for (; j < n; j++) {\n                if (haystack[i + j] != needle[j]) {\n                    break;\n                }\n            }\n            if (j == n) {\n                return i;\n            }\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/021-030/Merge Two Sorted Lists.cpp",
    "content": "class Solution {\npublic:\n    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {\n        ListNode *head = new ListNode(-1);\n        ListNode *fake_head = head;\n        \n        while (l1 != nullptr || l2 != nullptr) {\n            if (l1 == nullptr) {\n                head->next = l2;\n                break;\n            } else if(l2 == nullptr) {\n                head->next = l1;\n                break;\n            }\n            \n            if (l1->val <= l2->val) {\n                head->next = l1;\n                head = l1;\n                l1 = l1->next;\n            } else {\n                head->next = l2;\n                head = l2;\n                l2 = l2->next;\n            }\n        }\n        return fake_head->next;\n    }\n};\n"
  },
  {
    "path": "cpp/021-030/Merge k Sorted Lists.cpp",
    "content": "class Solution {\npublic:\n    ListNode *mergeKLists(vector<ListNode *> &lists) {\n        auto cmp = [] (ListNode *n1, ListNode *n2) {\n            return n1->val > n2->val;\n        };\n        priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> nodes(cmp);\n        for (ListNode *list : lists) {\n            if (list != nullptr) {\n                nodes.push(list);\n            }\n        }\n        \n        if (nodes.empty()) {\n            return nullptr;\n        }\n        ListNode fake_head(0);\n        ListNode* current = &fake_head;\n        \n        while (!nodes.empty()) {\n            current->next = nodes.top();\n            current = current->next;\n            nodes.pop();\n            if (current->next != nullptr) {\n                nodes.push(current->next);\n            }\n        }\n        \n        return fake_head.next;\n    }\n};\n"
  },
  {
    "path": "cpp/021-030/Remove Duplicates from Sorted Array.cpp",
    "content": "class Solution {\npublic:\n    int removeDuplicates(vector<int>& nums) {\n        int pos = 0;\n        for (int n : nums) {\n            if (pos == 0 || n > nums[pos-1]) {\n                nums[pos] = n;\n                pos++;\n            }\n        }\n        return pos;\n    }\n};\n"
  },
  {
    "path": "cpp/021-030/Remove Element.cpp",
    "content": "class Solution {\npublic:\n    int removeElement(vector<int>& nums, int val) {\n        int pos = 0;\n        for (int n : nums) {\n            if (n != val) {\n                nums[pos] = n;\n                pos++;\n            }\n        }\n        return pos;\n    }\n};\n"
  },
  {
    "path": "cpp/021-030/Reverse Nodes in k-Group.cpp",
    "content": "class Solution {\n    \n    int length(ListNode* head) {\n        int len = 0;\n        while (head != nullptr) {\n            head = head->next;\n            len++;\n        }\n        return len;\n    }\n    \n    ListNode* dfs(ListNode* head, int len, int k) {\n        if (len < k) {\n            return head;\n        }\n        ListNode* tail = head;\n        \n        ListNode* prev = nullptr, *tmp = nullptr;\n        for (int i = 0; i < k; i++) {\n            tmp = head->next;\n            head -> next = prev;\n            prev = head;\n            head = tmp;\n        }\n        \n        tail->next = dfs(head, len - k, k);\n        return prev;\n    }\n    \npublic:\n    ListNode* reverseKGroup(ListNode* head, int k) {\n        return dfs(head, length(head), k);\n    }\n};\n"
  },
  {
    "path": "cpp/021-030/Substring with Concatenation of All Words.cpp",
    "content": "class Solution {\npublic:\n    vector<int> findSubstring(string s, vector<string>& words) {\n        vector<int> res;\n        unordered_map<string, int> dict;\n        int len = words[0].size();\n        int n = s.length(), m = words.size();\n        for (const string& word : words) {\n            dict[word]++;\n        }\n        for (int i = 0; i < len; i++) {\n            int cnt = 0;\n            unordered_map<string, int> copy = dict;\n            for (int j = i; j <= n - len; j += len) {\n                string cur = s.substr(j, len);\n                copy[cur]--;\n                if (copy[cur] >= 0) {\n                    cnt++;\n                }\n                \n                int pop_start = j - m * len;\n                if (pop_start >= 0) {\n                    string pop_word = s.substr(pop_start, len);\n                    copy[pop_word]++;\n                    if (copy[pop_word] > 0) {\n                        cnt--;\n                    }\n                }\n                if (cnt == m) {\n                    res.push_back(pop_start + len);\n                }\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/021-030/Swap Nodes in Pairs.cpp",
    "content": "class Solution {\npublic:\n    ListNode* swapPairs(ListNode* head) {\n        if (head == nullptr || head->next == nullptr) {\n            return head;\n        }\n        \n        ListNode* new_head = head->next;\n        \n        head->next = swapPairs(new_head->next);\n        new_head->next = head;\n        \n        return new_head;\n    }\n};\n"
  },
  {
    "path": "cpp/031-040/Combination Sum II.cpp",
    "content": "#include <iostream>\n#include <unordered_map>\n#include <vector>\n#include <stack>\n#include <queue>\n\nusing namespace std;\n\nclass Solution {\n    \n    void help(vector<int>& now, vector<int>&candidates, int index, int target, vector<vector<int>>& results)\n    {\n        for(int i = index;i < candidates.size();i++)\n        {\n            if(candidates[i] < target)\n            {\n                now.push_back(candidates[i]);\n                help(now, candidates, i+1, target-candidates[i], results);\n                now.pop_back();\n                while(i < candidates.size()-1 && candidates[i] == candidates[i+1]) i++;\n            } else if(candidates[i] == target) {\n                now.push_back(candidates[i]);\n                results.push_back(now);\n                now.pop_back();\n                return;\n            }\n        }\n    }\n    \npublic:\n    vector<vector<int> > combinationSum2(vector<int> &candidates, int target) {\n        vector<vector<int>> results;\n        vector<int> tmp;\n        sort(candidates.begin(), candidates.end());\n        help(tmp, candidates, 0, target, results);\n        return results;\n    }\n    \n};\n\nint main()\n{\n    Solution s;\n\n    return 0;\n}"
  },
  {
    "path": "cpp/031-040/Combination Sum.cpp",
    "content": "class Solution {\n    \n    void help(vector<int>& now, vector<int>&candidates, int index, int target, vector<vector<int>>& results)\n    {\n        for (int i = index;i < candidates.size();i++)\n        {\n            if (candidates[i] < target)\n            {\n                now.push_back(candidates[i]);\n                help(now, candidates, i, target-candidates[i], results);\n                now.pop_back();\n            } else if (candidates[i] == target) {\n                now.push_back(candidates[i]);\n                results.push_back(now);\n                now.pop_back();\n            }\n        }\n    }\n    \npublic:\n    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {\n        vector<vector<int>> results;\n        vector<int>tmp;\n        help(tmp, candidates, 0, target, results);\n        return results;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/031-040/Count and Say.cpp",
    "content": "#include <iostream>\n#include <unordered_map>\n#include <vector>\n#include <stack>\n#include <queue>\n\nusing namespace std;\n\nclass Solution {\n    \n    string process(string &s)\n    {\n        int i = 0;\n        string r;\n        while(i < s.length())\n        {\n            int l = 1;\n            while(i < s.length()-1 && s[i] == s[i+1])\n            {\n                l++;\n                i++;\n            }\n            r = r + to_string(l) + s[i];\n            i++;\n        }\n        return r;\n    }\n    \npublic:\n    string countAndSay(int n) {\n        string r = \"1\";\n        if(n == 1) return r;\n        for(int i = 2;i <= n;i++)\n            r = process(r);\n        return r;\n    }\n    \n};\n\nint main()\n{\n    Solution s;\n    \n    cout << s.countAndSay(1);\n\n    return 0;\n}"
  },
  {
    "path": "cpp/031-040/Longest Valid Parentheses.cpp",
    "content": "// Solution 1: DP\nclass Solution {\npublic:\n    int longestValidParentheses(string s) {\n        int n = s.size();\n        int res = 0;\n        vector<int> dp(n, 0);\n        for (int i = 0; i < n; i++) {\n            if (i > 0 && s[i] == ')') {\n                if (s[i-1] == '(') {\n                    int val = i - 2 >= 0 ? dp[i-2] : 0;\n                    dp[i] = 2 + val;\n                } else {\n                    int ind = i - dp[i-1] - 1;\n                    if (ind >= 0 && s[ind] == '(') {\n                        int val = ind > 0 ? dp[ind - 1] : 0;\n                        dp[i] = 2 + dp[i-1] + val;\n                    }\n                }\n                res = max(res, dp[i]);\n            }\n        }\n        return res;\n    }\n};\n\n// Solution 2: stack\nclass Solution {\npublic:\n    int longestValidParentheses(string s) {\n        stack<int> mystack;\n        mystack.push(-1);\n        int res = 0;\n        for (int i = 0; i < s.size(); i++) {\n            int t = mystack.top();\n            if (t != -1 && s[i] == ')' && s[t]=='(') {\n                mystack.pop();\n                res = max(res, i - mystack.top());\n            } else {\n                mystack.push(i);\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/031-040/Next Permutation.cpp",
    "content": "class Solution {\npublic:\n    void nextPermutation(vector<int> &num) {\n        if (num.empty()) {\n            return;\n        }\n        \n        int violation_index = num.size() - 2;\n        for (; violation_index >= 0; violation_index--) {\n            if (num[violation_index] < num[violation_index+1]) {\n                break;\n            }\n        }\n        \n        reverse(begin(num) + violation_index + 1, end(num));\n        \n        if (violation_index == -1) {\n            return;\n        }\n        \n        auto it = upper_bound(begin(num) + violation_index + 1, num.end(), num[violation_index]);\n\n        swap(num[violation_index], *it);\n    }\n    \n};\n"
  },
  {
    "path": "cpp/031-040/Search Insert Position.cpp",
    "content": "class Solution {\npublic:\n    int searchInsert(vector<int>& nums, int target) {\n        int lo = 0;\n        int hi = nums.size() - 1;\n        while (lo <= hi) {\n            int mid = lo + (hi - lo) / 2;\n            if (target < nums[mid]) hi = mid - 1;\n            else if (target > nums[mid]) lo = mid + 1;\n            else return mid;\n        }\n        return lo;\n    }\n};"
  },
  {
    "path": "cpp/031-040/Search for a Range.cpp",
    "content": "class Solution {\npublic:\n    vector<int> searchRange(vector<int>& nums, int target) {\n        std::vector<int>::iterator low,up;\n        low =std::lower_bound (nums.begin(), nums.end(), target);\n        up = std::upper_bound (nums.begin(), nums.end(), target); \n        vector<int> result;\n        if (low == up) {\n            result.push_back(-1);\n            result.push_back(-1);\n        } else {\n            result.push_back(low - nums.begin());\n            result.push_back(up - nums.begin() - 1);\n        }\n        return result;\n    }\n};\n\n\n\nclass Solution {\n    \n    int FindFirst(const vector<int>& nums, int target) {\n        int i = 0;\n        int j = nums.size() - 1;\n        \n        int pos = -1;\n        while (i <= j) {\n            int mid = (i + j) / 2;\n            \n            if (nums[mid] == target) {\n                pos = mid;\n                j = mid - 1;\n            } else if (nums[mid] > target) {\n                j = mid - 1;\n            } else {\n                i = mid + 1;\n            }\n        }\n        \n        return pos;\n    }\n    \n    int FindLast(const vector<int>& nums, int target) {\n        int i = 0;\n        int j = nums.size() - 1;\n        \n        int pos = -1;\n        while (i <= j) {\n            int mid = (i + j) / 2;\n            \n            if (nums[mid] == target) {\n                pos = mid;\n                i = mid + 1;\n            } else if (nums[mid] > target) {\n                j = mid - 1;\n            } else {\n                i = mid + 1;\n            }\n        }\n        \n        return pos;\n    }\n    \npublic:\n    vector<int> searchRange(vector<int>& nums, int target) {\n        vector<int> ans{FindFirst(nums, target), FindLast(nums, target)};\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/031-040/Search in Rotated Sorted Array.cpp",
    "content": "class Solution {\npublic:\n    int search(vector<int>& nums, int target) {\n        int i = 0;\n        int j = nums.size() - 1;\n        \n        while (i <= j) {\n            int mid = (i + j) / 2;\n            if (nums[mid] == target) return mid;\n            if (nums[mid] < nums[i]) {\n                if (nums[mid] < target && nums[j] >= target) i = mid+1;\n                else j = mid-1;\n            } else {\n                if (nums[mid] > target && nums[i] <= target) j = mid-1;\n                else i = mid+1;\n            }\n        }\n        \n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/031-040/Sudoku Solver.cpp",
    "content": "class Solution {\n\n    bool rows[9][9];\n    bool cols[9][9];\n    bool rec[3][3][9];\n\n    bool help(vector<vector<char> > &board, int i, int j) {\n        if(i == 9) return true;\n        int nexti(i), nextj(0);\n        if (j != 8) {\n            nextj = j+1;\n        } else {\n            nexti = i+1;\n        }\n        \n        if(board[i][j] != '.') {\n            return help(board, nexti, nextj);\n        } else {\n            for(int k = 0;k < 9;k++) {\n                if(rows[i][k] == false && cols[k][j] == false && rec[i/3][j/3][k] == false) {\n                    rows[i][k] = true;\n                    cols[k][j] = true;\n                    rec[i/3][j/3][k] = true;\n                    board[i][j] = (k+'1');\n                    bool t = help(board, nexti, nextj);\n                    if(t) return true;\n                    rows[i][k] = false;\n                    cols[k][j] = false;\n                    rec[i/3][j/3][k] = false;\n                    board[i][j] = '.';\n                }\n            }\n        }\n        return false;\n    }\n    \npublic:\n    void solveSudoku(vector<vector<char> > &board) {\n        memset(rows, false, sizeof(rows));\n        memset(cols, false, sizeof(cols));\n        memset(rec, false, sizeof(rec));\n        \n        for (int i = 0;i < 9;i++) {\n            for(int j = 0;j < 9;j++) {\n                if(board[i][j] != '.') {\n                    int d = board[i][j] - '1';\n                    rows[i][d] = true;\n                    cols[d][j] = true;\n                    rec[i/3][j/3][d] = true;\n                }\n            }\n        }\n        \n        help(board, 0, 0);\n    }\n};\n"
  },
  {
    "path": "cpp/031-040/Valid Sudoku.cpp",
    "content": "class Solution {\npublic:\n    bool isValidSudoku(vector<vector<char> > &board) {\n        bool r[9][9], c[9][9], s[3][3][9];\n        memset(r, false, 9*9);\n        memset(c, false, 9*9);\n        memset(s, false, 3*3*9);\n        \n        for(int i = 0;i < 9;i++) {\n            for(int j = 0;j < 9;j++) {\n                char ch = board[i][j];\n                if (!isdigit(ch)) continue;\n                int num = ch - '1';\n                if (r[i][num] == true) return false;\n                r[i][num] = true;\n                if (c[j][num] == true) return false;\n                c[j][num] = true;\n                \n                int ii = i/3;\n                int jj = j/3;\n                if (s[ii][jj][num]) return false;\n                s[ii][jj][num] = true;\n            }\n        }\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/041-050/First Missing Positive.cpp",
    "content": "class Solution {\npublic:\n    int firstMissingPositive(vector<int>& nums) {\n        if (nums.empty()) return 1;\n        int i(0);\n        \n        while (i < nums.size()) {\n            if (nums[i] != i+1 && nums[i] > 0 && nums[i] < nums.size() && nums[i] != nums[nums[i]-1]) {\n                swap(nums[i], nums[nums[i]-1]);\n                continue;\n            }\n            i++;\n        }\n        \n        for (int i = 0;i < nums.size();i++)\n            if(nums[i] != i+1)\n                return i+1;\n        return nums.back()+1;\n    }\n};\n"
  },
  {
    "path": "cpp/041-050/Group Anagrams.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<string>> groupAnagrams(vector<string>& strs) {\n        map<string, vector<string>> mymap;\n        for (const string& str : strs) {\n            string key(str);\n            sort(key.begin(), key.end());\n            mymap[key].emplace_back(str);\n        }\n        vector<vector<string>> result;\n        for (const auto& it : mymap) result.emplace_back(it.second);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/041-050/Jump Game II.cpp",
    "content": "class Solution {\npublic:\n    int jump(vector<int>& nums) {\n        \n        if (nums.size() < 2) return 0;\n        \n        int count(0);\n        int step(0);\n        int nextstep(0);\n        \n        for (int i = 0; i < nums.size(); i++) {\n            if (i + nums[i] > nextstep) nextstep = i + nums[i];\n            if (i == step && i != nums.size()-1) {\n                step = nextstep;\n                count++;\n            }\n        }\n        \n        return count;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/041-050/Multiply Strings.cpp",
    "content": "class Solution {\n    \npublic:\n    string multiply(string num1, string num2) {\n        \n        string result(num1.length()+num2.length(), '0');\n        \n        reverse(num1.begin(), num1.end());\n        reverse(num2.begin(), num2.end());\n        \n        for (int i = 0;i < num1.length();i++) {\n            int carry = 0;\n            int j = 0;\n            while (j < num2.size() || carry > 0) {\n                int digit = result[i+j] - '0';\n                int v = j < num2.size() ? num2[j] : '0';\n                int num = (num1[i] - '0') * (v - '0');\n                int res = digit + num + carry;\n                result[i+j] = (res % 10) + '0';\n                carry = res / 10;\n\n                j++;\n            }\n        }\n        \n        reverse(result.begin(), result.end());\n        while(result[0] == '0' && result.length() > 1)\n            result = result.substr(1);\n        return result;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/041-050/Permutations II.cpp",
    "content": "class Solution {\n    \n    void help(vector<vector<int>>& result, int begin, vector<int> num) {\n        if (begin == num.size()) {\n            result.emplace_back(num);\n            return;\n        }\n \n        for (int i = begin; i < num.size();i++) {\n            if (i != begin && num[i] == num[begin]) continue;\n            swap(num[begin], num[i]);\n            help(result, begin+1, num);\n        }\n    }\n    \npublic:\n    vector<vector<int> > permuteUnique(vector<int> &num) {\n        vector<vector<int>> result;\n        sort(num.begin(), num.end());\n        help(result, 0, num);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/041-050/Permutations.cpp",
    "content": "class Solution {\n    \n    void help(vector<vector<int>>& result, int begin, vector<int> &num)\n    {\n        if (begin == num.size()) {\n            result.emplace(result.end(), num);\n            return;\n        }\n            \n        for (int i = begin; i < num.size();i++)\n        {\n            swap(num[begin], num[i]);\n            help(result, begin+1, num);\n            swap(num[begin], num[i]);\n        }\n    }\n    \npublic:\n    vector<vector<int> > permute(vector<int> &num) {\n        vector<vector<int>> result;\n        help(result, 0, num);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/041-050/Pow.cpp",
    "content": "class Solution {\npublic:\n    double myPow(double x, int n) {\n        double res = 1.0;\n        double tmp = x;\n        bool sign = (n >= 0);\n        n = abs(n);\n        \n        while (n > 0) {\n            if (n & 1) {\n                res *= tmp;\n            }\n            tmp *= tmp;\n            n = n >> 1;\n        }\n        \n        return sign ? res : 1/res;\n    }\n};\n"
  },
  {
    "path": "cpp/041-050/Rotate Image.cpp",
    "content": "class Solution {\npublic:\n    void rotate(vector<vector<int> > &matrix) {\n        int n = matrix[0].size() -1;\n        for (int i = 0;i <= n - i;i++) {\n            for (int j = i;j <= n - i - 1;j++) {\n                int tmp = matrix[j][n-i];\n                matrix[j][n-i] = matrix[i][j];\n                matrix[i][j] = matrix[n-j][i];\n                matrix[n-j][i] = matrix[n-i][n-j];\n                matrix[n-i][n-j] = tmp;\n            }\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/041-050/Trapping Rain Water.cpp",
    "content": "class Solution {\npublic:\n    int trap(vector<int>& height) {\n        int i = 0;\n        int j = height.size() - 1;\n        int maxleft = 0, maxright = 0;\n        int res = 0;\n        while(i < j) {\n            if(height[i] <= height[j]) {\n                if (height[i] > maxleft) maxleft = height[i];\n                else res += (maxleft - height[i]);\n                i++;\n            } else {\n                if (height[j] > maxright) maxright = height[j];\n                else res += (maxright - height[j]);\n                j--;\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/041-050/Wildcard Matching.cpp",
    "content": "class Solution {\npublic:\n    bool isMatch(string s, string p) {\n        \n        int i(0),j(0),ss(0),pp(-1);\n        \n        while (i < s.length()) {\n            if(s[i] == p[j] || p[j] == '?') {i++;j++;continue;}\n            \n            else if(p[j] == '*'){ss = i;pp = ++j;continue;}\n            \n            else if(pp != -1) {i = ++ss;j = pp;continue;}\n            \n            return false;\n        }\n        \n        while (j < p.length()) if(p[j++] != '*') return false;\n        return true;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/051-060/Insert Interval.cpp",
    "content": "class Solution {\n    \n    vector<Interval> merge(vector<Interval> &intervals) {\n        if(intervals.size() < 2)\n            return intervals;\n        auto comp = [&](Interval m,Interval n) { return m.start < n.start; };\n        vector<Interval> result;\n        sort(intervals.begin(), intervals.end(), comp);\n        \n        Interval now = intervals[0];\n        for(int i = 1;i < intervals.size();i++)\n        {\n            Interval then = intervals[i];\n            if(now.end >= then.start) {\n                now.end = max(now.end, then.end);\n            } else {\n                result.push_back(now);\n                now = then;\n            }\n        }\n        result.push_back(now);\n        return result;\n    }\n    \npublic:\n    vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {\n        intervals.push_back(newInterval);\n        return merge(intervals);\n    }\n};\n"
  },
  {
    "path": "cpp/051-060/Jump Game.cpp",
    "content": "class Solution {\npublic:\n    bool canJump(vector<int>& nums) {\n        \n        int maxpos(0);\n\n        for (int i = 0; i < nums.size(); i++) {\n            if (i <= maxpos) {\n                int tmp = i + nums[i];\n                if(tmp >= (nums.size()-1)) return true;\n                maxpos = max(tmp, maxpos);\n            }\n            else return false;\n        }\n        return false;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/051-060/Length of Last Word.cpp",
    "content": "class Solution {\npublic:\n    int lengthOfLastWord(string s) {\n        int len = 0, tail = s.length() - 1;\n        while (tail >= 0 && s[tail] == ' ') tail--;\n        while (tail >= 0 && s[tail] != ' ') {\n            len++;\n            tail--;\n        }\n        return len;\n    }\n};\n"
  },
  {
    "path": "cpp/051-060/Maximum_Subarray.cpp",
    "content": "/*************************************************************************\n\t> File Name: Maximum_Subarray.cpp\n\t> Author: Louis1992\n\t> Mail: zhenchaogan@gmail.com\n\t> Blog: http://gzc.github.io\n\t> Created Time: Sat Apr 18 19:14:47 2015\n ************************************************************************/\n#include<iostream>\n#include<cstdio>\n#include<list>\n#include<vector>\n#include<unordered_map>\n#include<climits>\n#include<unordered_set>\n#include<map>\n#include<set>\n#include<stack>\n#include<queue>\nusing namespace std;\n\nclass Solution {\npublic:\n    int maxSubArray(std::vector<int>& A) {\n        int n = A.size();\n        int a1(0), a2(0);\n        int m = INT_MIN;\n        \n        for(int i = 0;i < n;i++)\n        {\n            if(i == 0) a2 = A[i];\n            else if (a1 < 0) a2 = A[i];\n            else a2 = A[i]+a1;\n            m = max(m,a2);\n            a1 = a2;\n        }\n        \n        return m;\n    }\n};\n\n\nint main() {\n    Solution s;\n\n\n    return 0;\n}\n"
  },
  {
    "path": "cpp/051-060/Merge Intervals.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> merge(vector<vector<int>> &intervals) {\n        auto comp = [](const vector<int>& m, const vector<int>& n) {\n            return m[0] < n[0];\n        };\n        sort(intervals.begin(), intervals.end(), comp);\n        \n        vector<int> now = intervals[0];\n        vector<vector<int>> result;\n        for (int i = 1;i < intervals.size();i++) {\n            const vector<int>& then = intervals[i];\n            if (now[1] >= then[0]) {\n                now[1] = max(now[1], then[1]);\n            } else {\n                result.push_back(now);\n                now = then;\n            }\n        }\n        result.push_back(now);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/051-060/N-Queens II.cpp",
    "content": "class Solution {\n    \n    bool *cols;\n    bool *add;\n    bool *diff;\n    int n;\n    \n    bool valid(int i, int j) {\n        if (!cols[j] && !add[i+j] && !diff[i-j+n])\n            return true;\n        return false;\n    }\n    \n    void help(int i, int &res) {\n        if (i == n) {\n            res++;\n            return;\n        }\n\n        for (int j = 0;j < n;j++) {\n            if(valid(i, j)) {\n                cols[j] = add[i+j] = diff[i-j+n] = true;\n                help(i+1, res);\n                cols[j] = add[i+j] = diff[i-j+n] = false;\n            }\n        }\n    }\n    \npublic:\n    int totalNQueens(int n) {\n        cols = new bool[n];\n        add = new bool[2*n];\n        diff = new bool[2*n];\n        memset(cols, 0, n);\n        memset(add, 0, 2*n);\n        memset(diff, 0, 2*n);\n        this->n = n;\n        int res = 0;\n        help(0, res);\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/051-060/N-Queens.cpp",
    "content": "class Solution {\n    \n    bool *cols;\n    bool *add;\n    bool *diff;\n    int n;\n    \n    bool valid(int i, int j)\n    {\n        if(!cols[j] && !add[i+j] && !diff[i-j+n])\n            return true;\n        return false;\n    }\n    \n    void help(vector<vector<string>> &result, vector<pair<int, int>> &tmp, int i)\n    {\n        if(i == n)\n        {\n            string s(n, '.');\n            vector<string>t{n,s};\n            for(int k = 0;k < tmp.size();k++)\n                t[tmp[k].first][tmp[k].second] = 'Q';\n            result.push_back(t);\n            return;\n        } \n            \n        for(int j = 0;j < n;j++)\n        {\n            if(valid(i, j))\n            {\n                cols[j] = add[i+j] = diff[i-j+n] = true;\n                tmp.push_back(make_pair(i, j));\n                help(result, tmp, i+1);\n                tmp.pop_back();\n                cols[j] = add[i+j] = diff[i-j+n] = false;\n            }\n        }\n    }\n    \npublic:\n    vector<vector<string> > solveNQueens(int n) {\n\n        cols = new bool[n];\n        add = new bool[2*n];\n        diff = new bool[2*n];\n        this->n = n;\n        \n        vector<vector<string>> result;\n        vector<pair<int, int>> tmp;\n        \n        help(result, tmp, 0);\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/051-060/Permutation Sequence.cpp",
    "content": "class Solution {\npublic:\n    string getPermutation(int n, int k) {\n        int pTable[10] = {1};\n        for (int i = 1; i <= 9; i++) {\n            pTable[i] = i * pTable[i - 1];\n        }\n        string result;\n        char a[] = {'1','2','3','4','5','6','7','8','9'};\n        vector<char> numSet(a, a+9);\n        while (n > 0) {\n            int temp = (k - 1) / pTable[n - 1];\n            result += numSet[temp];\n            numSet.erase(numSet.begin() + temp);\n            k = k - temp * pTable[n - 1];\n            n--;\n        }\n        return result;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/051-060/Spiral Matrix II.cpp",
    "content": "#include <iostream>\n#include <unordered_map>\n#include <vector>\n#include <stack>\n#include <queue>\n\nusing namespace std;\n\nclass Solution {\npublic:\n    vector<vector<int> > generateMatrix(int n) {\n        \n        vector<vector <int> > result(n ,vector<int>(n));\n        \n        if(n == 0)\n            return result;\n        \n        int h = n;\n        int w = n;\n        int step = 1;\n        int i(0),j(0);\n        int z = 1;\n        \n        while(w > 0 && h > 0)\n        {\n            for(int k = 0;k < w;k++)\n            {\n                result[i][j] = z++;\n                j += step;\n            }\n            j -= step;\n            i += step;\n            \n            h--;\n            for(int k = 0;k < h;k++)\n            {\n                result[i][j] = z++;\n                i += step;\n            }\n            i -= step;\n            \n            step *= -1;\n            \n            j += step;\n            \n            w--;\n        }\n        return result;\n        \n        \n        \n        \n    }\n    \n};\n\nint main()\n{\n    Solution s;\n    \n    return 0;\n}"
  },
  {
    "path": "cpp/051-060/Spiral Matrix.cpp",
    "content": "#include <iostream>\n#include <unordered_map>\n#include <vector>\n#include <stack>\n#include <queue>\n\nusing namespace std;\n\nclass Solution {\npublic:\n    vector<int> spiralOrder(vector<vector<int> > &matrix) {\n        \n        vector<int>result;\n        \n        if(matrix.size() == 0)\n            return result;\n        \n        int h = matrix.size();\n        int w = matrix[0].size();\n        int step = 1;\n        int i(0),j(0);\n        \n        while(w > 0 && h > 0)\n        {\n            for(int k = 0;k < w;k++)\n            {\n                result.push_back(matrix[i][j]);\n                j += step;\n            }\n            j -= step;\n            i += step;\n            \n            h--;\n            for(int k = 0;k < h;k++)\n            {\n                result.push_back(matrix[i][j]);\n                i += step;\n            }\n            i -= step;\n            \n            step *= -1;\n            \n            j += step;\n            \n            w--;\n        }\n        return result;\n    }\n    \n};\n\nint main()\n{\n    Solution s;\n    \n    return 0;\n}"
  },
  {
    "path": "cpp/061-070/Add Binary.cpp",
    "content": "class Solution {\npublic:\n    string addBinary(string a, string b) {\n        string result;\n        int carry = 0;\n        int i1 = a.length() - 1;\n        int i2 = b.length() - 1;\n        while (i1 >= 0 || i2 >= 0 || carry > 0) {\n            int v1 = i1 >= 0 ? a[i1] - '0' : 0;\n            int v2 = i2 >= 0 ? b[i2] - '0' : 0;\n            int sum = v1 + v2 + carry;\n            result.push_back((sum & 1) + '0');\n            carry = (sum >> 1) & 1;\n            i1--;\n            i2--;\n        }\n        \n        reverse(begin(result), end(result));\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/061-070/Climbing Stairs.cpp",
    "content": "class Solution {\npublic:\n    int climbStairs(int n) {\n        vector<int> dp(n, 0);\n        dp[0] = 1;\n        dp[1] = 2;\n        \n        for (int i =2;i < n;i++)\n        {\n            dp[i] = dp[i-1]+dp[i-2];\n        }\n        \n        return dp[n-1];\n    }\n};\n"
  },
  {
    "path": "cpp/061-070/Minimum Path Sum .cpp",
    "content": "public:\nint minPathSum(vector<vector<int> > &grid) {\n    \n    int n = grid.size();\n    int m = grid[0].size();\n    int p[n][m];\n    p[0][0] = grid[0][0];\n    \n    \n    for(int k = 1;k < n;k++)\n        p[k][0] = p[k-1][0]+grid[k][0];\n    for(int k = 1;k < m;k++)\n        p[0][k] = p[0][k-1]+grid[0][k];\n    \n    for(int i = 1;i < n;i++)\n        for(int j = 1;j < m;j++)\n            p[i][j] = min(p[i-1][j], p[i][j-1]) + grid[i][j];\n    \n    return p[n-1][m-1];\n}\n};"
  },
  {
    "path": "cpp/061-070/Plus One.cpp",
    "content": "class Solution {\npublic:\n    vector<int> plusOne(vector<int>& digits) {\n        int carry(1);\n        for (int i = digits.size()-1; i >= 0; i--) {\n            int tmp = digits[i] + carry;\n            carry = tmp/10;\n            digits[i] = tmp%10;\n        }\n        \n        if (carry)\n            digits.emplace(digits.begin(), 1);\n        \n        return digits;\n    }\n};\n"
  },
  {
    "path": "cpp/061-070/Rotate List.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *rotateRight(ListNode *head, int k) {\n        if(!head || !head->next || !k)\n            return head;\n        \n        int len = 1;\n        ListNode *tail(head), *head2(head);\n        while (tail && tail->next) {\n            len++;\n            tail = tail->next;\n        }\n        k = k % len;\n        if(!k) return head;\n        \n        int n = len-k;\n        while(--n)\n            head2 = head2->next;\n        ListNode *tmp = head2->next;\n        head2->next = nullptr;\n        head2 = tmp;\n        \n        tail->next = head;\n        \n        return head2;\n    }\n};\n"
  },
  {
    "path": "cpp/061-070/Sqrt.cpp",
    "content": "class Solution {\npublic:\n    int mySqrt(int x) {\n        if (x == 0) return 0;\n        int left(1), right(x);\n        while (true) {\n            int mid = left + (right - left)/2;\n            if (mid > x/mid) {\n                right = mid - 1;\n            } else {\n                if (mid + 1 > x/(mid + 1))\n                    return mid;\n                left = mid + 1;\n            }\n        }\n        return -1;\n    }\n};\n\n\n\nclass Solution {\npublic:\n    int mySqrt(int x) {\n        if (x == 0) return 0;\n        int left = 1, right = x/2;\n        \n        while (left < right) {\n            int mid = left + (right - left)/2;\n            \n            if ((long)mid * (long)mid <= (long)x && (long)(mid+1)*(long)(mid+1) > (long)x) {\n                return mid;\n            } else if ((long)mid * (long)mid > (long)x) {\n                right = mid - 1;\n            } else {\n                left = mid + 1;\n            }\n        }\n        \n        return left;\n    }\n};\n"
  },
  {
    "path": "cpp/061-070/Text Justification.cpp",
    "content": "class Solution {\n    \n    vector<int> help(vector<string> &words, int start, int end, int L)\n    {\n        int wordCount = end - start;\n        if(words.size() == end) return vector<int>(wordCount-1,1);\n        int sum = L;\n        for(int i = start;i < end;i++)\n            sum -= words[i].length();\n        int Count = wordCount - 1;\n        \n        int average = sum / Count;\n        vector<int> blocks(wordCount-1, average);\n        sum -= average * Count;\n        \n        int index = 0;\n        while(sum--)\n            blocks[index++]++;\n        \n        return blocks;\n    }\n    \npublic:\n    vector<string> fullJustify(vector<string> &words, int L) {\n        vector<string> result;\n        if(words.size() == 0) return result;\n        int from = 0;\n        \n        \n        while(from < words.size())\n        {\n            string temp(L, ' ');\n            \n            int start = from;\n            int len = words[from].length();\n            while(len <= L && from < words.size()){\n                from ++;\n                if(from == words.size()) break;\n                len = len + words[from].length() + 1;\n            }\n            \n            if(from - start == 1){\n                for(int n = 0;n < words[start].length();n++)\n                    temp[n] = words[start][n];\n            } else {\n                vector<int> blocks = help(words, start, from, L);\n                int index = 0;\n                int skip = 0;\n                for(int i = start;i < from;i++)\n                {\n                    string now = words[i];\n                    for(int j = 0;j < now.length();j++)\n                        temp[index++] = now[j];\n                    index += blocks[skip++];\n                }\n            }\n            \n            result.push_back(temp);\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/061-070/Unique Paths II .cpp",
    "content": "class Solution {\npublic:\n    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {\n        int m(obstacleGrid.size()), n(obstacleGrid[0].size());\n        vector<vector<int>> dp(m+1,vector<int>(n+1,0));\n        if(obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1)\n            return 0;\n        dp[1][1] = 1;\n        \n        for(int i = 1;i <= m;i++)\n        {\n            for(int j = 1;j <= n;j++)\n            {\n                if(i == 1 && j == 1) continue;\n                if(obstacleGrid[i-1][j-1] == 1)\n                    dp[i][j] = 0;\n                else\n                    dp[i][j] = dp[i-1][j] + dp[i][j-1];\n            }\n        }\n        return dp[m][n];\n    }\n    \n};\n"
  },
  {
    "path": "cpp/061-070/Unique Paths.cpp",
    "content": "class Solution {\npublic:\n    int uniquePaths(int m, int n) {\n        vector<vector<int> > path(m, vector<int> (n, 1));\n        for (int i = 1; i < m; i++)\n            for (int j = 1; j < n; j++)\n                path[i][j] = path[i - 1][j] + path[i][j - 1];\n        return path[m - 1][n - 1];\n    }\n};\n"
  },
  {
    "path": "cpp/061-070/Valid Number.cpp",
    "content": "class Solution {\npublic:\n    bool isNumber(string str) {\n        int state=0, flag=0; // flag to judge the special case \".\"\n        while(str[0]==' ')  str.erase(0,1);//delete the  prefix whitespace \n        while(str[str.length()-1]==' ') str.erase(str.length()-1, 1);//delete the suffix whitespace\n        for(int i=0; i<str.length(); i++){\n            if('0'<=str[i] && str[i]<='9'){\n                flag=1;\n                if(state<=2) state=2;\n                else state=(state<=5)?5:7;\n            }\n            else if('+'==str[i] || '-'==str[i]){\n                if(state==0 || state==3) state++;\n                else return false;\n            }\n            else if('.'==str[i]){\n                if(state<=2) state=6;\n                else return false;\n            }\n            else if('e'==str[i]){\n                if(flag&&(state==2 || state==6 || state==7)) state=3;\n                else return false;\n            }\n            else return false;\n        }\n        return (state==2 || state==5 || (flag&&state==6) || state==7);\n    }\n};\n"
  },
  {
    "path": "cpp/071-080/Combinations.cpp",
    "content": "class Solution {\n    \n    void help(int n, int k, int index, vector<int>&tmp, vector<vector<int>>&v)\n    {\n        if(k == 0)\n        {\n            v.push_back(tmp);\n            return;\n        }\n        else if(index > n)\n            return;\n            \n        help(n,k,index+1,tmp,v);\n        tmp.push_back(index);\n        help(n,k-1,index+1,tmp,v);\n        tmp.pop_back();\n    }\n    \npublic:\n    vector<vector<int> > combine(int n, int k) {\n        vector<vector<int>>v;\n        vector<int>tmp;\n        \n        help(n,k,1,tmp,v);\n        return v;\n    }\n};\n"
  },
  {
    "path": "cpp/071-080/Edit Distance.cpp",
    "content": "class Solution {\npublic:\n    int minDistance(string word1, string word2) {\n        int m = word1.length();\n        int n = word2.length();\n        \n        vector<vector<int>> p(m+1, vector<int>(n+1));\n\n        for (int i = 0;i <= m;i++)\n            p[i][0] = i;\n        for (int j = 0;j <= n;j++)\n            p[0][j] = j;\n        \n        for (int i = 1;i <= m;i++) {\n            for (int j = 1;j <= n;j++) {\n                \n                if (word1[i-1] == word2[j-1]) {\n                    p[i][j] = p[i-1][j-1];\n                } else {\n                    p[i][j] = min(1 + p[i-1][j-1], 1+min(p[i][j-1], p[i-1][j]));\n                }\n                \n            }\n        }\n        \n        return p[m][n];\n    }\n};\n"
  },
  {
    "path": "cpp/071-080/Minimum Window Substring.cpp",
    "content": "class Solution {\npublic:\n    string minWindow(string s, string t) {\n        unordered_map<char, int> dict;\n        int cnt = 0, start = 0, len = INT_MAX, first = 0;\n        for (char c : t) {\n            dict[c]++;\n        }\n        for (int i = 0; i < s.size(); i++) {\n            dict[s[i]]--;\n            if (dict[s[i]] >= 0) {\n                cnt++;\n            }\n            while (cnt == t.size()) {\n                dict[s[start]]++;\n                if (dict[s[start]] > 0) {\n                    cnt--;\n                }\n                if (i - start + 1 < len) {\n                    len = i - start + 1;\n                    first = start;\n                }\n                start++;\n            }\n        }\n        return len == INT_MAX ? \"\" : s.substr(first, len);\n    }\n};\n"
  },
  {
    "path": "cpp/071-080/Remove Duplicates from Sorted Array II.cpp",
    "content": "class Solution {\npublic:\n    int removeDuplicates(vector<int>& nums) {\n        int rear(1), n(nums.size());\n        if (n <= 2) return n;\n        for (int i = 2; i < n; i++)\n            if (!(nums[i] == nums[rear] && nums[i] == nums[rear -1]))\n                nums[++rear] = nums[i];\n        return rear+1;\n    }\n};\n"
  },
  {
    "path": "cpp/071-080/Search a 2D Matrix.cpp",
    "content": "class Solution {\npublic:\n    bool searchMatrix(vector<vector<int> > &matrix, int target) {\n        int row(matrix.size()), col(matrix[0].size());\n        int i(0), j(row*col-1);\n        while (i <= j) {\n            int mid = (i+j) >> 1;\n            int v = matrix[mid/col][mid%col];\n            if (target < v) j = mid  - 1;\n            else if (target > v) i = mid + 1;\n            else if (target == v) return true;\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/071-080/Set Matrix Zeroes.cpp",
    "content": "class Solution {\npublic:\n    void setZeroes(vector<vector<int> > &matrix) {\n        \n        bool col0 = false;\n        int outer = matrix.size();\n        int inner = matrix[0].size();\n        \n        for (int i = 0; i < outer; i++) {\n            if (matrix[i][0] == 0)\n                col0 = true;\n            for (int j = 1; j < inner; j++) {\n                if (matrix[i][j] == 0) {\n                    matrix[i][0] = 0;\n                    matrix[0][j] = 0;\n                }\n            }\n        }\n        \n        for (int i = outer-1; i >= 0; i--) {\n            for (int j = inner-1; j >= 1; j--) {\n                if (matrix[i][0] == 0 || matrix[0][j] == 0) {\n                    matrix[i][j] = 0;\n                }\n            }\n            if(col0)\n                matrix[i][0] = 0;\n        }\n        \n    }\n};\n"
  },
  {
    "path": "cpp/071-080/Simplify Path.cpp",
    "content": "class Solution {\npublic:\n    string simplifyPath(string path) {\n        string res, tmp;\n        vector<string> stk;\n        stringstream ss(path);\n        while(getline(ss,tmp,'/')) {\n            if (tmp == \"\" or tmp == \".\") continue;\n            if (tmp == \"..\" and !stk.empty()) stk.pop_back();\n            else if (tmp != \"..\") stk.push_back(tmp);\n        }\n        for(auto str : stk) res += \"/\"+str;\n        return res.empty() ? \"/\" : res;\n    }\n};\n"
  },
  {
    "path": "cpp/071-080/Sort Colors.cpp",
    "content": "class Solution {\npublic:\n    void sortColors(vector<int>& nums) {\n        int i = 0, j = 0;\n        for (int r = 0; r < nums.size(); r++) {\n            if (nums[r] == 0) {\n                swap(nums[j], nums[r]);\n                swap(nums[i], nums[j]);\n                i++;\n                j++;\n            } else if (nums[r] == 1) {\n                swap(nums[r], nums[j]);\n                j++;\n            }\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/071-080/Subsets.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int> > subsets(vector<int> &S) {\n        \n        sort(S.begin(),S.end());\n        vector<vector<int>> sets;\n        vector<int> empty;\n        sets.push_back(empty);\n        int num = 1;\n        for(int i = 0;i < S.size();i++)\n        {\n            for(int k = 0;k < num;k++)\n            {\n                vector<int> tmp = sets[k];\n                tmp.push_back(S[i]);\n                sets.push_back(tmp);\n            }\n            num *= 2;\n        }\n        return sets;\n    }\n};\n"
  },
  {
    "path": "cpp/071-080/Word Search.cpp",
    "content": "class Solution {\npublic:\n    bool dfs(vector<vector<char>>& board, const string &word, int i, int j, int ind) {\n        if (ind == word.size()) {\n            return true;\n        }\n        if (i >= board.size() || j >= board[0].size() || i < 0 || j < 0) return false;\n        if (board[i][j] == 0 || board[i][j] != word[ind]) return false;\n\n        board[i][j] = 0;\n        if (dfs(board, word, i+1, j, ind + 1)) return true;\n        if (dfs(board, word, i, j+1, ind + 1)) return true;\n        if (dfs(board, word, i-1, j, ind + 1)) return true;\n        if (dfs(board, word, i, j-1, ind + 1)) return true;\n        board[i][j] = word[ind];\n\n        return false;\n    }\n    \n    bool exist(vector<vector<char>>& board, string word) {\n        int m = board.size();\n        if (m == 0) return false;\n        int n = board[0].size();\n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                if (dfs(board, word, i, j, 0)) return true;\n            }\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/081-090/Gray Code.cpp",
    "content": "class Solution {\npublic:\n    vector<int> grayCode(int n) {\n        vector<int> v{0};\n        for (int i = 0; i < n; i++) {\n            int len = v.size();\n            for (int j = len-1; j >= 0; j--)\n                v.push_back(v[j] | (1 << i) );\n        }\n        return v;\n    }\n};\n"
  },
  {
    "path": "cpp/081-090/Largest Rectangle in Histogram.cpp",
    "content": "class Solution {\npublic:\n    int largestRectangleArea(vector<int> &hist) {\n        int res(0);\n        stack<int> s;\n        hist.push_back(0);\n        for (int i = 0;i < hist.size();i++) {\n            while (!s.empty() && hist[i] < hist[s.top()]) {\n                int tp = s.top();\n                int h = hist[tp];\n                s.pop();\n            \n                int tmp = h * (s.empty() ? i : i-s.top()-1);\n                res = max(res, tmp);\n            }\n            s.push(i);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/081-090/Maximal Rectangle.cpp",
    "content": "class Solution {\npublic:\n    int maximalRectangle(vector<vector<char>>& matrix) {\n        if (matrix.size() <= 0) return 0;\n        int h[matrix[0].size()+1];\n        memset(h, 0, sizeof(int) * (matrix[0].size()+1));\n        int res(0);\n        \n        for (int i = 0;i < matrix.size();i++) {\n            stack<int> s;\n            matrix[i].push_back('0');\n            \n            for (int j = 0;j < matrix[0].size();j++) {\n                if (matrix[i][j] == '0') h[j] = 0;\n                else h[j]++;\n\n                while (!s.empty() && h[j] < h[s.top()]) {\n                    int tp = s.top();\n                    s.pop();\n                    int height = h[tp];\n                \n                    int tmp = height * (s.empty() ? j : j - s.top() - 1);\n                    res = max(res, tmp);\n                }\n                s.push(j);\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/081-090/Merge Sorted Array.cpp",
    "content": "class Solution {\npublic:\n    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {\n        int i = m - 1;\n        int j = n - 1;\n        int k = m + n - 1;\n        \n        while (i >= 0 && j >= 0) {\n            if (nums1[i] >= nums2[j]) {\n                nums1[k] = nums1[i];\n                i--;\n            } else {\n                nums1[k] = nums2[j];\n                j--;\n            }\n            \n            k--;\n        }\n        \n        while (i >= 0) {\n            nums1[k] = nums1[i];\n            k--;\n            i--;\n        }\n        \n        while (j >= 0) {\n            nums1[k] = nums2[j];\n            k--;\n            j--;\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/081-090/Partition List.cpp",
    "content": "class Solution {\npublic:\n    ListNode *partition(ListNode *head, int x) {\n        \n        ListNode *head1 = new ListNode(0);\n        ListNode *head2 = new ListNode(0);\n        ListNode *h1 = head1;\n        ListNode *h2 = head2;\n        while(head)\n        {\n            int v = head->val;\n            if(v < x)\n            {\n                head1->next = head;\n                head1 = head1->next;\n            } else {\n                head2->next = head;\n                head2 = head2->next;\n            }\n            head = head->next;\n        }\n        head2->next = NULL;\n        head1->next = h2->next;;\n        return h1->next;\n        \n    }\n};\n"
  },
  {
    "path": "cpp/081-090/Remove Duplicates from Sorted List II.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <vector>\n#include <cmath>\n#include <stack>\n#include <string>\n\nusing namespace std;\n\n\nstruct ListNode {\n    int val;\n    ListNode *next;\n    ListNode(int x) : val(x), next(NULL) {}\n};\n \nclass Solution {\npublic:\n    ListNode *deleteDuplicates(ListNode *head) {\n        \n        ListNode *result = new ListNode(INT_MIN);\n        ListNode *_head = result;\n        int prev(INT_MIN);\n        \n        while(head)\n        {\n            if(head->val != prev && ( (!head->next) || head->val != head->next->val) )\n            {\n                _head->next = head;\n                _head = head;\n            }\n            \n            prev = head->val;\n            head = head->next;\n        }\n        _head->next = NULL;\n        return result->next;\n        \n    }\n    \n    \n};\n\nint main()\n{\n    Solution s;\n    ListNode *n1 = new ListNode(1);\n    ListNode *n2 = new ListNode(2);\n    ListNode *n3 = new ListNode(2);\n    n1->next = n2;\n    n2->next = n3;\n    \n    ListNode *head = s.deleteDuplicates(n1);\n    \n    while(head)\n    {\n        cout << head->val << \" \";\n        head = head->next;\n    }\n}"
  },
  {
    "path": "cpp/081-090/Remove Duplicates from Sorted List.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <vector>\n#include <cmath>\n#include <stack>\n#include <string>\n\nusing namespace std;\n\n\nstruct ListNode {\n    int val;\n    ListNode *next;\n    ListNode(int x) : val(x), next(NULL) {}\n};\n \nclass Solution {\npublic:\n    ListNode* deleteDuplicates(ListNode* head) {\n        \n        ListNode *node(head);\n        while(node && node->next)\n        {\n            if (node->val == node->next->val)\n                node->next = node->next->next;\n            else\n                node = node->next;\n        }\n        \n        return head;\n    }\n    \n};\n\nint main()\n{\n    Solution s;\n    ListNode *n1 = new ListNode(1);\n    ListNode *n2 = new ListNode(2);\n    ListNode *n3 = new ListNode(2);\n    n1->next = n2;\n    n2->next = n3;\n    \n    ListNode *head = s.deleteDuplicates(n1);\n    \n    while(head)\n    {\n        cout << head->val << \" \";\n        head = head->next;\n    }\n}"
  },
  {
    "path": "cpp/081-090/Scramble String.cpp",
    "content": "class Solution {\n    \npublic:\n    bool isScramble(string s1, string s2) {\n        // Note: The Solution object is instantiated only once.\n    \tif (s1.length() != s2.length()) return false;\n\t\tif (s1 == s2) return true;\n\n\t\tint A[26] = {0};\n\t\tfor (int i = 0; i < s1.length(); i++)\n\t\t\t++A[s1[i]-'a'];\n\t\tfor (int j = 0; j < s2.length(); j++)\n\t\t\t--A[s2[j]-'a'];\n\t\tfor (int k = 0; k < 26; k++)\n\t\t\tif(A[k] != 0) return false;\n\n        for(int i = 1; i < s1.length(); i++) {\n\t\t\tbool result = isScramble(s1.substr(0,i), s2.substr(0,i)) \n\t\t\t\t&& isScramble(s1.substr(i), s2.substr(i));\n\t\t\tresult = result || (isScramble(s1.substr(0,i), s2.substr(s2.length()-i, i))\n\t\t\t\t&& isScramble(s1.substr(i), s2.substr(0,s2.length()-i)));\n\t\t\tif (result) return true;\n\t\t}\n\t\treturn false;\n    }\n};\n"
  },
  {
    "path": "cpp/081-090/Search in Rotated Sorted Array II.cpp",
    "content": "class Solution {\npublic:\n    bool search(vector<int>& nums, int target) {\n        int i = 0;\n        int j = nums.size() - 1;\n        \n        while (i <= j) {\n            int mid = (i + j) / 2;\n            if (nums[mid] == target) return true;\n            \n            if (nums[mid] < nums[i]) {\n                if (nums[mid] < target && nums[j] >= target) i = mid + 1;\n                else j = mid - 1;\n            } else if (nums[mid] > nums[i]) {\n                if (nums[mid] > target && nums[i] <= target) j = mid - 1;\n                else i = mid + 1;\n            } else {\n                i++;\n            }\n        }\n        \n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/081-090/Subsets II.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> subsetsWithDup(vector<int>& nums) {\n        \n        sort(nums.begin(), nums.end());\n        \n        vector<vector<int>> sets;\n        vector<int> empty;\n        sets.push_back(empty);\n        int num = 1;\n        int prev(INT_MIN);\n        for(int i = 0;i < nums.size();i++)\n        {\n            int number = nums[i];\n            if(number != prev)\n            {\n                num = sets.size();\n                for(int k = 0;k < num;k++)\n                {\n                    vector<int> tmp = sets[k];\n                    tmp.push_back(number);\n                    sets.push_back(tmp);\n                }\n                prev = number;\n            } else {\n                int index = sets.size()-num;\n                for(int k = 0;k < num;k++)\n                {\n                    vector<int> tmp = sets[k+index];\n                    tmp.push_back(number);\n                    sets.push_back(tmp);\n                }\n            }\n        }\n        return sets;\n        \n    }\n};\n"
  },
  {
    "path": "cpp/091-100/Binary Tree Inorder Traversal.cpp",
    "content": "class Solution {\npublic:\n    vector<int> inorderTraversal(TreeNode* root) {\n        vector<int> result;\n        stack<TreeNode*> node_in_path;\n        TreeNode* current_node = root;\n        \n        while (current_node || !node_in_path.empty())\n        {\n            while (current_node)\n            {\n                node_in_path.emplace(current_node);\n                current_node = current_node->left;\n            }\n                \n            current_node = node_in_path.top();\n            node_in_path.pop();\n            result.push_back(current_node->val);\n            current_node = current_node->right;\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/091-100/Decode Ways.cpp",
    "content": "class Solution {\n    \n    bool valid(char ch1, char ch2)\n    {\n        if(ch1 == '1')\n            return true;\n        else if(ch1 == '2')\n        {\n            if(ch2 <= '6')\n                return true;\n            return false;\n        }\n        return false;\n    }\n    \npublic:\n    int numDecodings(string s) {\n        \n        int n = s.length();\n        if(n == 0) return 0;\n        \n        int *p = new int[n+1];\n        p[0] = 1;\n        p[1] = 1;\n        if(s[0] == '0') p[1] = 0;\n        \n        for(int i = 0;i < n-1;i++)\n        {\n            if(s[i+1] == '0')\n            {\n                if (s[i] >= '1' && s[i] <= '2')\n                    p[i+2] = p[i];\n                else \n                    p[i+2] = 0;\n            } else if(s[i] == '0') {\n                p[i+2] = p[i+1];\n            }\n            else if(valid(s[i], s[i+1]))\n                p[i+2] = p[i]+p[i+1];\n            else\n                p[i+2] = p[i+1];\n        }\n        \n        return p[n];\n    }\n};\n"
  },
  {
    "path": "cpp/091-100/Interleaving String.cpp",
    "content": "class Solution {\n    \npublic:\n    bool isInterleave(string s1, string s2, string s3) {\n        if(s1.length() + s2.length() != s3.length())\n            return false;\n        \n        bool table[s1.length()+1][s2.length()+1];\n        for(int i = 0;i <= s1.length();i++)\n            for(int j = 0;j <= s2.length();j++)\n                table[i][j] = false;\n\n        \n        table[0][0] = true;\n        for(int i = 1;i <= s1.length();i++)\n            if(s3[i-1] == s1[i-1] && table[i-1][0])\n                table[i][0] = true;\n\n        for(int j = 1;j <= s2.length();j++)\n            if(s3[j-1] == s2[j-1] && table[0][j-1])\n                table[0][j] = true;\n        \n        for(int i = 1;i <= s1.length();i++)\n        {\n            for(int j = 1;j <= s2.length();j++)\n            {\n                if(s3[i+j-1] == s1[i-1] && table[i-1][j] == true)\n                    table[i][j] = true;\n                if(s3[i+j-1] == s2[j-1] && table[i][j-1] == true)\n                    table[i][j] = true;\n            }\n        }\n\n        return table[s1.length()][s2.length()];\n    }\n    \n};\n"
  },
  {
    "path": "cpp/091-100/Recover Binary Search Tree.cpp",
    "content": "class Solution {\npublic:\n    void recoverTree(TreeNode* root) {\n        stack<TreeNode*>s;\n        TreeNode *p = root;\n        TreeNode *prev(nullptr);\n        bool fff(false);\n        TreeNode *n1(nullptr), *n2(nullptr);\n        \n        while (p || !s.empty()) {\n            while (p) {\n                s.push(p);\n                p = p->left;\n            }\n            p = s.top();\n            s.pop();\n            if (prev && prev->val > p->val) {\n                n2 = p;\n                if (!fff){\n                    fff = true;\n                    n1 = prev;\n                } else {\n                    swap(n1->val, n2->val);\n                    return;\n                }\n            }\n            prev = p;\n            p = p->right;\n        }\n        swap(n1->val, n2->val);\n    }\n};\n"
  },
  {
    "path": "cpp/091-100/Restore IP Addresses.cpp",
    "content": "class Solution {\npublic:\n    vector<string> restoreIpAddresses(string s) {\n        vector<string> ret;\n        string ans;\n        \n        for (int a=1; a<=3; a++)\n        for (int b=1; b<=3; b++)\n        for (int c=1; c<=3; c++)\n        for (int d=1; d<=3; d++)\n            if (a+b+c+d == s.length()) {\n                int A = stoi(s.substr(0, a));\n                int B = stoi(s.substr(a, b));\n                int C = stoi(s.substr(a+b, c));\n                int D = stoi(s.substr(a+b+c, d));\n                if (A <= 255 && B <= 255 && C <= 255 && D <= 255)\n                    // 000000 => false\n                    if ( (ans=to_string(A)+\".\"+to_string(B)+\".\"+to_string(C)+\".\"+to_string(D)).length() == s.length()+3)\n                        ret.push_back(ans);\n            }    \n        \n        return ret;\n    }\n};\n"
  },
  {
    "path": "cpp/091-100/Reverse Linked List II.cpp",
    "content": "class Solution {\npublic:\n    ListNode *reverseBetween(ListNode *head, int m, int n) {\n        int d = n - m;\n        if(m == n) return head;\n        int ttt = m;\n        \n        ListNode *answer = new ListNode(0);\n        answer->next = head;\n        \n        while(--m > 1)\n            head = head->next;\n        ListNode *left = ttt == 1 ? answer : head;\n        ListNode *r_head = left->next;\n        \n        head = r_head;\n        ListNode *tmp = head->next;\n        while(d-- > 0) {\n            ListNode *n = tmp->next;\n            tmp -> next = head;\n            head = tmp;\n            tmp = n;\n        }\n\n        left->next = head;\n        r_head->next = tmp;\n        \n        return answer->next;\n    }\n};\n"
  },
  {
    "path": "cpp/091-100/Same Tree.cpp",
    "content": "class Solution {\npublic:\n    bool isSameTree(TreeNode* p, TreeNode* q) {\n        if (p == nullptr && q == nullptr) return true;\n        if ( (p && !q) || (q && !p) ) return false;\n        if (p->val != q->val) return false;\n        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);\n    }\n};\n"
  },
  {
    "path": "cpp/091-100/Unique Binary Search Trees II.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    vector<TreeNode *> generate(int beg, int end) {\n        vector<TreeNode* > ret;\n        if (beg > end) {\n            ret.push_back(nullptr);\n            return ret;\n        }\n        \n        for (int i = beg; i <= end; i++) {\n            vector<TreeNode* > leftTree = generate(beg, i - 1);\n            vector<TreeNode* > rightTree = generate(i + 1, end);\n            for (int j = 0; j < leftTree.size(); j++) {\n                for (int k = 0; k < rightTree.size(); k++) {\n                    TreeNode *node = new TreeNode(i);\n                    ret.push_back(node);\n                    node->left = leftTree[j];\n                    node->right = rightTree[k];              \n                }\n            }\n        }\n        return ret;\n    }\n\npublic:\n\n    vector<TreeNode *> generateTrees(int n) {\n        if (n == 0) return vector<TreeNode *>();\n        return generate(1, n);\n    }\n};\n"
  },
  {
    "path": "cpp/091-100/Unique Binary Search Trees.cpp",
    "content": "class Solution {\npublic:\n    int numTrees(int n) {\n        vector<int> dp(n+1, 0);\n        dp[0] = dp[1] = 1;\n        \n        for (int i = 2;i <= n;i++)\n            for (int k = 0;k < n;k++)\n                dp[i] += dp[k]*dp[i-k-1];\n        \n        return dp[n];\n    }\n};\n"
  },
  {
    "path": "cpp/091-100/Validate Binary Search Tree.cpp",
    "content": "class Solution {\npublic:\n    bool isValidBST(TreeNode* root) {\n        stack<TreeNode*>s;\n        TreeNode *p = root;\n        int prev(INT_MIN);\n        bool first(true);\n        \n        while (p!= nullptr || !s.empty()) {\n            while (p != nullptr) {\n                s.push(p);\n                p = p->left;\n            }\n            p = s.top();\n            s.pop();\n            if (first) {\n                prev = p->val;\n                first = false;\n            } else if (p->val <= prev) {\n                return false;\n            }\n            prev = p->val;\n            p = p->right;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1001-1010/Construct Binary Search Tree from Preorder Traversal.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    TreeNode* dfs(int& i, vector<int>& preorder, int lower, int upper) {\n        if (i >= preorder.size()) return nullptr;\n        \n        int v = preorder[i];\n        \n        if (v < lower || v > upper) return nullptr;\n        \n        TreeNode* root = new TreeNode(v);\n        \n        i++;\n        \n        root->left = dfs(i, preorder, lower, v);\n        \n        root->right = dfs(i, preorder, v, upper);\n        \n        return root;\n    }\n    \npublic:\n    TreeNode* bstFromPreorder(vector<int>& preorder) {\n        int i = 0;\n        return dfs(i, preorder, -99999999, 99999999);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1011-1020/Best Sightseeing Pair.cpp",
    "content": "class Solution {\npublic:\n    int maxScoreSightseeingPair(vector<int>& A) {\n        int best_i = 0;\n        int ans = 0;\n        \n        for (int i = 1; i < A.size(); i++) {\n            ans = max(ans, A[best_i] + A[i] + best_i - i);\n            if (i + A[i] >= best_i + A[best_i]) {\n                best_i = i;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1011-1020/Binary Prefix Divisible By 5.cpp",
    "content": "class Solution {\npublic:\n    vector<bool> prefixesDivBy5(vector<int>& A) {\n        vector<bool> answer(A.size());\n        int v = 0;\n        \n        int i = 0;\n        for (int e : A) {\n            v = 2*v + e;\n            v %= 5;\n            answer[i] = v == 0;\n            i++;\n        }\n        \n        return answer;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1011-1020/Binary String With Substrings Representing 1 To N.cpp",
    "content": "class Solution {\npublic:\n    bool queryString(string S, int N) {\n        for (int i = N; i >= 1; i--) {\n            int number = i;\n            string str_num = \"\";\n\t\t\n            // Convert the number to string\n            while(number!=0) {\n                str_num += number%2 + '0';\n                number = number/2;\n            }\n        \n            reverse(str_num.begin(), str_num.end());\n            if(S.find(str_num)==string::npos) \n                return false;\n        }\n    \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1011-1020/Convert to Base -2.cpp",
    "content": "class Solution {\npublic:\n    string baseNeg2(int N) {\n        if (N == 0) return \"0\";\n        string ans;\n        \n        while(N != 0) {\n            if (N % 2 != 0) {\n                ans = '1' + ans;\n                N--;\n            } else {\n                ans = '0' + ans;\n            }\n            \n            N = -(N/2);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1011-1020/Next Greater Node In Linked List.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<int> nextLargerNodes(ListNode* head) {\n        int current_index = 0;\n        vector<int> ans(10001, 0);\n        stack<pair<int, int>> mystack;\n        \n        while (head) {\n            while (!mystack.empty() && mystack.top().second < head->val) {\n                pair<int, int> e = mystack.top();\n                mystack.pop();\n                ans[e.first] = head->val;\n            }\n            mystack.push({current_index, head->val});\n            head = head->next;\n            current_index++;\n        }\n        \n        ans.resize(current_index);\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1011-1020/Number of Enclaves.cpp",
    "content": "class Solution {\n    \n    pair<int, int> tmp[4] = {{1,0}, {-1,0}, {0,1}, {0,-1}};\n    \n    int m;\n    int n;\n    \n    void dfs(vector<vector<int>>& A, int i, int j) {\n        if (A[i][j] == 0) return;\n        A[i][j] = 2;\n        for (int k = 0; k < 4; k++) {\n            int n_i = i + tmp[k].first;\n            int n_j = j + tmp[k].second;\n            if (n_i < 0 || n_j < 0 || n_i >= m || n_j >= n) continue;\n            if (A[n_i][n_j] == 1) dfs(A, n_i, n_j);\n        }\n    }\n    \npublic:\n    int numEnclaves(vector<vector<int>>& A) {\n        m = A.size();\n        n = A.front().size();\n        \n        for (int i = 0; i < m; i++) {\n            dfs(A, i, 0);\n            dfs(A, i, n-1);\n        }\n        \n        for (int j = 0; j < n; j++) {\n            dfs(A, 0, j);\n            dfs(A, m-1, j);\n        }\n        \n        int ans = 0;\n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                if (A[i][j] == 1) {\n                    ans++;\n                }\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1011-1020/Partition Array Into Three Parts With Equal Sum.cpp",
    "content": "class Solution {\npublic:\n    bool canThreePartsEqualSum(vector<int>& A) {\n        int target = std::accumulate(A.begin(), A.end(), 0) / 3;\n        \n        int sum = 0;\n        int times = 0;\n        for (int e : A) {\n            sum += e;\n            if (sum == target) {\n                times++;\n                sum = 0;\n            }\n        }\n        \n        return times >= 3;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1021-1030/Camelcase Matching.cpp",
    "content": "class Solution {\npublic:\n    vector<bool> camelMatch(vector<string>& queries, string pattern) {\n        vector<bool> ans;\n        \n        for (const string& query : queries) {\n            \n            int i = 0;\n            bool find = true;\n            \n            for (int j = 0; j < query.length(); j++) {\n                if (i >= pattern.size()) {\n                    if (isupper(query[j])) {\n                        find = false;\n                        break;\n                    }\n                    continue;\n                }\n                char target = pattern[i];\n                if (target == query[j]) {\n                    i++;\n                } else if (isupper(query[j])) {\n                    find = false;\n                    break;\n                }\n            }\n            \n            find &= i >= pattern.size();\n            \n            ans.push_back(find);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1021-1030/Divisor Game.cpp",
    "content": "class Solution {\n    map<int, bool> dp;\npublic:\n    bool divisorGame(int N) {\n        if (N == 0) return false;\n        if (dp.count(N) > 0) return dp[N];\n        for (int i = 1; i < N; i++) {\n            if (N % i == 0) {\n                bool win = !divisorGame(N - i);\n                if (win) {\n                    return dp[N] = win;\n                }\n            }\n        }\n        \n        return dp[N] = false;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1021-1030/Longest Arithmetic Sequence.cpp",
    "content": "class Solution {\npublic:\n    int longestArithSeqLength(vector<int>& A) {\n        unordered_map<int, int> dp;\n        int ans = 0;\n        \n        for (int i = 0; i < A.size(); i++) {\n            for (int j = 0; j < i; j++) {\n                int d = A[i] - A[j];\n                int key1 = i * 20001 + d;\n                int key2 = j * 20001 + d;\n                dp[key1] = max(dp[key1], 1 + dp[key2]);\n                ans = max(ans, dp[key1]);\n            }\n        }\n        \n        return ans + 1;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1021-1030/Matrix Cells in Distance Order.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> allCellsDistOrder(int R, int C, int r0, int c0) {\n        vector<vector<int>> myqueue;\n        myqueue.push_back({r0, c0});\n        int i = 0;\n        int dis = 0;\n        \n        pair<int, int> tmp[4] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n        \n        while (i < myqueue.size()) {\n            int next_i = myqueue.size();\n            dis++;\n            unordered_set<int> visited;\n            \n            for (int k = i; k < next_i; k++) {\n                \n                int x = myqueue[k][0];\n                int y = myqueue[k][1];\n                \n                for (int j = 0; j < 4; j++) {\n                    int n_x = x + tmp[j].first;\n                    int n_y = y + tmp[j].second;\n                    if (n_x < 0 || n_y < 0 || n_x >= R || n_y >= C) continue;\n                    int d = abs(r0 - n_x) + abs(c0 - n_y);\n                    if (dis != d) continue;\n                    int hash_ = n_x * 101 + n_y;\n                    if (visited.count(hash_) > 0) continue;\n                    myqueue.push_back({n_x, n_y});\n                    visited.insert(hash_);\n                }\n                \n            }\n            \n            i = next_i;\n        }\n        \n        return myqueue;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1021-1030/Maximum Difference Between Node and Ancestor.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    int dfs(TreeNode* root, int min_, int max_) {\n        if (!root) return 0;\n        \n        int current = max(abs(min_ - root->val), abs(max_ - root->val));\n        \n        min_ = min(min_, root->val);\n        max_ = max(max_, root->val);\n        \n        return max(current, max(dfs(root->left, min_, max_), dfs(root->right, min_, max_)));\n    }\n    \npublic:\n    int maxAncestorDiff(TreeNode* root) {\n        return dfs(root, root->val, root->val);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1021-1030/Recover a Tree From Preorder Traversal.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    TreeNode* dfs(const string& S, int& i, int d) {\n        int dash_count = 0;\n        int i_ = i;\n        while (i_ < S.length() && S[i_] == '-') {\n            dash_count++;\n            i_++;\n        }\n        \n        if (dash_count != d) return nullptr;\n        \n        int num = 0;\n        \n        while (i_ < S.length() && isdigit(S[i_])) {\n            num = 10 * num + (S[i_] - '0');\n            i_++;\n        }\n        \n        i = i_;\n        TreeNode* node = new TreeNode(num);\n        node->left = dfs(S, i, d+1);\n        node->right = dfs(S, i, d+1);\n        \n        return node;\n    }\n    \npublic:\n    TreeNode* recoverFromPreorder(string S) {\n        int i = 0;\n        return dfs(S, i, 0);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1021-1030/Remove Outermost Parentheses.cpp",
    "content": "class Solution {\npublic:\n    string removeOuterParentheses(string S) {\n        string return_ans;\n        stack<char> mystack;\n        \n        for (char ch : S) {\n            if (mystack.empty()) {\n                mystack.push(ch);\n            } else {\n                if (ch == '(') {\n                    mystack.push(ch);\n                    return_ans += '(';\n                } else {\n                    mystack.pop();\n                    if (!mystack.empty()) {\n                        return_ans += ')';\n                    }\n                }\n            }\n        }\n        \n        return return_ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1021-1030/Sum of Root To Leaf Binary Numbers.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    int dfs(TreeNode* root, int carry) {\n        if (!root) return 0;\n        if (!root->left && !root->right) {\n            return 2*carry + root->val;\n        }\n        \n        carry = 2 * carry + root->val;\n        return dfs(root->left, carry) + dfs(root->right, carry);\n    }\n    \npublic:\n    int sumRootToLeaf(TreeNode* root) {\n        return dfs(root, 0);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1021-1030/Two City Scheduling.cpp",
    "content": "class Solution {\npublic:\n    int twoCitySchedCost(vector<vector<int>>& costs) {\n        sort(begin(costs), end(costs), [](vector<int> &v1, vector<int> &v2) {\n            return abs(v1[0] - v1[1]) > abs(v2[0] - v2[1]);\n        });\n      \n        int a = costs.size()/2;\n        int b = costs.size()/2;\n        \n        int ans = 0;\n        \n        for (const vector<int>& cost : costs) {\n            if (a == 0) {\n                ans += cost[1];\n                continue;\n            }\n            if (b == 0) {\n                ans += cost[0];\n                continue;\n            }\n            if (cost[0] <= cost[1]) {\n                ans += cost[0];\n                a--;\n            } else {\n                ans += cost[1];\n                b--;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1021-1030/Video Stitching.cpp",
    "content": "class Solution {\npublic:\n    int videoStitching(vector<vector<int>>& clips, int T) {\n        auto cmp = [](const vector<int>& a, const vector<int>& b) {\n            return a[0] <= b[0];\n        };\n        sort(clips.begin(), clips.end(), cmp);\n        \n        int k = 0;\n        int next_k = -1;\n        int ans = 0;\n        \n        for (const vector<int>& clip : clips) {\n            if (clip[0] > k && clip[0] <= next_k) {\n                ans++;\n                k = next_k;\n            }\n            \n            if (clip[0] <= k) {\n                next_k = max(next_k, clip[1]);\n                if (next_k >= T) return ans + 1;\n            }\n        }\n        \n        return next_k >= T ? ans : -1;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1031-1040/Binary Search Tree to Greater Sum Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    void dfs(TreeNode* root, int& v) {\n        if (!root) return;\n        dfs(root->right, v);\n        v += root->val;\n        root->val = v;\n        dfs(root->left, v);\n    }\n    \npublic:\n    TreeNode* bstToGst(TreeNode* root) {\n        int v = 0;\n        dfs(root, v);\n        return root;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1031-1040/Coloring A Border.cpp",
    "content": "class Solution {\n    \n    int old_color;\n    int new_color;\n    int row;\n    int col;\n    pair<int, int> tmp[4] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};\n    \n    void dfs(vector<vector<int>>& grid, int i, int j, vector<vector<bool>>& visited) {\n        visited[i][j] = true;\n        \n        bool has_non_connected_cells = false;\n        for (int k = 0; k < 4; k++) {\n            int new_i = i + tmp[k].first;\n            int new_j = j + tmp[k].second;\n            if (new_i < 0 || new_j < 0 || new_i >= row || new_j >= col || visited[new_i][new_j]) continue;\n            if (grid[new_i][new_j] == old_color) {\n                dfs(grid, new_i, new_j, visited);\n            } else {\n                has_non_connected_cells = true;\n            }\n        }\n        \n        has_non_connected_cells |= (i == 0 || j == 0 || i == row-1 || j == col-1);\n        \n        if (has_non_connected_cells) {\n            grid[i][j] = new_color;\n        }\n    }\n    \npublic:\n    vector<vector<int>> colorBorder(vector<vector<int>>& grid, int r0, int c0, int color) {\n        old_color = grid[r0][c0];\n        new_color = color;\n        row = grid.size();\n        col = grid.front().size();\n        vector<vector<bool>> visited(row, vector<bool>(col, false));\n        dfs(grid, r0, c0, visited);\n        return grid;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1031-1040/Escape a Large Maze.cpp",
    "content": "class Solution {\n    \n    bool find = false;\n    \n    pair<int, int> tmp[4] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};\n    \n    bool isEscapePossibleInternal(vector<vector<int>>& blocked, vector<int>& source, vector<int>& target) {\n        set<pair<int, int>> visited;\n        for (const vector<int>& b : blocked) {\n            visited.insert({b[0], b[1]});\n        }\n        \n        stack<pair<int, int>> mystack;\n        mystack.push({source[0], source[1]});\n        visited.insert({source[0], source[1]});\n        \n        while (!mystack.empty()) {\n            pair<int, int> ele = mystack.top();\n            mystack.pop();\n            if (ele.first == target[0] && ele.second == target[1]) { find = true; return true; }\n            int dis = abs(ele.first - source[0]) + abs(ele.second - source[1]);\n            if (dis > blocked.size()) return true;\n            \n            for (int k = 0; k < 4; k++) {\n                int n_i = ele.first + tmp[k].first;\n                int n_j = ele.second + tmp[k].second;\n                if (n_i < 0 || n_j < 0 || n_i >= 1e6 || n_j >= 1e6) continue;\n                if (visited.count({n_i, n_j}) > 0) continue;\n                \n                visited.insert({n_i, n_j});\n                mystack.push({n_i, n_j});\n            }\n        }\n        \n        return false;\n    }\n    \npublic:\n    bool isEscapePossible(vector<vector<int>>& blocked, vector<int>& source, vector<int>& target) {\n        if (!isEscapePossibleInternal(blocked, source, target)) return false;\n        if (find) return true;\n        return isEscapePossibleInternal(blocked, target, source);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1031-1040/Maximum Sum of Two Non-Overlapping Subarrays.cpp",
    "content": "class Solution {\npublic:\n    int maxSumTwoNoOverlap(vector<int>& A, int L, int M) {\n        vector<int> sum = {0};\n        for(auto x:A) sum.push_back(sum.back()+x);\n        return max(help(sum, L, M), help(sum, M,L));\n    }\n    \n    int help(const vector<int>& sum, int L, int M) {\n        int maxSumL = sum[L], maxSumLM = sum[L+M];\n        for(int i=L+M+1;i<sum.size();i++){\n            int curSumL = sum[i-M] - sum[i-M-L];\n            int curSumM = sum[i]-sum[i-M];\n            maxSumL = max(maxSumL, curSumL);\n            maxSumLM = max(maxSumLM, maxSumL + curSumM);\n        }\n        return maxSumLM;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1031-1040/Minimum Score Triangulation of Polygon.cpp",
    "content": "class Solution {\n    \n    int dfs(vector<int>& A, map<pair<int, int>, int>& cache, int start_index, int end_index) {\n        pair<int, int> key = {start_index, end_index};\n        auto it = cache.find(key);\n        if (it != cache.end()) return it->second;\n        \n        if (end_index - start_index < 2) {\n            return 0;\n        }\n        if (end_index - start_index == 2) {\n            return A[start_index] * A[start_index+1] * A[start_index+2];\n        }\n        \n        int ans = INT_MAX;\n        for (int i = start_index+1; i < end_index; i++) {\n            int current = A[start_index] * A[i] * A[end_index];\n            current += dfs(A, cache, start_index, i);\n            current += dfs(A, cache, i, end_index);\n            ans = min(ans,  current);\n        }\n        \n        return cache[key] = ans;\n    }\n    \npublic:\n    int minScoreTriangulation(vector<int>& A) {\n        map<pair<int, int>, int> cache;\n        return dfs(A, cache, 0, A.size() - 1);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1031-1040/Moving Stones Until Consecutive.cpp",
    "content": "class Solution {\npublic:\n    vector<int> numMovesStones(int a, int b, int c) {\n        vector<int> v{a,b,c};\n        sort(v.begin(), v.end());\n        int maximum_move = v[2] - v[0] - 2;\n        \n        int d1 = v[1] - v[0];\n        int d2 = v[2] - v[1];\n        \n        int minimum_move = 0;\n        \n        if (d1 == 1 && d2 == 1) return {0, maximum_move};\n        if (d1 == 1 || d2 == 1 || d1 == 2 || d2 == 2) return {1, maximum_move};\n        \n        return {2, maximum_move};\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1031-1040/Stream of Characters.cpp",
    "content": "struct TrieNode {\n    TrieNode *nodes[26];\n    bool word;\n    // Initialize your data structure here.\n    TrieNode(): word(false) {\n        memset(nodes, 0, sizeof(nodes));\n    }\n};\n\nclass Trie {\n    \npublic:\n    Trie() {\n        root = new TrieNode();\n    }\n    \n    // Inserts a word into the trie.\n    void insert(const string& s) {\n        TrieNode *tmp = root;\n        for(char ch : s) {\n            int index = ch - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                tmp->nodes[index] = new TrieNode();\n            }\n            tmp = tmp->nodes[index];\n        }\n        tmp->word = true;\n    }\n    \n    bool eat(char ch) {\n        vector<TrieNode*> tmp;\n        if (root->nodes[ch - 'a'] != nullptr) {\n            tmp.push_back(root->nodes[ch - 'a']);\n        }\n        for (TrieNode* node : state) {\n            if (node->nodes[ch - 'a'] != nullptr) {\n                tmp.push_back(node->nodes[ch - 'a']);\n            }\n        }\n        \n        swap(state, tmp);\n        bool return_val = false;\n        for (TrieNode* node : state) {\n            if (node->word) {\n                return_val = true;\n                break;\n            }\n        }\n        return return_val;\n    }\n\n    \nprivate:\n    TrieNode* root;\n    vector<TrieNode*> state;\n};\n\nclass StreamChecker {\n    Trie trie;\npublic:\n    StreamChecker(vector<string>& words) {\n        for (const string& word : words) {\n            trie.insert(word);\n        }\n    }\n    \n    bool query(char letter) {\n        return trie.eat(letter);\n    }\n};\n\n/**\n * Your StreamChecker object will be instantiated and called as such:\n * StreamChecker* obj = new StreamChecker(words);\n * bool param_1 = obj->query(letter);\n */\n"
  },
  {
    "path": "cpp/1001-10000/1031-1040/Uncrossed Lines.cpp",
    "content": "class Solution {\npublic:\n    int maxUncrossedLines(vector<int>& A, vector<int>& B) {\n        int m = A.size();\n        int n = B.size();\n        \n        vector<vector<int>> dp(m+1, vector<int>(n+1, 0));\n        \n        for (int i = 1; i <= m; i++) {\n            for (int j = 1; j <= n; j++) {\n                if (A[i-1] == B[j-1]) {\n                    dp[i][j] = 1 + dp[i-1][j-1];\n                } else {\n                    dp[i][j] = max(dp[i-1][j], dp[i][j-1]);\n                }\n            }\n        }\n        \n        return dp[m][n];\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1031-1040/Valid Boomerang.cpp",
    "content": "class Solution {\npublic:\n    bool isBoomerang(vector<vector<int>>& points) {\n        sort(points.begin(), points.end());\n        if (points[0] == points[1] || points[1] == points[2]) return false;\n        \n        int x1 = points[1][0] - points[0][0];\n        int y1 = points[1][1] - points[0][1];\n        int x2 = points[2][0] - points[1][0];\n        int y2 = points[2][1] - points[1][1];\n        \n        if (x1 == 0 || x2 == 0) {\n            return x1 != 0 || x2 != 0;\n        }\n        \n        return fabs(1.0*y1/x1 - 1.0*y2/x2) > 10e-5;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1041-1050/Flower Planting With No Adjacent.cpp",
    "content": "class Solution {\n    vector<int> colors;\n    \n    void dfs(int u, map<int, vector<int>>& edges) {\n        vector<int> neighbors = edges[u];\n        set<int> excluded_colors;\n        for (int neighbor : neighbors) {\n            if (colors[neighbor-1] > 0) {\n                excluded_colors.insert(colors[neighbor-1]);   \n            }\n        }\n        \n        for (int i = 1; i <= 4; i++) {\n            if (excluded_colors.count(i) == 0) {\n                colors[u-1] = i;\n                for (int neighbor : neighbors) {\n                    if (colors[neighbor-1] == 0) {\n                        dfs(neighbor, edges);\n                    }   \n                }\n                break;\n            }\n        }\n    }\n    \npublic:\n    vector<int> gardenNoAdj(int N, vector<vector<int>>& paths) {\n        map<int, vector<int>> edges;\n        for (const vector<int>& path : paths) {\n            edges[path[0]].push_back(path[1]);\n            edges[path[1]].push_back(path[0]);\n        }\n        colors.resize(N, 0);\n        \n        for (int garden = 1; garden <= N; garden++) {\n            if (colors[garden - 1] == 0) {\n                dfs(garden, edges);\n            }\n        }\n        \n        return colors;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1041-1050/Last Stone Weight II.cpp",
    "content": "class Solution {\n\npublic:\n    int lastStoneWeightII(vector<int>& stones) {\n        int sum = 0;\n        bool dp[1501] = {false};\n        dp[0] = true;\n        for (int v : stones) {\n            sum += v;\n            for (int start = sum; start >= v; start--) {\n                // we need to start from back to make it not affected by itself\n                dp[start] = dp[start] | dp[start-v];\n            }\n        }\n        \n        for (int i = sum/2; i > 0; i--) {\n            if (dp[i] == true) {\n                return sum - 2 * i;\n            }\n        }\n        return 0;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1041-1050/Last Stone Weight.cpp",
    "content": "class Solution {\npublic:\n    int lastStoneWeight(vector<int>& stones) {\n        std::priority_queue<int, std::vector<int>, std::less<int> >\n                            myqueue (stones.begin(), stones.end());\n        while (myqueue.size() > 1) {\n            int v1 = myqueue.top();\n            myqueue.pop();\n            int v2 = myqueue.top();\n            myqueue.pop();\n            int v = abs(v1 - v2);\n            if (v > 0) myqueue.push(v);\n        }\n        \n        return myqueue.empty() ? 0 : myqueue.top();\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1041-1050/Longest String Chain.cpp",
    "content": "class Solution {\n    \n    int dfs(const string& word, const unordered_set<string>& dictionary, unordered_map<string, int>& cache) {\n        unordered_map<string, int>::iterator it = cache.find(word);\n        if (it != cache.end()) {\n            return it->second;\n        }\n        \n        int ans = 1;\n        for (int i = 0; i < word.size(); i++) {\n            string c_word = word.substr(0, i) + word.substr(i+1);\n            if (dictionary.count(c_word) > 0) {\n                ans = max(ans, 1 + dfs(c_word, dictionary, cache));\n            }\n        }\n        return cache[word] = ans;\n    }\n    \npublic:\n    int longestStrChain(vector<string>& words) {\n        unordered_set<string> dictionary(begin(words), end(words));\n        unordered_map<string, int> cache;\n        \n        int ans = 1;\n        for (const string& word : words) {\n            ans = max(ans, dfs(word, dictionary, cache));\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1041-1050/Partition Array for Maximum Sum.cpp",
    "content": "class Solution {\npublic:\n    int maxSumAfterPartitioning(vector<int>& A, int K) {\n        vector<int> dp(A.size()+1, 0);\n        \n        for (int i = 0; i < A.size(); i++) {\n            int p_i = max(-1, i - K);\n            int maximum_i_sum = 0;\n            int temp_max = -1;\n            int n_elements = 0;\n            for (int j = i; j > p_i; j--) {\n                n_elements++;\n                temp_max = max(temp_max, A[j]);\n                maximum_i_sum = max(maximum_i_sum, dp[j] + n_elements * temp_max);\n            }\n            \n            dp[i+1] = maximum_i_sum;\n        } \n        \n        return dp.back();\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1041-1050/Remove All Adjacent Duplicates In String.cpp",
    "content": "class Solution {\npublic:\n    string removeDuplicates(string S) {\n        int i = 0;\n        \n        for (char ch : S) {\n            if (i != 0 && ch == S[i-1]) {\n                i--;\n            } else {\n                S[i] = ch;\n                i++;\n            }\n        }\n        \n        return S.substr(0, i);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1041-1050/Robot Bounded In Circle.cpp",
    "content": "class Solution {\n    \n    pair<int, int> getNextDirection(pair<int, int> d, char ch) {\n        if (ch == 'L') {\n            if (d.first == 0 && d.second == 1) {\n                return {-1, 0};\n            }\n            if (d.first == -1 && d.second == 0) {\n                return {0, -1};\n            }\n            if (d.first == 0 && d.second == -1) {\n                return {1, 0};\n            }\n            if (d.first == 1 && d.second == 0) {\n                return {0, 1};\n            }\n        } else {\n            if (d.first == 0 && d.second == 1) {\n                return {1, 0};\n            }\n            if (d.first == 1 && d.second == 0) {\n                return {0, -1};\n            }\n            if (d.first == 0 && d.second == -1) {\n                return {-1, 0};\n            }\n            if (d.first == -1 && d.second == 0) {\n                return {0, 1};\n            }\n        }\n        return {0, 0};\n    }\n    \n    string GetKey(int x, int y, pair<int, int> d) {\n        return to_string(x) + '-' + to_string(y) + '-' + to_string(d.first) + '-' + to_string(d.second);\n    }\n    \npublic:\n    bool isRobotBounded(string instructions) {\n        pair<int, int> d = {0, 1};\n        int x = 0, y = 0;\n        \n        for (char ch : instructions) {\n            if (ch == 'G') {\n                x += d.first;\n                y += d.second;\n            } else {\n                d = getNextDirection(d, ch);\n            }\n        }\n        \n        if (x == 0 && y == 0) return true;\n        if (d.first == 0 && d.second == 1) return false;\n        return true;\n        \n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1051-1060/Distant Barcodes.cpp",
    "content": "class Solution {\npublic:\n    vector<int> rearrangeBarcodes(vector<int>& barcodes) {\n        auto cmp = [](const pair<int, int> &a, const pair<int, int> &b) {\n            return a.second < b.second || (a.second == b.second && a.first > b.first);\n        };\n\n        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp);\n        \n        map<int, int> mymap;\n        for (int e : barcodes) {\n            mymap[e]++;\n        }\n        \n        for (auto it : mymap) {\n            pq.push(it);\n        }\n        \n        vector<int> ans;\n        while (!pq.empty()) {\n            pair<int, int> e1 = pq.top();\n            pq.pop();\n            ans.push_back(e1.first);\n            if (!pq.empty()) {\n                pair<int, int> e2 = pq.top();\n                pq.pop();\n                ans.push_back(e2.first);\n                if (e2.second > 1) {\n                    pq.push({e2.first, e2.second - 1});\n                }\n            }\n            if (e1.second > 1) {\n                pq.push({e1.first, e1.second - 1});\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1051-1060/Grumpy Bookstore Owner.cpp",
    "content": "class Solution {\npublic:\n    int maxSatisfied(vector<int>& customers, vector<int>& grumpy, int X) {\n        int gained = 0;\n        int max_gained = 0;\n        int normal_gained = 0;\n        for (int i = 0; i < grumpy.size(); i++) {\n            if (grumpy[i] == 0) normal_gained += customers[i];\n            gained += (grumpy[i] == 1 ? customers[i] : 0);\n            if (i >= X) {\n                gained -= (grumpy[i-X] == 1 ? customers[i-X] : 0);\n            }\n            max_gained = max(max_gained, gained);\n        }\n        return normal_gained + max_gained;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1051-1060/Height Checker.cpp",
    "content": "class Solution {\npublic:\n    int heightChecker(vector<int>& heights) {\n        int returned_ans = 0;\n        vector<int> copy = heights;\n        sort(begin(heights), end(heights));\n        for (int i = 0; i < heights.size(); i++) {\n            returned_ans += (heights[i] != copy[i]);\n        }\n        return returned_ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1051-1060/Previous Permutation With One Swap.cpp",
    "content": "class Solution {\npublic:\n    vector<int> prevPermOpt1(vector<int>& A) {\n        if (A.empty()) return A;\n        \n        // in reverse order, find the first number which is in decreasing trend (we call it violated number here)\n        int i(0);\n        for (i = A.size()-2; i >= 0; --i)\n            if (A[i] > A[i+1]) break;\n\n        if (i == -1) return A;\n        \n        auto itr = lower_bound(A.begin()+i+1, A.end(), A[i]);\n        if (itr != A.begin()) {\n            itr--;\n            auto copy = itr;\n            while (itr != A.begin()) {\n                int e1 = *itr;\n                itr--;\n                int e2 = *itr;\n                if (e1 != e2) break;\n                copy = itr;\n            }\n            swap(A[i], *copy);\n            return A;\n        }\n        \n        return A;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1071-1080/Adding Two Negabinary Numbers.cpp",
    "content": "class Solution {\npublic:\n    vector<int> addNegabinary(vector<int>& arr1, vector<int>& arr2) {\n        vector<int> ans;\n        reverse(arr1.begin(), arr1.end());\n        reverse(arr2.begin(), arr2.end());\n        \n        int i = 0, j = 0;\n        int add_on = 0;\n        \n        while (i < arr1.size() || j < arr2.size() || add_on != 0) {\n            int a = i < arr1.size() ? arr1[i] : 0;\n            int b = j < arr2.size() ? arr2[j] : 0;\n            \n            int v = a + b + add_on;\n            \n            if (v == -1) {\n                v = 1;\n                add_on = 1;\n            } else if (v >= 2) {\n                v = v%2;\n                add_on = -1;\n            } else {\n                add_on = 0;\n            }\n            \n                \n            ans.push_back(v);\n            i++; j++;\n        }\n        \n        reverse(ans.begin(), ans.end());\n        while (ans.size() > 1 && ans[0] == 0) ans.erase(begin(ans));\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1071-1080/Flip Columns For Maximum Number of Equal Rows.cpp",
    "content": "class Solution {\n    \n    void process(map<string, int>& mymap, const vector<int>& vec) {\n        string str1, str2;\n        for (int e : vec) {\n            str1 += ('0' + e);\n            str2 += ('0' + (1-e));\n        }\n        mymap[str1]++;\n        mymap[str2]++;\n    }\n    \npublic:\n    int maxEqualRowsAfterFlips(vector<vector<int>>& matrix) {\n        map<string, int> mymap;\n        \n        for (const vector<int>& vec : matrix) {\n            process(mymap, vec);\n        }\n        \n        int ans = 0;\n        for (auto e : mymap) {\n            ans = max(ans, e.second);\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1071-1080/Greatest Common Divisor of Strings.cpp",
    "content": "class Solution {\n    \n    bool IsValid(const string& str, const string& candidate) {\n        for (int i = 0; i < str.length(); i += candidate.length()) {\n            if (str.substr(i, candidate.length()) != candidate) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \npublic:\n    string gcdOfStrings(string str1, string str2) {\n        int m = str1.length();\n        int n = str2.length();\n        int gcd = __gcd(m, n);\n        \n        string candidate = str1.substr(0, gcd);\n        \n        if (!IsValid(str1, candidate)) return \"\";\n        if (!IsValid(str2, candidate)) return \"\";\n        \n        return candidate;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1071-1080/Insufficient Nodes in Root to Leaf Paths.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode* sufficientSubset(TreeNode* root, int limit) {\n        if (root->left == root->right) // leaf node\n            return root->val < limit ? nullptr : root;\n        if (root->left)\n            root->left = sufficientSubset(root->left, limit - root->val);\n        if (root->right)\n            root->right = sufficientSubset(root->right, limit - root->val);\n        return root->left == root->right ? nullptr : root;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1071-1080/Letter Tile Possibilities.cpp",
    "content": "class Solution {\n    int fact[8] = { 1, 1, 2, 6, 24, 120, 720, 5040 };\n    set<string> st;\n    \n    int uniquePerms(const string& s) {\n        int cnt[26] = {};\n        for (char ch : s) cnt[ch - 'A']++;\n        int res = fact[s.size()];\n        for (int n : cnt) res /= fact[n];\n        return res;\n    }\n    \n    int dfs(const string& s, string seq = \"\", int pos = 0) {\n        if (pos >= s.size()) {\n            return st.insert(seq).second ? uniquePerms(seq) : 0;\n        }\n        return dfs(s, seq, pos + 1) + dfs(s, seq + s[pos], pos + 1);\n    }\n    \npublic:\n    int numTilePossibilities(string tiles) {\n        sort(begin(tiles), end(tiles));\n        return dfs(tiles) - 1;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1071-1080/Number of Submatrices That Sum to Target.cpp",
    "content": "class Solution {\npublic:\n    int numSubmatrixSumTarget(vector<vector<int>>& matrix, int target) {\n        int m = matrix.size(), n = matrix[0].size();\n        for (int i = 0; i < m; i++)\n            for (int j = 1; j < n; j++)\n                matrix[i][j] += matrix[i][j - 1];\n        int res = 0;\n        for (int i = 0; i < n; i++) {\n            for (int j = i; j < n; j++) {\n                unordered_map<int, int> counter;\n                counter[0] = 1;\n                int cur = 0;\n                for (int k = 0; k < m; k++) {\n                    cur += matrix[k][j] - (i > 0 ? matrix[k][i - 1] : 0);\n                    res += counter[cur - target];\n                    counter[cur]++;\n                }\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1071-1080/Occurrences After Bigram.cpp",
    "content": "class Solution {\npublic:\n    vector<string> findOcurrences(string text, string first, string second) {\n        string matched_string = first + \" \" + second;\n        vector<string> return_ans;\n        int idx = 0;\n        \n        while ((idx = text.find(matched_string, idx)) >= 0) {\n            int start = idx + matched_string.size() + 1;\n            if (start >= text.size()) break;\n            int end = start;\n            while (end < text.size() && text[end] != ' ') {\n                end++;\n            }\n            string third = text.substr(start, end-start);\n            return_ans.push_back(third);\n            idx = start;\n        }\n        \n        return return_ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1081-1090/Duplicate Zeros.cpp",
    "content": "class Solution {\npublic:\n    void duplicateZeros(vector<int>& arr) {\n        int zeros_now = 0;\n        for (int e : arr) {\n            zeros_now += (e == 0);\n        }\n        \n        int n = arr.size();\n        \n        for (int i = arr.size()-1; i >= 0; i--) {\n            if (arr[i] != 0) {\n                int pos = i + zeros_now;\n                int copy = arr[i];\n                arr[i] = 0;\n                if (pos < n) {\n                    arr[pos] = copy;\n                }\n            } else {\n                zeros_now--;\n            }\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1081-1090/Largest Values From Labels.cpp",
    "content": "class Solution {\npublic:\n    int largestValsFromLabels(vector<int>& values, vector<int>& labels, int num_wanted, int use_limit) {\n        vector<pair<int, int>> myvec(values.size());\n        for (int i = 0; i < values.size(); i++) {\n            myvec[i] = make_pair(values[i], labels[i]);\n        }\n        \n        sort(myvec.begin(), myvec.end());\n        \n        map<int, int> counts;\n        int ans = 0;\n        \n        for (int i = myvec.size() - 1; i >= 0; i--) {\n            if (num_wanted == 0) break;\n            int label = myvec[i].second;\n            if (counts[label] < use_limit) {\n                counts[label]++;\n                ans += myvec[i].first;\n                num_wanted--;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1081-1090/Smallest Subsequence of Distinct Characters.cpp",
    "content": "class Solution {\npublic:\n    string smallestSubsequence(string text) {\n        \n        bool visited[26] = {false};\n        int count[26] = {0};\n        stack<char> temp_answers;\n        for (char ch : text) {\n            count[ch - 'a']++;\n        }\n        \n        // bcabc, b -> bc -> a -> ab -> abc\n        // cbacdcbc, c -> b -> a -> ac -> acd -> acd -> acdb \n        for (char ch : text) {\n            int index = ch - 'a';\n            count[index]--;\n\n            if (visited[index]) continue;\n            \n            while (!temp_answers.empty() && temp_answers.top() > ch && count[temp_answers.top() - 'a'] > 0) {\n                char c = temp_answers.top();\n                temp_answers.pop();\n                visited[c - 'a'] = false;\n            }\n            \n            temp_answers.push(ch);\n            visited[index] = true;\n        }\n        \n        string res(\"\");\n        while (!temp_answers.empty()) {\n            res = temp_answers.top() + res;\n            temp_answers.pop();\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1091-1100/Brace Expansion II.cpp",
    "content": "class Solution {\n    \n    set<string> merge(const set<string>& set1, const set<string>& set2) {\n        set<string> ans;\n        for (const string& str1 : set1) {\n            for (const string& str2 : set2) {\n                ans.insert(str1+str2);\n            }\n        }\n        return ans;\n    }\n    \n    void process(stack<set<string>>& mystack, stack<char>& ops) {\n        char op = ops.top();\n        ops.pop();\n        set<string> set1 = mystack.top();\n        mystack.pop();\n        set<string> set2 = mystack.top();\n        mystack.pop();\n        if (op == '*') {\n            set<string> merged = merge(set2, set1);\n            mystack.push(merged);\n        } else if (op == ',') {\n            set1.insert(set2.begin(), set2.end());\n            mystack.push(set1);\n        }\n    }\n    \npublic:\n    vector<string> braceExpansionII(string expression) {\n        stack<char> ops;\n        stack<set<string>> mystack;\n        expression = \"{\" + expression + \"}\";\n        \n        string word;\n        for (int i = 0; i < expression.length(); i++) {\n            \n            if (!word.empty() && (expression[i] < 'a' || expression[i] > 'z' || i + 1 == expression.length())) {\n                set<string> set_;\n                set_.insert(word);\n                mystack.push(set_);\n                word.clear();\n            }\n            \n            if (expression[i] == '{') {\n                if (i != 0 && (expression[i-1] != ',' && expression[i-1] != '{')) {\n                    ops.push('*');\n                }\n                ops.push('{');\n            } else if (expression[i] == '}') {\n                while (ops.top() != '{') {\n                    process(mystack, ops);\n                }\n                ops.pop();\n            } else if (expression[i] == ',') {\n                while (ops.top() == '*') {\n                    process(mystack, ops);\n                }\n                ops.push(',');\n            } else {\n                if (word.empty() && i != 0 && expression[i-1] == '}') {\n                    ops.push('*');\n                }\n                word = word + expression[i];\n            }\n        }\n        \n        return vector<string>(mystack.top().begin(), mystack.top().end());\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1091-1100/Car Pooling.cpp",
    "content": "class Solution {\npublic:\n    bool carPooling(vector<vector<int>>& trips, int capacity) {\n        vector<pair<int, int>> v;\n        for (const vector<int>& trip : trips) {\n            v.push_back({trip[1], trip[0]});\n            v.push_back({trip[2], -trip[0]});\n        }\n        sort(v.begin(), v.end());\n        \n        int passengers = 0;\n        for (const pair<int, int>& e : v) {\n            passengers += e.second;\n            if (passengers > capacity) {\n                return false;\n            }\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1091-1100/Find in Mountain Array.cpp",
    "content": "/**\n * // This is the MountainArray's API interface.\n * // You should not implement it, or speculate about its implementation\n * class MountainArray {\n *   public:\n *     int get(int index);\n *     int length();\n * };\n */\nclass Solution {\n    \npublic:\n    int findInMountainArray(int target, MountainArray &mountainArr) {\n        int left = 0;\n        int right = mountainArr.length() - 1;\n        \n        while (left <= right) {\n            \n            if (right - left < 6) {\n                for (int k = left; k <= right; k++) {\n                    if (mountainArr.get(k) == target) return k;\n                }\n                return -1;\n            }\n            \n            int mid = (left+right)/2;\n            int nmid = mid+1;\n            \n            int v = mountainArr.get(mid);\n            if (v == target) return mid;\n            int vv = mountainArr.get(nmid);\n            if (vv == target) return nmid;\n            \n            bool isup = vv > v;\n            \n            if (isup) {\n                // [left, mid - 1]\n                if (target < v) {\n                    \n                    int l = left;\n                    int r = mid - 1;\n                    \n                    while (r - l >= 2) {\n                        int mid_ = (l+r)/2;\n                        int v_ = mountainArr.get(mid_);\n                        if (v_ == target) return mid_;\n                        if (v_ < target) l = mid_ + 1;\n                        else r = mid_ - 1;\n                    }\n                    \n                    while (l <= r) {\n                        if (mountainArr.get(l) == target) return l;\n                        l++;\n                    }\n                    \n                }\n                left = nmid + 1;\n            } else {\n                // [mid+1, right]\n                if (target < vv) {\n                    \n                    int l = mid+1;\n                    int r = right;\n                    \n                    while (r - l >= 2) {\n                        int mid_ = (l+r)/2;\n                        int v_ = mountainArr.get(mid_);\n                        if (v_ == target) return mid_;\n                        if (v_ > target) l = mid_ + 1;\n                        else r = mid_ - 1;\n                    }\n                    \n                    while (l <= r) {\n                        if (mountainArr.get(l) == target) return l;\n                        l++;\n                    }\n                    \n                }\n                right = mid - 1;\n            }\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1091-1100/Shortest Common Supersequence.cpp",
    "content": "class Solution {\n    \npublic:\n    string shortestCommonSupersequence(string str1, string str2) {\n        int m = str1.size();\n        int n = str2.size();\n        vector<vector<int>> dp(m+1, vector<int>(n+1, 0));\n\n        map<pair<int,int>, pair<int, int>> from;\n\n        for (int i = 0; i <= m; i++) {\n            for (int j = 0; j <= n; j++) {\n                if (i == 0) {\n                    dp[i][j] = 0;\n                    from[{i, j}] = {0, j-1};\n                } else if (j == 0) {\n                    dp[i][j] = 0;\n                    from[{i,j}] = {i-1, 0};\n                } else if (str1[i-1] == str2[j-1]) {\n                    dp[i][j] = dp[i-1][j-1] + 1;\n                    from[{i, j}] = {i-1, j-1};\n                } else {\n                    if (dp[i-1][j] > dp[i][j-1]) {\n                        from[{i, j}] = {i-1, j};\n                    } else {\n                        from[{i, j}] = {i, j-1};\n                    }\n                    dp[i][j] = max(dp[i-1][j], dp[i][j-1]);\n                }\n            }\n        }\n        int i = m;\n        int j = n;\n\n        string ans;\n\n        while (!(i == 0 && j == 0)) {\n            auto p = from[{i, j}];\n\n            if (i == p.first + 1 && j == p.second + 1) {\n                ans = str1[i-1] + ans;\n            } else if (i == p.first) {\n                ans = str2[j-1] + ans;\n            } else {\n                ans = str1[i-1] + ans;\n            }\n\n            i = p.first;\n            j = p.second;\n        }\n\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1091-1100/Shortest Path in Binary Matrix.cpp",
    "content": "class Solution {\npublic:\n    int shortestPathBinaryMatrix(vector<vector<int>>& grid) {\n        int m = grid.size();\n        int n = grid[0].size();\n        if (grid[0][0] == 1 || grid[m-1][n-1] == 1) return -1;\n        set<pair<int, int>> visited;\n        \n        visited.insert({0, 0});\n        queue<pair<pair<int, int>, int>> myqueue;\n        myqueue.push({{0, 0}, 1});\n        \n        while (!myqueue.empty()) {\n            auto ele = myqueue.front();\n            myqueue.pop();\n            int m_ = ele.first.first;\n            int n_ = ele.first.second;\n            int d = ele.second;\n            \n            if (m_ == m - 1 && n_ == n - 1) return d;\n            \n            for (int i = 0; i < 3; i++) {\n                for (int j = 0; j < 3; j++) {\n                    if (i == 1 && j == 1) continue;\n                    int new_m = m_ + i - 1;\n                    int new_n = n_ + j - 1;\n                    if (new_m < 0 || new_n < 0 || new_m >= m || new_n >= n) continue;\n                    if (visited.count({new_m, new_n}) > 0) continue;\n                    if (grid[new_m][new_n] == 1) continue;\n                    visited.insert({new_m, new_n});\n                    myqueue.push({{new_m, new_n}, d+1});\n                }\n            }\n        }\n        \n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1091-1100/Statistics from a Large Sample.cpp",
    "content": "class Solution {\npublic:\n    vector<double> sampleStats(vector<int>& count) {\n        vector<double> res{256, -1, 0, 0, 0};\n        int n_sample = accumulate(count.begin(), count.end(), 0);\n        long sum = 0;\n        int nth = (n_sample-1) / 2 + 1;\n        int nnth = n_sample % 2 == 1 ? nth : nth + 1;\n        \n        int n_sample_so_far = 0;\n        int mode_samples = 0;\n        \n        for (int i = 0; i < count.size(); i++) {\n            if (count[i] > 0) {\n                if (res[0] > 255) {\n                    res[0] = i;\n                }\n                res[1] = i;\n                sum += i*count[i];\n                if (count[i] > mode_samples) {\n                    res[4] = i;\n                    mode_samples = count[i];\n                }\n                \n                int previous_sample = n_sample_so_far;\n                n_sample_so_far += count[i];\n                \n                if (nth > previous_sample && nth <= n_sample_so_far) res[3] += i;\n                if (nnth > previous_sample && nnth <= n_sample_so_far) res[3] += i;\n            }\n        }\n        \n        res[2] = sum*1.0/n_sample;\n        res[3] /= 2.0;\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1091-1100/Two Sum Less Than K.cpp",
    "content": "class Solution {\npublic:\n    int twoSumLessThanK(vector<int>& A, int K) {\n        sort(begin(A), end(A));\n        int i = 0, j = A.size() - 1;\n        int ans = -1;\n        \n        while (i < j) {\n            int sum = A[i] + A[j];\n            if (sum < K) {\n                ans = max(ans, sum);\n                i++;\n            } else {\n                j--;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1101-1110/Corporate Flight Bookings.cpp",
    "content": "class Solution {\npublic:\n    vector<int> corpFlightBookings(vector<vector<int>>& bookings, int n) {\n        unordered_map<int, int> record;\n        for (const vector<int>& booking : bookings) {\n            record[booking[0]-1] += booking[2];\n            record[booking[1]] -= booking[2];\n        }\n        \n        vector<int> ans(n, -1);\n        \n        int current = 0;\n        for (int i = 0; i < n; i++) {\n            current += record[i];\n            ans[i] = current;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1101-1110/Defanging an IP Address.cpp",
    "content": "class Solution {\npublic:\n    string defangIPaddr(string address) {\n        string ans;\n        \n        for (char ch : address) {\n            if (ch == '.') {\n                ans = ans + '[' + '.' + ']';\n            } else {\n                ans = ans + ch;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1101-1110/Delete Nodes And Return Forest.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    vector<TreeNode*> ans;\n    \n    TreeNode* dfs (TreeNode* root, set<int>& to_deleted, bool is_root) {\n        \n        if (root == nullptr) {\n            return nullptr;\n        }\n        \n        if (to_deleted.count(root->val) > 0) {\n            dfs(root->left, to_deleted, true);\n            dfs(root->right, to_deleted, true);\n            return nullptr;\n        }\n        \n        root->left = dfs(root->left, to_deleted, false);\n        root->right = dfs(root->right, to_deleted, false);\n        \n        if (is_root) ans.push_back(root);\n        \n        return root;\n    }\n    \npublic:\n    vector<TreeNode*> delNodes(TreeNode* root, vector<int>& to_delete) {\n        set<int> to_deleted(to_delete.begin(), to_delete.end());\n        dfs(root, to_deleted, true);\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1101-1110/Distribute Candies to People.cpp",
    "content": "class Solution {\npublic:\n    vector<int> distributeCandies(int candies, int num_people) {\n        vector<int> ans(num_people, 0);\n        int k = 1;\n        int index = 0;\n        \n        while (candies > 0) {\n            int c = min(k, candies);\n            ans[index] += c;\n            k++;\n            candies -= c;\n            index = (index+1) % num_people;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1101-1110/Filling Bookcase Shelves.cpp",
    "content": "class Solution {\npublic:\n    int minHeightShelves(vector<vector<int>>& books, int shelf_width) {\n        vector<int> dp(books.size()+1, 0);\n        \n        for (int i = 0; i < books.size(); i++) {\n            int minimum_h = 1001*1001;\n            int current_shelf_height = -1;\n            int n_elements = 0;\n            int current_shelf_width = 0;\n            for (int j = i; j >= 0; j--) {\n                n_elements++;\n                current_shelf_width += books[j][0];\n                if (current_shelf_width > shelf_width) break;\n                current_shelf_height = max(current_shelf_height, books[j][1]);\n                minimum_h = min(minimum_h, dp[j] + current_shelf_height);\n            }\n            \n            dp[i+1] = minimum_h;\n        } \n        \n        return dp.back();\n    }\n};\n\nclass Solution {\npublic:\n    int dfs(vector<vector<int>>& books, int shelf_width, int ind, int remain_width, int current_height, map<pair<int, int>, int>& cache) {\n        if (ind == books.size()) {\n            return current_height;\n        }\n        auto it = cache.find({ind, remain_width});\n        if (it != cache.end()) return it->second;\n        \n        // 1) we can put current book on a new shelf.\n        int minimum_height = INT_MAX;\n        minimum_height = current_height + dfs(books, shelf_width, ind+1, shelf_width - books[ind][0], books[ind][1], cache);\n        // 2) If we have plenty width in current shelf, we can also put in current shelf.\n        if (books[ind][0] <= remain_width) {\n            current_height = max(current_height, books[ind][1]);\n            minimum_height = min(minimum_height, dfs(books, shelf_width, ind+1, remain_width - books[ind][0], current_height, cache));\n        }\n        return cache[{ind, remain_width}] = minimum_height;\n    }\n    int minHeightShelves(vector<vector<int>>& books, int shelf_width) {\n        map<pair<int, int>, int> cache; // {ith_book}, {how many width remained in current shelf}\n        // This cache means when I process ith book and in a w position, how many remain minimum height I need for remaining books in that state.\n        return dfs(books, shelf_width, 0, shelf_width, 0, cache);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1101-1110/Parsing A Boolean Expression.cpp",
    "content": "class Solution {\npublic:\n    bool parseBoolExpr(string expression) {\n        stack<char> ops;\n        stack<bool> nums;\n        \n        for (char ch : expression) {\n            if (ch == '(' || ch == '&' || ch == '!' || ch == '|' || ch ==',') {\n                ops.push(ch);\n            } else if (ch == 't') {\n                nums.push(true);\n            } else if (ch == 'f') {\n                nums.push(false);\n            } else if (ch == ')') {\n                vector<bool> tmp;\n                tmp.push_back(nums.top());\n                nums.pop();\n                while (ops.top() == ',') {\n                    tmp.push_back(nums.top());\n                    nums.pop();\n                    ops.pop();\n                }\n                ops.pop();\n                char op = ops.top(); ops.pop();\n                bool result = tmp.front();\n                if (op == '&') {\n                    for (int i = 1; i < tmp.size(); i++) {\n                        result &= tmp[i];\n                    }\n                } else if (op == '|') {\n                    for (int i = 1; i < tmp.size(); i++) {\n                        result |= tmp[i];\n                    }\n                } else if (op == '!') {\n                    result = 1 - result;\n                }\n                nums.push(result);\n            }\n        }\n        \n        return nums.top();\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1101-1110/Path In Zigzag Labelled Binary Tree.cpp",
    "content": "class Solution {\npublic:\n    vector<int> pathInZigZagTree(int label) {\n        int row = 0;\n        int tmp = label;\n        int start_number = 1;\n        while (tmp > 0) {\n            row++;\n            tmp = tmp >> 1;\n            if (tmp > 0) start_number *= 2;\n        }\n        \n        vector<int> ans;\n        \n        while (label > 0) {\n            \n            if (label == 1) {\n                ans.insert(ans.begin(), label);\n                break;\n            }\n            \n            int a1 = start_number/2;\n            int a2 = a1*2 - 1;\n            int sum = a1+a2;\n            \n            ans.insert(ans.begin(), label);\n            int t = label/2;\n            start_number /= 2;\n            \n            label = sum - t;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1111-1120/Maximum Nesting Depth of Two Valid Parentheses Strings.cpp",
    "content": "class Solution {\npublic:\n    vector<int> maxDepthAfterSplit(string seq) {\n        int n = seq.size();\n        vector<int> ans(n, 0);\n        int depth = 0;\n        \n        for (int i = 0; i < seq.size(); i++) {\n            if (seq[i] == '(') {\n                depth++;\n                if (depth % 2 == 0) ans[i] = 1;\n            } else {\n                depth--;\n                if (depth % 2 == 1) ans[i] = 1;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1111-1120/Print FooBar Alternately.cpp",
    "content": "class FooBar {\n    mutex m1,m2;\nprivate:\n    int n;\n\npublic:\n    FooBar(int n) {\n        this->n = n;\n\t\tm1.lock();\n    }\n\n    void foo(function<void()> printFoo) {\n        \n        for (int i = 0; i < n; i++) {\n            \n        \t// printFoo() outputs \"foo\". Do not change or remove this line.\n            m2.lock();\n        \tprintFoo();\n            m1.unlock();\n            \n        }\n    }\n\n    void bar(function<void()> printBar) {\n        \n        for (int i = 0; i < n; i++) {\n            \n        \t// printBar() outputs \"bar\". Do not change or remove this line.\n            m1.lock();\n        \tprintBar();\n            m2.unlock();\n            \n        }\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1111-1120/Print in Order.cpp",
    "content": "class Foo {\n    \n    std::promise<void> p1;\n    std::promise<void> p2;\n    \npublic:\n    Foo() {\n        \n    }\n\n    void first(function<void()> printFirst) {\n        // printFirst() outputs \"first\". Do not change or remove this line.\n        printFirst();\n        p1.set_value();\n    }\n\n    void second(function<void()> printSecond) {\n        p1.get_future().wait();\n        // printSecond() outputs \"second\". Do not change or remove this line.\n        printSecond();\n        p2.set_value();\n    }\n\n    void third(function<void()> printThird) {\n        p2.get_future().wait();\n        // printThird() outputs \"third\". Do not change or remove this line.\n        printThird();\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1121-1130/Lowest Common Ancestor of Deepest Leaves.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    pair<int, TreeNode*>  dfs(TreeNode* root) {\n        if (root == nullptr) {\n            return {0, root};\n        }\n\n        pair<int, TreeNode*> l_ans = dfs(root->left);\n        pair<int, TreeNode*> r_ans = dfs(root->right);\n        \n        if (l_ans.first == r_ans.first) {\n            return {l_ans.first+1, root};\n        } else if (l_ans.first > r_ans.first) {\n            return {l_ans.first+1, l_ans.second};\n        } else {\n            return {r_ans.first+1, r_ans.second};\n        }\n    }\n    \npublic:\n    TreeNode* lcaDeepestLeaves(TreeNode* root) {\n        return dfs(root).second;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1121-1130/Minimum Cost Tree From Leaf Values.cpp",
    "content": "class Solution {\npublic:\n    int mctFromLeafValues(vector<int>& arr) {\n        int n = arr.size();\n        vector<vector<int>> max_array(n, vector<int>(n, 0));\n        vector<vector<int>> dp(n, vector<int>(n, 0));\n        \n        for (int k = 0; k < n; k++) {\n            for (int i = 0; i+k < n; i++) {\n                int j = i+k;\n                if (j >= n) continue;\n                if (k == 0) {\n                    max_array[i][j] = arr[i];\n                    continue;\n                }\n                if (k==1) {\n                    max_array[i][j] = max(arr[i], arr[j]);\n                    dp[i][j] += arr[i] * arr[j];\n                } else {\n                    max_array[i][j] = max(max_array[i][j-1], arr[j]);\n                    \n                    int temp = INT_MAX;\n                    for (int t = i; t < j; t++) {\n                        temp = min(temp, dp[i][t] + dp[t+1][j] + max_array[i][t] * max_array[t+1][j]);\n                    }\n                    dp[i][j] = temp;\n                }\n            }\n        }\n        \n        return dp[0][n-1];\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1121-1130/Number of Equivalent Domino Pairs.cpp",
    "content": "class Solution {\npublic:\n    int numEquivDominoPairs(vector<vector<int>>& dominoes) {\n        map<pair<int, int>, int> mymap;\n        for (const vector<int>& domi : dominoes) {\n            mymap[{min(domi[0], domi[1]), max(domi[0], domi[1])}]++;\n        }\n        \n        int ans = 0;\n        for (auto it : mymap) {\n            if (it.second > 0) {\n                ans += it.second * (it.second-1) / 2;\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1121-1130/Relative Sort Array.cpp",
    "content": "class Solution {\npublic:\n    vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) {\n        map<int, int> mymap;\n        for (int e : arr1) {\n            mymap[e]++;\n        }\n        \n        vector<int> ans;\n        \n        for (int e : arr2) {\n            int times = mymap[e];\n            for (int i = 0; i < times; i++) {\n                ans.push_back(e);\n            }\n            mymap[e] = 0;\n        }\n        \n        for (auto it : mymap) {\n            if (it.second > 0) {\n                int times = it.second;\n                for (int i = 0; i < times; i++) {\n                    ans.push_back(it.first);\n                }\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1121-1130/Smallest Sufficient Team.cpp",
    "content": "class Solution {\n    \n    vector<int> ans;\n    \n    map<string, vector<int>> skill_to_ppl;\n    \n    bool dfs(int need_skills, int n, vector<bool>& used, map<string, bool>& skills_picked, const vector<vector<string>>& people) {\n        if (need_skills == 0) {\n            for (int i = 0; i < used.size(); i++) {\n                if (used[i]) {\n                    ans.push_back(i);\n                }\n            }\n            return true;\n        }\n        if (n == 0) return false;\n        \n        for (auto& it : skills_picked) {\n            if (it.second == false) {\n                // we only focus on this skill.\n                const string& skill = it.first;\n                vector<int>& ppl_index = skill_to_ppl[skill];\n                for (int k : ppl_index) {\n                    if (used[k]) continue;\n                    \n                    used[k] = true;\n                    const vector<string>& current_person_skills = people[k];\n                    int new_skills = 0;\n                    vector<string> new_skill_vec;\n                    for (const string& current_person_skill : current_person_skills) {\n                        if (!skills_picked[current_person_skill]) {\n                            skills_picked[current_person_skill] = true;\n                            new_skills++;\n                            new_skill_vec.push_back(current_person_skill);\n                        }\n                    }\n                    if (dfs(need_skills - new_skills, n-1, used, skills_picked, people)) return true;\n                    \n                    for (const string& new_skill : new_skill_vec) {\n                        skills_picked[new_skill] = false;\n                    }\n                    used[k] = false;\n                }\n                \n                return false;\n            }\n        }\n        \n        return false;\n    }\n    \npublic:\n    vector<int> smallestSufficientTeam(vector<string>& req_skills, vector<vector<string>>& people) {\n        for (int i = 0; i < people.size(); i++) {\n            for (const string& skill : people[i]) {\n                skill_to_ppl[skill].push_back(i);\n            }\n        }\n        \n        map<string, bool> skills_picked;\n        for (const string& req_skill : req_skills) {\n            skills_picked[req_skill] = false;\n        }\n        \n        for (int i = 1; i <= req_skills.size(); i++) {\n            vector<bool> used(people.size(), false);\n            if (dfs(req_skills.size(), i, used, skills_picked, people)) {\n                return ans;\n            }\n        }\n        \n        return vector<int>();\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1131-1140/N-th Tribonacci Number.cpp",
    "content": "class Solution {\npublic:\n    int tribonacci(int n) {\n        int dp[50] = {0};\n        dp[1] = 1;\n        dp[2] = 1;\n        if (n <= 2) return dp[n];\n        \n        for (int i = 3; i <= n; i++) {\n            dp[i] = dp[i-3] + dp[i-2] + dp[i-1];\n        }\n        \n        return dp[n];\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1141-1150/Binary Tree Coloring Game.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    int l_num_;\n    int r_num_;\n    \n    int dfs(TreeNode* root, int x) {\n        if (!root) return 0;\n        \n        int l = dfs(root->left, x);\n        int r = dfs(root->right, x);\n        \n        if (root->val == x) {\n            l_num_ = l;\n            r_num_ = r;\n            return 0;\n        }\n        \n        return l + r + 1;\n    }\n    \npublic:\n    bool btreeGameWinningMove(TreeNode* root, int n, int x) {\n        l_num_ = 0;\n        r_num_ = 0;\n        \n        int l_p = dfs(root, x);\n        \n        return (l_num_ > n/2 || r_num_ > n/2 || l_p > n/2);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1141-1150/Decrease Elements To Make Array Zigzag.cpp",
    "content": "class Solution {\npublic:\n    int movesToMakeZigzag(vector<int>& nums) {\n        int temp1 = 0;\n        for (int i = 1; i < nums.size(); i += 2) {\n            int ele = nums[i-1];\n            if (i+1 < nums.size()) ele = min(ele, nums[i+1]);\n            if (nums[i] >= ele) {\n                temp1 += (nums[i] - ele + 1);\n            }\n        }\n        \n        int temp2 = 0;\n        for (int i = 0; i < nums.size(); i += 2) {\n            int ele = min(i-1 >= 0 ? nums[i-1] : 10000, i+1 < nums.size() ? nums[i+1] : 10000);\n            if (nums[i] >= ele) {\n                temp2 += (nums[i] - ele + 1);\n            }\n        }\n        \n        return min(temp1, temp2);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1141-1150/Longest Chunked Palindrome Decomposition.cpp",
    "content": "class Solution {\npublic:\n    int longestDecomposition(string text) {\n        if (text.length() <= 1) return text.length();\n        int i_start = 0;\n        \n        int i_end = i_start + 1;\n        int j_start = text.length() - 1;\n        \n        while (true) {\n            if (j_start < i_end) {\n                return 1;\n            }\n            \n            string str1 = text.substr(i_start, i_end - i_start);\n            string str2 = text.substr(j_start);\n            \n            if (str1 == str2) {\n                int len = text.length() - 2 * (i_end - i_start);\n                return 2 + longestDecomposition(text.substr(i_end, len));\n            }\n            \n            i_end++;\n            j_start--;\n        }\n        \n        return 1;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1141-1150/Longest Common Subsequence.cpp",
    "content": "class Solution {\npublic:\n    int longestCommonSubsequence(string text1, string text2) {\n        int m = text1.length();\n        int n = text2.length();\n        \n        vector<vector<int>> dp(m+1, vector<int>(n+1, 0));\n        \n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                if (text1[i] == text2[j]) {\n                    dp[i+1][j+1] = 1 + dp[i][j];\n                } else {\n                    dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]);\n                }\n            }\n        }\n        \n        return dp[m][n];\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1141-1150/Snapshot Array.cpp",
    "content": "class SnapshotArray {\n    map<pair<int, int>, int> mymap_;\n    int snapshot_id_;\n    map<int, vector<int>> index_to_snaps_;\npublic:\n    SnapshotArray(int length) {\n        snapshot_id_ = 0;\n    }\n    \n    void set(int index, int val) {\n        mymap_[{snapshot_id_, index}] = val;\n        index_to_snaps_[index].push_back(snapshot_id_);\n    }\n    \n    int snap() {\n        snapshot_id_++;\n        return snapshot_id_-1;\n    }\n    \n    int get(int index, int snap_id) {\n        auto up = std::upper_bound (index_to_snaps_[index].begin(), index_to_snaps_[index].end(), snap_id);\n        if (up == index_to_snaps_[index].begin()) return 0;\n        --up;\n        int target_snap_id =*up;\n        return mymap_[{target_snap_id, index}];\n    }\n};\n\n/**\n * Your SnapshotArray object will be instantiated and called as such:\n * SnapshotArray* obj = new SnapshotArray(length);\n * obj->set(index,val);\n * int param_2 = obj->snap();\n * int param_3 = obj->get(index,snap_id);\n */\n"
  },
  {
    "path": "cpp/1001-10000/1151-1160/Day of the Year.cpp",
    "content": "class Solution {\npublic:\n    int dayOfYear(string date) {\n        vector<int> daysOfMonth{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};\n        int y = stoi(date.substr(0, 4)), m = stoi(date.substr(5, 2)), d = stoi(date.substr(8, 2));\n        if ((y % 100 != 0 && y % 4 == 0) || y % 400 == 0) daysOfMonth[1] = 29;\n        return accumulate(daysOfMonth.begin(), daysOfMonth.begin() + m - 1, 0) + d;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1151-1160/Find Words That Can Be Formed by Characters.cpp",
    "content": "class Solution {\npublic:\n    int countCharacters(vector<string>& words, string chars) {\n        map<char, int> mymap;\n        for (char ch : chars) {\n            mymap[ch]++;\n        }\n        \n        int res = 0;\n        \n        map<char, int> copy = mymap;\n        for (const string& word : words) {\n            bool ok = true;\n            \n            for (char ch : word) {\n                mymap[ch]--;\n                if (mymap[ch] < 0) {\n                    ok = false;\n                    break;\n                }\n            }\n            \n            if (ok) res += word.length();\n            mymap = copy;\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1151-1160/Number of Dice Rolls With Target Sum.cpp",
    "content": "class Solution {\n    unordered_map<int, long> cache;\npublic:\n    int numRollsToTarget(int d, int f, int target) {\n        if (target == 0) {\n            if (d == 0) return 1;\n            return 0;\n        }\n        if (d <= 0 || target <= 0) return 0;\n        int key = d * 1001 + target;\n        if (cache.count(key) > 0) return cache[key];\n        \n        long res = 0;\n        for (int i = 1; i <= f; i++) {\n            res = (res + (long)numRollsToTarget(d-1, f, target - i)) % 1000000007L;\n        }\n        \n        return cache[key] = res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1161-1170/As Far from Land as Possible.cpp",
    "content": "class Solution {\npublic:\n    int maxDistance(vector<vector<int>>& grid) {\n        queue<pair<int, int>> myqueue;\n        set<pair<int, int>> visited;\n        for (int i = 0; i < grid.size(); i++) {\n            for (int j = 0; j < grid.front().size(); j++) {\n                if (grid[i][j] == 1) {\n                    myqueue.push({i, j});\n                    visited.insert({i, j});\n                }\n            }\n        }\n        \n        pair<int, int> tmp[4] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};\n        int dis = 1;\n        int res = -1;\n        while (!myqueue.empty()) {\n            int sizes = myqueue.size();\n            for (int i = 0; i < sizes; i++) {\n                pair<int, int> ele = myqueue.front();\n                myqueue.pop();\n                \n                int i_ = ele.first;\n                int j_ = ele.second;\n                \n                for (const pair<int, int>& p : tmp) {\n                    int new_i = i_ + p.first;\n                    int new_j = j_ + p.second;\n                    if (new_i < 0 || new_j < 0 || new_i >= grid.size() || new_j >= grid.front().size()) continue;\n                    if (grid[new_i][new_j] == 1) continue;\n                    if (visited.count({new_i, new_j}) > 0) continue;\n                    visited.insert({new_i, new_j});\n                    myqueue.push({new_i, new_j});\n                    res = dis;\n                }\n            }\n            \n            dis++;\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1161-1170/Compare Strings by Frequency of the Smallest Character.cpp",
    "content": "class Solution {\n    \n    int getF(const string& word) {\n        char ch = word[0];\n        for (int i = 1; i < word.size(); i++) {\n            if (ch > word[i]) ch = word[i];\n        }\n\n        int f = 0;\n        for (char c : word) if (c == ch) f++;\n        return f;\n    }\n    \npublic:\n    vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {\n        vector<int> v;\n        \n        for (auto& word : words) {\n            int f = getF(word);\n            v.push_back(f);\n        }\n        \n        vector<int> ans;\n        for (auto& query : queries) {\n            int f = getF(query);\n            int c = 0;\n            for (int e : v) if (f < e) c++;\n            ans.push_back(c);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1161-1170/Design File System.cpp",
    "content": "class FileSystem {\n    map<string, int> mymap;\npublic:\n    FileSystem() {\n        mymap[\"\"] = 0;\n    }\n    \n    bool create(string path, int value) {\n        size_t pos = path.find_last_of('//');\n        if (pos == string::npos) {\n            return false;\n        }\n        \n        string parent = path.substr(0, pos);\n        if (mymap.count(parent) == 0) return false;\n        mymap[path] = value;\n        return true;\n    }\n    \n    int get(string path) {\n        if (mymap.count(path) == 0) return -1;\n        return mymap[path];\n    }\n};\n\n/**\n * Your FileSystem object will be instantiated and called as such:\n * FileSystem* obj = new FileSystem();\n * bool param_1 = obj->create(path,value);\n * int param_2 = obj->get(path);\n */\n"
  },
  {
    "path": "cpp/1001-10000/1161-1170/Invalid Transactions.cpp",
    "content": "class Solution {\n    \n    vector<string> split(const string &s, char delim) {\n        vector<string> elems;\n        stringstream ss(s);\n        string item;\n        while (getline(ss, item, delim)) {\n            if (item.length() > 0) {\n                elems.push_back(item);\n            }\n        }\n        return elems;\n    }\n    \npublic:\n    vector<string> invalidTransactions(vector<string>& transactions) {\n        vector<string> ans;\n        \n        for (int i = 0; i < transactions.size(); i++) {\n            vector<string> to_check = split(transactions[i], ',');\n            int amount = stoi(to_check[2]);\n            if (amount > 1000) {\n                ans.push_back(transactions[i]);\n                continue;\n            }\n            int i_time = stoi(to_check[1]);\n            for (int j = 0; j < transactions.size(); j++) {\n                if (i == j) continue;\n                vector<string> v = split(transactions[j], ',');\n                if (to_check[0] != v[0]) continue;\n                if (to_check[3] == v[3]) continue;\n                int j_time = stoi(v[1]);\n                if (abs(i_time - j_time ) > 60) continue;\n\n                ans.push_back(transactions[i]);\n                break;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1161-1170/Maximum Level Sum of a Binary Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    map<int, int> mymap;\n    \n    void dfs(TreeNode* root, int level) {\n        if (root == nullptr) return;\n        mymap[level] += root->val;\n        dfs(root->left, level+1);\n        dfs(root->right, level+1);\n    }\n    \npublic:\n    int maxLevelSum(TreeNode* root) {\n        int level = 1;\n        int max_sum = INT_MIN;\n        dfs(root, 1);\n        \n        for (auto& it : mymap) {\n            if (it.second > max_sum) {\n                max_sum = it.second;\n                level = it.first;\n            }\n        }\n        \n        return level;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1161-1170/Minimum Cost to Connect Sticks.cpp",
    "content": "class Solution {\npublic:\n    int connectSticks(vector<int>& sticks) {\n        priority_queue<int, vector<int>, std::greater<int>> myqueue;\n        for (int e : sticks) myqueue.push(e);\n        \n        int ans = 0;\n        \n        while (myqueue.size() > 1) {\n            int e1 = myqueue.top(); myqueue.pop();\n            int e2 = myqueue.top(); myqueue.pop();\n            ans += (e1 + e2);\n            myqueue.push(e1 + e2);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1161-1170/Optimize Water Distribution in a Village.cpp",
    "content": "class UF {\n    \nprivate:\n    vector<int> parent;\n    vector<int> rank;\n    int count;\n    int N;\n    \npublic:\n    \n    UF(int N) : parent(N), rank(N, 0), N(N), count(N) {\n        for (int i = 0; i < N; i++) {\n            parent[i] = i;\n        }\n    }\n    \n    int find(int p) {\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];    // path compression by halving\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    void Union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rootP == rootQ) return;\n        \n        // make root of smaller rank point to root of larger rank\n        if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;\n        else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;\n        else {\n            parent[rootQ] = rootP;\n            rank[rootP]++;\n        }\n        count--;\n    }\n};\n\n\nclass Solution {\npublic:\n    int minCostToSupplyWater(int n, vector<int>& wells, vector<vector<int>>& pipes) {\n        UF uf(n+1);\n        for (auto& pipe : pipes) swap(pipe[0], pipe[2]);\n        for (int i = 0; i < n; i++) pipes.push_back({wells[i], 0, i+1});\n        sort(pipes.begin(), pipes.end());\n        \n        int ans = 0;\n        for (auto& pipe : pipes) {\n            int u = pipe[1];\n            int v = pipe[2];\n            if (!uf.connected(u, v)) {\n                uf.Union(u, v);\n                ans += pipe[0];\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1161-1170/Single-Row Keyboard.cpp",
    "content": "class Solution {\npublic:\n    int calculateTime(string keyboard, string word) {\n        map<char, int> kmap;\n        for (int i = 0; i < keyboard.size(); i++) {\n            kmap[keyboard[i]] = i;\n        }\n        \n        int res = 0;\n        for (int i = 0; i < word.length(); i++) {\n            res += abs(kmap[word[i]] - (i == 0 ? 0 : kmap[word[i-1]]));\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1171-1180/Can Make Palindrome from Substring.cpp",
    "content": "class Solution {\npublic:\n    vector<bool> canMakePaliQueries(string s, vector<vector<int>>& queries) {\n        vector<vector<int>> data(s.length()+1, vector<int>(26, 0));\n        \n        for (int i = 0; i < s.length(); i++) {\n            for (int j = 0; j < 26; j++) {\n                data[i+1][j] = data[i][j] + (s[i] - 'a' == j ? 1 : 0);\n            }\n        }\n        \n        vector<bool> answers;\n        \n        for (const vector<int>& query : queries) {\n            int needed = 0;\n            for (int j = 0; j < 26; j++) {\n                int d = data[query[1]+1][j] - data[query[0]][j];\n                if (d % 2 == 1) needed++;\n            }\n            if ((query[1] - query[0]) % 2 == 0) needed--;\n            if (needed <= 2*query[2]) answers.push_back(true);\n            else answers.push_back(false);\n        }\n        \n        return answers;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1171-1180/Count Substrings with Only One Distinct Letter.cpp",
    "content": "class Solution {\npublic:\n    int countLetters(string S) {\n        int i = 0;\n        int j = 0;\n        int ans = 0;\n        while (i < S.length()) {\n            while (S[j] == S[i]) {\n                j++;\n            }\n            int num = j - i;\n            ans += ((1+num) * num / 2);\n            i = j;\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1171-1180/Diet Plan Performance.cpp",
    "content": "class Solution {\npublic:\n    int dietPlanPerformance(vector<int>& calories, int k, int lower, int upper) {\n        int ans = 0;\n        int sum = accumulate(calories.begin(), calories.begin() + k, 0);\n        \n        for (int i = k; i <= calories.size(); i++) {\n            if (sum > upper) ans++;\n            if (sum < lower) ans--;\n            \n            if (i >= calories.size()) break;\n            \n            sum = sum - calories[i - k];\n            sum = sum + calories[i];\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1171-1180/Dinner Plate Stacks.cpp",
    "content": "class DinnerPlates {\n    \n    vector<stack<int>> v;\n    int capacity;\n    int bestindex;\n    \npublic:\n    DinnerPlates(int capacity) {\n        this->capacity = capacity;\n        bestindex = 0;\n    }\n    \n    void push(int val) {\n        for (int i = bestindex; i < v.size(); i++) {\n            stack<int>& s = v[i];\n            if (s.size() < capacity) {\n                s.push(val);\n                bestindex = i;\n                return;\n            }\n        }\n        stack<int> ss;\n        ss.push(val);\n        v.emplace_back(ss);\n        bestindex = v.size() - 1;\n    }\n    \n    int pop() {\n        for (int i = v.size() - 1; i >= 0; i--) {\n            stack<int>& s = v[i];\n            if (!s.empty()) {\n                int ret = s.top();\n                s.pop();\n                bestindex = min(bestindex, i);\n                return ret;\n            }\n            v.pop_back();\n            bestindex = max(0, min(bestindex, (int)v.size()-1));\n        }\n        return -1;\n    }\n    \n    int popAtStack(int index) {\n        stack<int>& s = v[index];\n        if (!s.empty()) {\n            int ret = s.top();\n            s.pop();\n            bestindex = min(bestindex, index);\n            return ret;\n        }\n        return -1;\n    }\n};\n\n/**\n * Your DinnerPlates object will be instantiated and called as such:\n * DinnerPlates* obj = new DinnerPlates(capacity);\n * obj->push(val);\n * int param_2 = obj->pop();\n * int param_3 = obj->popAtStack(index);\n */\n"
  },
  {
    "path": "cpp/1001-10000/1171-1180/Prime Arrangements.cpp",
    "content": "class Solution {\n    \n    bool isPrime(int k) {\n        if (k == 1) return false;\n        if (k <= 3) return true;\n        int limit = sqrt(k);\n        for (int i = 2; i <= limit; i++) {\n            if (k % i == 0) return false;\n        }\n        return true;\n    }\n    \npublic:\n    int numPrimeArrangements(int n) {\n        int pn = 0;\n        for (int i = 1; i <= n; i++) {\n            if (isPrime(i)) {\n                pn++;\n            }\n        }\n        int npn = n - pn;\n        \n        long ans = 1;\n        int mod = 1000000007;\n        \n        for (int i = 1; i <= pn; i++) {\n            ans = (ans * i) % mod;\n        }\n        for (int i = 1; i <= npn; i++) {\n            ans = (ans * i) % mod;\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1171-1180/Remove Zero Sum Consecutive Nodes from Linked List.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* removeZeroSumSublists(ListNode* head) {\n        map<int, ListNode*> mymap;\n        \n        ListNode* phead = new ListNode(0);\n        mymap[0] = phead;\n        phead->next = head;\n        int sum = 0;\n        while (head) {\n            sum += head->val;\n\n            if (mymap.count(sum) > 0) {\n                ListNode* prev = mymap[sum];\n                ListNode* deleted = prev->next;\n                int mysum = sum;\n                while (deleted != head) {\n                    mysum += deleted->val;\n                    mymap.erase(mysum);\n                    deleted = deleted->next;\n                }\n\n                prev->next = head->next;\n            } else {\n                mymap[sum] = head;\n            }\n            \n            head = head->next;\n        }\n        \n        return phead->next;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1181-1190/Before and After Puzzle.cpp",
    "content": "class Solution {\n    \n    string getfirst(string& s) {\n        size_t pos = s.find(' ');\n        if (pos == string::npos) return s;\n        return s.substr(0, pos);\n    }\n    \n    string getlast(string& s) {\n        size_t pos = s.find_last_of(' ');\n        if (pos == string::npos) return s;\n        return s.substr(pos+1);\n    }\n    \npublic:\n    vector<string> beforeAndAfterPuzzles(vector<string>& phrases) {\n        map<string, vector<int>> firstmap;\n        map<string, vector<int>> lastmap;\n        for (int i = 0; i < phrases.size(); i++) {\n            string& s = phrases[i];\n            string first = getfirst(s);\n            firstmap[first].push_back(i);\n            string last = getlast(s);\n            lastmap[last].push_back(i);\n        }\n        \n        set<string> ans;\n        for (auto& it : lastmap) {\n            const string& s = it.first;\n            if (firstmap.count(s) > 0) {\n                vector<int>& seconds = firstmap[s];\n                vector<int>& firsts = it.second;\n                for (int i : firsts) {\n                    string original_first = phrases[i];\n                    string f;\n                    size_t pos = original_first.find_last_of(' ');\n                    if (pos == string::npos) f = \"\";\n                    else f = original_first.substr(0, pos+1);\n                    for (int j : seconds) {\n                        if (i == j) continue;\n                        string original_second = phrases[j];\n                        ans.insert(f + original_second);\n                    }\n                }\n            }\n        }\n        vector<string> return_ans(ans.begin(), ans.end());\n        return return_ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1181-1190/Day of the Week.cpp",
    "content": "class Solution {\npublic:\n    string dayOfTheWeek(int day, int month, int year) {\n        vector<int> t {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};  \n        year -= (month < 3);  \n        int v = (year + year / 4 - year / 100 +  year / 400 + t[month - 1] + day) % 7;  \n        if (v == 1) return \"Monday\";\n        if (v == 2) return \"Tuesday\";\n        if (v == 3) return \"Wednesday\";\n        if (v == 4) return \"Thursday\";\n        if (v == 5) return \"Friday\";\n        if (v == 6) return \"Saturday\";\n        return \"Sunday\";\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1181-1190/Design Bounded Blocking Queue.cpp",
    "content": "// copy form https://leetcode.com/problems/design-bounded-blocking-queue/discuss/394855/C%2B%2B-Mutex-and-Condition-Variable-w-Predicate\nclass BoundedBlockingQueue {\nprivate:\n    mutex m_queue_mutex;\n    condition_variable m_queue_changed;\n    queue<int> m_queue; // m_queue_mutex\n    int m_capacity; // m_queue_mutex\n    \npublic:\n    BoundedBlockingQueue(int capacity) {\n        // Initialize queue and capacity\n        m_capacity = capacity;\n    }\n    \n    void enqueue(int element) {\n        // Add to front of queue\n        // If full, block caller until enqueue succeeds\n        {\n            unique_lock<mutex> lk(m_queue_mutex);\n\n            // Grab the lock with queue size < capacity\n            m_queue_changed.wait(lk, [this] {return m_queue.size() < m_capacity;});\n\n            m_queue.push(element);\n        }\n        \n        // Avoid waiters waking up and immediately blocking by unlocking\n        // before notifying\n        m_queue_changed.notify_all();\n    }\n    \n    int dequeue() {\n        // Remove from front of queue\n        // If empty, block caller until dequeue succeeds\n        int ret;\n        {\n            unique_lock<mutex> lk(m_queue_mutex);\n\n            // Grab the lock with queue size > 0\n            m_queue_changed.wait(lk, [this] {return !m_queue.empty();});\n\n            ret = m_queue.front();\n            m_queue.pop();\n        }\n        m_queue_changed.notify_all();\n        \n        return ret;\n    }\n    \n    int size() {\n        // returns size of queue\n        unique_lock<mutex> lk(m_queue_mutex);\n        return m_queue.size();\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1181-1190/Distance Between Bus Stops.cpp",
    "content": "class Solution {\npublic:\n    int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {\n        int dis_a = 0;\n        int dis_b = 0;\n        int n = distance.size();\n        \n        int s = start;\n        int d = destination;\n        while (s != d) {\n            dis_a += distance[s];\n            s = (s+1) % n;\n        }\n        \n        s = start; d = destination;\n        while (s != d) {\n            s = ( (s-1) + n) % n;\n            dis_b += distance[s];\n        }\n        \n        return min(dis_a, dis_b);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1181-1190/Make Array Strictly Increasing.cpp",
    "content": "class Solution {\n    map<pair<int, int>, int> cache;\npublic:\n    int makeArrayIncreasing(vector<int>& arr1, vector<int>& arr2) {\n        sort(arr2.begin(), arr2.end());\n        int val= dfs(arr1, arr2, 0, -1);\n        if(val>=2000)\n            return -1;\n        else\n            return val;\n    }\n    \n    int dfs(vector<int>& arr1, vector<int>& arr2, int i, int prev) {\n        if (i >= arr1.size()) return 0;\n        pair<int, int> key = {i, prev};\n        if (cache.count(key) > 0) return cache[key];\n        \n        // find the next greater element in arr2 than prev\n        auto it = upper_bound(arr2.begin(), arr2.end(), prev);\n        int j = it - arr2.begin();\n        \n        int val;\n        if (arr1[i] <= prev) {\n            // Current value is not valid.\n            if (j >= arr2.size()) {\n                // we cannot find any value in arr2 to replace\n                val = 2500;\n            } else {\n                val = 1 + dfs(arr1, arr2, i+1, arr2[j]);   \n            }\n        } else {\n            // Current value in arr1 is ok.\n            // If we cannot make use of arr2 or arr1[i] is smaller than arr2[j](greedy).\n            if (j >= arr2.size() || arr1[i] <= arr2[j]) {\n                val = dfs(arr1, arr2, i+1, arr1[i]);\n            } else {\n                val = min(dfs(arr1, arr2, i+1, arr1[i]), 1+dfs(arr1, arr2, i+1, arr2[j]));\n            }\n        }\n        \n        return cache[key] = val;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/1001-10000/1181-1190/Maximum Subarray Sum with One Deletion.cpp",
    "content": "class Solution {\n    \n    int getV(vector<int>& dp, int i) {\n        if (i < 0 || i >= dp.size()) return -100000;\n        return dp[i];\n    }\n    \npublic:\n    int maximumSum(vector<int>& arr) {\n        int n = arr.size();\n        if (n == 1) return arr[0];\n        vector<int> dp1(n, 0);\n        vector<int> dp2(n, 0); \n\n        dp1[0] = arr[0]; \n        for (int i = 1; i < n; i++)  { \n            dp1[i] = max(arr[i], dp1[i-1] + arr[i]); \n        }\n\n        dp2[n-1] = arr[n-1]; \n        for (int i = n-2; i >= 0; i--)  { \n            dp2[i] = max(arr[i], dp2[i+1] + arr[i]);\n        }\n\n        int ans = INT_MIN;\n        for (int i = 0; i < n; i++) {\n            ans = max(ans, max(getV(dp1, i-1), getV(dp2, i+1)));\n            ans = max(ans, getV(dp1, i-1) + getV(dp2, i+1));\n        }\n        return ans; \n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1181-1190/Shortest Distance to Target Color.cpp",
    "content": "class Solution {\npublic:\n    vector<int> shortestDistanceColor(vector<int>& colors, vector<vector<int>>& queries) {\n        int n = colors.size();\n        vector<vector<int>> dp(n, vector<int>(3, INT_MAX));\n        \n        vector<int> pos(3, -1);\n        for (int i = 0; i < colors.size(); i++) {\n            int color = colors[i];\n            pos[color-1] = i;\n            for (int k = 0; k < 3; k++) {\n                dp[i][k] = pos[k] >= 0 ? i - pos[k] : INT_MAX;\n            }\n        }\n        \n        pos[0] = pos[1] = pos[2] = -1;\n        for (int i = colors.size()-1; i >= 0; i--) {\n            int color = colors[i];\n            pos[color-1] = i;\n            for (int k = 0; k < 3; k++) {\n                dp[i][k] = min(dp[i][k], pos[k] >= 0 ? pos[k] - i : INT_MAX);\n            }\n        }\n        \n        vector<int> ans;\n        for (auto& query : queries) {\n            int v = dp[query[0]][query[1]-1];\n            ans.push_back(v == INT_MAX ? -1 : v);\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1191-1200/Minimum Knight Moves.cpp",
    "content": "class Solution {\npublic:\n    int minKnightMoves(int x, int y) {\n        queue<pair<int, int>> myqueue;\n        unordered_set<int> visited;\n        myqueue.push({0, 0});\n        visited.insert(0);\n        \n        int step = 0;\n        vector<pair<int, int>> directions = {{1,2},{2,1},{2,-1},{1,-2},{-1,2},{-2,1},{-1,-2},{-2,-1}};\n        \n        while (!myqueue.empty()) {\n            \n            int k = myqueue.size();\n            \n            for (int i = 0; i < k; i++) {\n                pair<int, int> cur = myqueue.front();\n                myqueue.pop();\n                \n                if (cur.first == x && cur.second == y) {\n                    return step;\n                }\n                \n                for (const auto& d : directions) {\n                    int nx = cur.first + d.first;\n                    int ny = cur.second + d.second;\n                    if (nx < -300 || ny < -300 || ny > 300 || nx > 300) continue;\n                    if ((abs(nx) + abs(ny)) > 300) continue;\n                    \n                    int key = nx * 1000 + ny;\n                    \n                    if (visited.count(key) > 0) continue;\n                    \n                    visited.insert(key);\n                    myqueue.push({nx, ny});\n                }\n            }\n            \n            step++;\n        }\n        \n        return step;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1201-1210/Design Skiplist.cpp",
    "content": "class Skiplist {\n    \n    struct Node {\n        Node *right, *down;\n        int val;\n        Node(Node *right, Node *down, int val): right(right), down(down), val(val) {}\n    };\n    \n    Node* head;\n    \npublic:\n    Skiplist() {\n        head = new Node(nullptr, nullptr, -1);\n    }\n    \n    bool search(int num) {\n        Node *cur = head;\n        while (cur != nullptr) {\n            while (cur->right != nullptr && cur->right->val < num) {\n                cur = cur->right;\n            }\n            \n            if (cur->right == nullptr || cur->right->val > num) {\n                cur = cur->down;\n            } else {\n                return true;\n            }\n        }\n        return false;\n    }\n    \n    void add(int num) {\n        stack<Node*> insertPoints;\n        Node *cur = head;\n        while (cur != nullptr) {\n            while (cur->right != nullptr && cur->right->val < num) {\n                cur = cur->right;\n            }\n            insertPoints.push(cur);\n            cur = cur->down;\n        }\n        \n        Node* downNode = nullptr;\n        bool insertUp = true;\n        while (insertUp && !insertPoints.empty()) {\n            Node *ins = insertPoints.top();\n            insertPoints.pop();\n            \n            ins->right = new Node(ins->right, downNode, num);\n            downNode = ins->right;\n            \n            insertUp = ((rand() & 1) == 0);\n        }\n        \n        if (insertUp) {\n            head = new Node(new Node(NULL, downNode, num), head, -1);\n        }\n    }\n    \n    bool erase(int num) {\n        Node *cur = head;\n        bool seen = false;\n        while (cur != nullptr) {\n            while (cur->right != nullptr && cur->right->val < num) {\n                cur = cur->right;\n            }\n            \n            if (cur->right == nullptr || cur->right->val > num) {\n                cur = cur->down;\n            } else {\n                seen = true;\n                Node* to_delete = cur->right;\n                cur->right = cur->right->right;\n                cur = cur->down;\n                delete to_delete;\n            }\n        }\n        return seen;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1201-1210/Smallest String With Swaps.cpp",
    "content": "class Solution {\n    \n    void dfs(int node, vector<int>& group, vector<int>& colors, map<int, vector<int>>& graph) {\n        colors[node] = 1;\n        group.push_back(node);\n        \n        for (int neighbor : graph[node]) {\n            if (colors[neighbor] == 0) {\n                dfs(neighbor, group, colors, graph);\n            }\n        }\n    }\n    \npublic:\n    string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {\n        map<int, vector<int>> graph;\n        for (const auto& pair : pairs) {\n            graph[pair[0]].push_back(pair[1]);\n            graph[pair[1]].push_back(pair[0]);\n        }\n        \n        int n = s.length();\n        vector<int> colors(n, 0);\n        \n        for (int i = 0; i < n; i++) {\n            if (colors[i] == 0) {\n                vector<int> group;\n                dfs(i, group, colors, graph);\n                sort(group.begin(), group.end());\n                \n                string temp;\n                for (int index : group) temp += s[index];\n                sort(temp.begin(), temp.end());\n                for (int k = 0; k < group.size(); k++) {\n                    s[group[k]] = temp[k];\n                }\n            }\n        }\n        \n        return s;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1221-1230/Dice Roll Simulation.cpp",
    "content": "class Solution {\npublic:\n    int dieSimulator(int n, vector<int>& rollMax) {\n        long cnt = 0;\n        long MOD = 1e9+7;\n        vector<vector<long>> dp(7, vector<long>(16, 0));\n        dp[1][1] = dp[2][1] = dp[3][1] = dp[4][1] = dp[5][1] = dp[6][1] = 1;\n        for (int k = 2; k <= n; k++) {\n            vector<vector<long>> dp_tmp(7, vector<long>(16, 0));\n            // 这一层循环，是骰子有6种可能性\n            for (int i = 1; i <= 6; i++) {\n                // 这一层循环，是前一次骰子有6种可能性\n                for (int j = 1; j <= 6; j++) {\n                    // 这一层循环，是前一次骰子在最后重复的次数\n                    for (int m = 1; m < 16; m++) {\n                        long v = dp[j][m];\n                        if (i == j) {\n                            if (m+1 <= rollMax[i-1]) {\n                                dp_tmp[i][m+1] = (dp_tmp[i][m+1] + v) % MOD;\n                            }\n                        } else {\n                            dp_tmp[i][1] = (dp_tmp[i][1] + v) % MOD;\n                        }\n                    }\n                }\n            }\n            \n            swap(dp, dp_tmp);\n        }\n        \n        for (int i = 1; i <= 6; i++) {\n            for (int j = 1; j <= 15; j++) {\n                cnt = (cnt + dp[i][j]) % MOD;\n            }\n        }\n        return cnt;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1221-1230/Queens That Can Attack the King.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king) {\n        vector<vector<int>> ans;\n        \n        vector<pair<int, int>> directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};\n        \n        set<pair<int, int>> q;\n        for (auto& queen : queens) {\n            q.insert({queen[0], queen[1]});\n        }\n        \n        for (auto& dir : directions) {\n            int x = king[0];\n            int y = king[1];\n            \n            while (true) {\n                x += dir.first;\n                y += dir.second;\n                if (x < 0 || y < 0 || x >= 8 || y >= 8) break;\n                if (q.count({x,y}) > 0) {\n                    ans.push_back({x, y});\n                    break;\n                }\n            }\n        }\n        \n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1221-1230/Split a String in Balanced Strings.cpp",
    "content": "class Solution {\npublic:\n    int balancedStringSplit(string s) {\n        int ans = 0;\n        int num = 0;\n        for (char ch : s) {\n            num += (ch == 'L') ? 1 : -1;\n            if (num == 0) ans++;\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1231-1240/Maximum Profit in Job Scheduling.cpp",
    "content": "struct Entry {\n    int start_time;\n    int end_time;\n    int profit;\n};\n\nclass Solution {\npublic:\n    int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {\n        map<int, int> dp;\n        int maximum_profit = 0;\n        int n = profit.size();\n        vector<Entry> entries;\n        for (int i = 0; i < n; i++) {\n            Entry entry;\n            entry.start_time = startTime[i];\n            entry.end_time = endTime[i];\n            entry.profit = profit[i];\n            entries.push_back(entry);\n        }\n        \n        auto cmp = [](const Entry& lhs, const Entry& rhs) {\n            return lhs.end_time <= rhs.end_time;\n        };\n        sort(entries.begin(), entries.end(), cmp);\n        \n        for (const Entry& entry : entries) {\n            auto it = dp.upper_bound(entry.start_time);\n            int max_profit_until_start_time = 0;\n            if (it != dp.begin()) {\n                max_profit_until_start_time = (--it)->second;\n            }\n            int current_profit = max_profit_until_start_time + entry.profit;\n            maximum_profit = max(maximum_profit, current_profit);\n            dp[entry.end_time] = maximum_profit;\n        }\n        \n        return maximum_profit;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1231-1240/Replace the Substring for Balanced String.cpp",
    "content": "class Solution {\n\npublic:\n    int balancedString(string s) {\n        map<char, int> sum;\n        int n = s.length();\n        int needed = n/4;\n        for (char ch : s) sum[ch]++;\n        int ans = INT_MAX;\n        \n        map<char, int> chInSubString;\n        \n        int i = 0, j = -1;\n        while (j < n) {\n            int temp = 0;\n            for (char ch : {'Q', 'W', 'E', 'R'}) {\n                int ch_needed = needed - (sum[ch] - chInSubString[ch]);\n                if (ch_needed > 0) temp += ch_needed;\n            }\n\n            if (temp <= (j-i+1)) {\n                ans = min(ans, temp);\n                chInSubString[s[i]]--;\n                i++;\n            } else {\n                j++;\n                chInSubString[s[j]]++;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1241-1250/Minimum Remove to Make Valid Parentheses.cpp",
    "content": "class Solution {\npublic:\n    string minRemoveToMakeValid(string s) {\n        stack<int> mystack;\n        \n        for (int i = 0; i < s.length(); i++) {\n            char ch = s[i];\n            if (ch == '(') {\n                mystack.push(i);\n            } else if (ch == ')') {\n                if (!mystack.empty()) {\n                    mystack.pop();\n                } else {\n                    s[i] = '?';\n                }\n            }\n        }\n        \n        while (!mystack.empty()) {\n            s[mystack.top()] = '?';\n            mystack.pop();\n        }\n        \n        // https://www.geeksforgeeks.org/remove-spaces-from-a-given-string/\n        s.erase(remove(s.begin(), s.end(), '?'), s.end());\n        return s;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1241-1250/Web Crawler Multithreaded.cpp",
    "content": "/**\n * // This is the HtmlParser's API interface.\n * // You should not implement it, or speculate about its implementation\n * class HtmlParser {\n *   public:\n *     vector<string> getUrls(string url);\n * };\n */\nclass Solution {\n    \n    private:\n    int thread_num;\n    string hostname;\n    queue<string> q;\n    unordered_set<string> seen;\n    int working = 0;\n    bool done;\n    mutex m;\n    condition_variable cv;\n    \n    string extractHostName(const string& url){\n        int start = url.find('/') + 2;\n        int end =  url.find('/', start);\n        if(end == string::npos) \n            return url.substr(start);\n        return url.substr(start, end - start);\n    }\n    vector<thread> workers;\n    \n    // this a worker thread that will be doing tasks.\n    void startWorker(HtmlParser* parser){\n        while (done == false) {\n            unique_lock<mutex> ul(m);\n            \n            cv.wait(ul, [&]() {\n                return !q.empty() || done;\n            });\n            \n            if (done) {\n                return;\n            }\n            \n            string item = q.front();\n            q.pop();\n            working++;\n            \n            ul.unlock();\n            vector<string> urls = parser->getUrls(item);\n            ul.lock();\n            \n            for (const string& url : urls) {\n                if (seen.count(url) > 0 || (extractHostName(url) != hostname)) continue;\n                seen.insert(url);\n                q.push(url);\n            }\n            working--;\n            \n            if (q.empty() && working == 0) {\n                done = true;\n            }\n            \n            cv.notify_all();\n        }\n    }\n\npublic:\n    vector<string> crawl(string startUrl, HtmlParser htmlParser) {\n        // get the hostname for this url.\n        // mark it as seen.\n        hostname = extractHostName(startUrl);\n        seen.insert(startUrl);\n        done = false;\n        // get number of supported threads\n        thread_num = thread::hardware_concurrency();\n        // push the first task to do.\n        q.push(startUrl);\n        \n        // start bunch of worker threads.\n        for(int i = 0; i < thread_num; i++){\n            workers.emplace_back(&Solution::startWorker, this, &htmlParser);\n        }\n        \n        // join those threads so that crawl is a blocking call \n        for(auto &t : workers){\n            t.join();\n        }\n        // return every unique processed string\n        return vector<string>(seen.begin(), seen.end());\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1261-1270/Greatest Sum Divisible by Three.cpp",
    "content": "class Solution {\npublic:\n    int maxSumDivThree(vector<int>& nums) {\n        vector<int> dp(3, 0);\n        \n        for (int v : nums) {\n            vector<int> dp_copy = dp;\n            \n            for (int i = 0; i < 3; i++) {\n                int tmp = v + dp[i];\n                int mod = tmp % 3;\n                dp_copy[mod] = max(dp_copy[mod], tmp);\n            }\n            \n            dp = dp_copy;\n        }\n        \n        return dp[0];\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1281-1290/Convert Binary Number in a Linked List to Integer.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int getDecimalValue(ListNode* head) {\n        int ans = 0;\n        while(head) {\n            ans = 2*ans + head->val;\n            head = head->next;\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1281-1290/Element Appearing More Than 25% In Sorted Array.cpp",
    "content": "class Solution {\npublic:\n    int findSpecialInteger(vector<int>& arr) {\n        int pv = arr[0]-1;\n        int times = 0;\n        for (int v : arr) {\n            if (v == pv) {\n                times++;\n                if (times >= arr.size()/4) return v;\n            } else {\n                times = 0;\n                pv = v;\n            }\n        }\n        return arr.back();\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1281-1290/Remove Covered Intervals.cpp",
    "content": "class Solution {\npublic:\n    int removeCoveredIntervals(vector<vector<int>>& intervals) {\n        int ans = intervals.size();\n        sort(intervals.begin(), intervals.end());\n        int left = intervals[0][0];\n        int right = intervals[0][1];\n        for (int i = 1; i < intervals.size(); i++) {\n            int l = intervals[i][0];\n            int r = intervals[i][1];\n            if (l >= left && r <= right) ans--;\n            else {\n                left = l;\n                right = r;\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1291-1300/Maximum Side Length of a Square with Sum Less than or Equal to Threshold.cpp",
    "content": "class Solution {\n    \n    bool check(const vector<vector<long>>& sum, int side_length, int m, int n, int threshold) {\n        for (int i = 0; i <= m-side_length; i++) {\n            for (int j = 0; j <= n-side_length; j++) {\n                int x = i + side_length;\n                int y = j + side_length;\n                long current_sum = sum[x][y] - sum[i][y] - sum[x][j] + sum[i][j];\n                if (current_sum <= threshold) return true;\n            }\n        }\n        return false;\n    }\n    \npublic:\n    int maxSideLength(vector<vector<int>>& mat, int threshold) {\n        int m = mat.size();\n        int n = mat[0].size();\n        vector<vector<long>> sum(m+1, vector<long>(n+1, 0));\n        \n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                sum[i+1][j+1] = sum[i][j+1] + sum[i+1][j] - sum[i][j] + mat[i][j];\n            }\n        }\n        \n        int left = 1; int right = min(m, n);\n        int ans = 0;\n        while (left <= right) {\n            int mid = (left + right) / 2;\n            bool ok = check(sum, mid, m, n, threshold);\n            if (ok) {\n                ans = mid;\n                left = mid + 1;\n            } else {\n                right = mid - 1;\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1291-1300/Sequential Digits.cpp",
    "content": "class Solution {\npublic:\n    vector<int> sequentialDigits(int low, int high) {\n        string tmp = \"123456789\";\n        \n        vector<int> res;\n        for (int i = 0; i < 9; i++) {\n            for (int j = i+1; j <= 9; j++) {\n                int len = j - i;\n                string str = tmp.substr(i, len);\n                int v = stol(str);\n                if (v >= low && v <= high) res.push_back(v);\n            }\n        }\n        \n        sort(res.begin(), res.end());\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1311-1320/Minimum Distance to Type a Word Using Two Fingers.cpp",
    "content": "class Solution {\n    \n    int distance(int from, int to) {\n        if (from == 26) return 0;\n        int row_1 = from / 6;\n        int col_1 = from%6;\n        int row_2 = to / 6;\n        int col_2 = to%6;\n        return abs(row_1 - row_2) + abs(col_1 - col_2);\n    }\n    \n    int dfs(vector<vector<vector<int>>>& dp, const string& word, int index, int left, int right) {\n        if (index >= word.length()) return 0;\n        if (dp[left][right][index] != 0) return dp[left][right][index];\n        char ch = word[index];\n        int chv = ch - 'A';\n        \n        int temp = min(dfs(dp, word, index+1, chv, right) + distance(left, chv),\n                      dfs(dp, word, index+1, left, chv) + distance(right, chv));\n        return dp[left][right][index] = temp;\n    }\n    \npublic:\n    int minimumDistance(string word) {\n        vector<vector<vector<int>>> dp(27, vector<vector<int>>(27, vector<int>(301, 0)));\n        return dfs(dp, word, 0, 26, 26);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1411-1420/Minimum Value to Get Positive Step by Step Sum.cpp",
    "content": "class Solution {\npublic:\n    int minStartValue(vector<int>& nums) {\n        int sum = 0;\n        int minVal = INT_MAX;\n        \n        for (int v : nums) {\n            sum += v;\n            minVal = min(minVal, sum);\n        }\n        \n        return 1 - minVal <= 0 ? 1 : 1 - minVal;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1421-1430/Leftmost Column with at Least a One.cpp",
    "content": "/**\n * // This is the BinaryMatrix's API interface.\n * // You should not implement it, or speculate about its implementation\n * class BinaryMatrix {\n *   public:\n *     int get(int row, int col);\n *     vector<int> dimensions();\n * };\n */\n\nclass Solution {\npublic:\n    int leftMostColumnWithOne(BinaryMatrix &binaryMatrix) {\n        vector<int> dimension = binaryMatrix.dimensions();\n        int row = dimension[0];\n        int col = dimension[1];\n        int res = -1;\n        for (int i = 0; i < row; i++) {\n            int left = 0;\n            int right = (res == -1 ? col - 1 : res - 1);\n            while (left < right) {\n                int mid = left + (right - left) / 2;\n                if (binaryMatrix.get(i, mid) == 0) {\n                    left = mid + 1;\n                } else {\n                    right = mid;\n                }\n            }\n\n            if (binaryMatrix.get(i, left) == 1) {\n                res = left;\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1481-1490/Avoid Flood in The City.cpp",
    "content": "class Solution {\npublic:\n    vector<int> avoidFlood(vector<int>& rains) {\n        \n        unordered_map<int, int> days_to_clear;\n        set<int> available_days;\n        \n        vector<int> ans(rains.size(), 1);\n        for (int i = 0; i < rains.size(); i++) {\n            \n            if (rains[i] == 0) {\n                available_days.insert(i);\n            } else {\n                if (days_to_clear.count(rains[i]) > 0) {\n                    \n                    auto it = available_days.lower_bound(days_to_clear[rains[i]]);\n                    \n                    if (it == available_days.end()) {\n                        return vector<int>();\n                    } else {\n                        ans[*it] = rains[i];\n                        days_to_clear.erase(rains[i]);\n                        available_days.erase(it);\n                    }\n                    \n                }\n                days_to_clear[rains[i]] = i;\n                ans[i] = -1;\n            }\n            \n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1481-1490/Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree.cpp",
    "content": "class UF {\n    \nprivate:\n    vector<int> parent;\n    vector<int> rank;\n    int count;\n    int N;\n    \npublic:\n    \n    UF(int N) : parent(N), rank(N, 0), N(N), count(N) {\n        for (int i = 0; i < N; i++) {\n            parent[i] = i;\n        }\n    }\n    \n    int find(int p) {\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];    // path compression by halving\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    int getCount() const {\n        return count;\n    }\n    \n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    void Union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rootP == rootQ) return;\n        \n        // make root of smaller rank point to root of larger rank\n        if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;\n        else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;\n        else {\n            parent[rootQ] = rootP;\n            rank[rootP]++;\n        }\n        count--;\n    }\n    \n    ~UF() {}\n};\n\nclass Solution {\npublic:\n    vector<vector<int>> findCriticalAndPseudoCriticalEdges(int n, vector<vector<int>>& edges) {\n        vector<vector<int>> all_edges(1001);\n        for (int i = 0; i < edges.size(); i++) {\n            all_edges[edges[i][2]].push_back(i);\n        }\n        \n        vector<vector<int>> ans(2);\n        UF uf(n);\n        \n        for (int i = 1; i <= 1000; i++) {\n            \n            vector<int> candidates;\n            \n            for (int index : all_edges[i]) {\n                const vector<int>& edge = edges[index];\n                if (!uf.connected(edge[0], edge[1])) {\n                    candidates.push_back(index);\n                }\n            }\n            \n            for (int check_index = 0; check_index < candidates.size(); check_index++) {\n                UF copy = uf;\n                for (int k = 0; k < candidates.size(); k++) {\n                    if (check_index == k) continue;\n                    const vector<int>& k_edge = edges[candidates[k]];\n                    if (!copy.connected(k_edge[0], k_edge[1])) {\n                        copy.Union(k_edge[0], k_edge[1]);\n                    }\n                }\n                const vector<int>& check_edge = edges[candidates[check_index]];\n                if (!copy.connected(check_edge[0], check_edge[1])) {\n                    ans[0].push_back(candidates[check_index]);\n                } else {\n                    ans[1].push_back(candidates[check_index]);\n                }\n            }\n            \n            for (int k = 0; k < candidates.size(); k++) {\n                const vector<int>& current_edge = edges[candidates[k]];\n                if (!uf.connected(current_edge[0], current_edge[1])) {\n                    uf.Union(current_edge[0], current_edge[1]);\n                }\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1481-1490/Making File Names Unique.cpp",
    "content": "class Solution {\npublic:\n    vector<string> getFolderNames(vector<string>& names) {\n        unordered_map<string, int> visited;\n        vector<string> ans;\n        \n        for (const string& name : names) {\n            if (visited.count(name) == 0) {\n                ans.push_back(name);\n                visited[name]++;\n            } else {\n                int i = visited[name];\n                while (true) {\n                    string new_name = name + \"(\" + to_string(i) + \")\";\n                    if (visited.count(new_name) == 0) {\n                        ans.push_back(new_name);\n                        visited[name] = i;\n                        visited[new_name]++;\n                        break;\n                    }\n                    i++;\n                }\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1481-1490/XOR Operation in an Array.cpp",
    "content": "class Solution {\npublic:\n    int xorOperation(int n, int start) {\n        if (n == 1) return start;\n\n        int last = start + 2 * (n - 1);\n        \n        if (start % 4 <= 1) {\n            if (n % 4 == 0) return 0;\n            if (n % 4 == 1) return last;\n            if (n % 4 == 2) return 2;\n            else return 2 ^ last;\n        }\n        \n        return start ^ xorOperation(n-1, start + 2);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1501-1510/Stone Game IV.cpp",
    "content": "class Solution {\npublic:\n    bool winnerSquareGame(int n) {\n        vector<int> dp(n+1, false);\n        dp[0] = false;\n        \n        vector<int> squares;\n        for (int i = 1; i*i <= n; i++) {\n            squares.push_back(i*i);\n        }\n        \n        for (int i = 1; i <= n; i++) {\n            for (int square : squares) {\n                if (i - square < 0) {\n                    break;\n                }\n                \n                if (dp[i-square] == false) {\n                    dp[i] = true;\n                    break;\n                }\n            }\n        }\n        \n        return dp[n];\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1541-1550/Minimum Insertions to Balance a Parentheses String.cpp",
    "content": "class Solution {\npublic:\n   int minInsertions(string s) {\n       int res = 0;\n       int close_needed = 0;\n       \n       \n       for (int i = 0; i < s.length(); i++) {\n           \n           if (s[i] == '(') {\n               if (close_needed % 2 == 1) {\n                   // Handle previous case like '()('\n                   res++;\n                   close_needed--;\n               }\n               close_needed += 2; // Add 2 required close for current '('\n           } else {\n               if (close_needed == 0) {\n                   res++;\n                   close_needed++;\n               } else {\n                   close_needed--;\n               }\n           }\n           \n       }\n       \n       return res + close_needed;\n   }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1561-1570/Dot Product of Two Sparse Vectors.cpp",
    "content": "class SparseVector {\npublic:\n    \n    vector<pair<int, int>> idx_value_pairs;\n    \n    SparseVector(vector<int> &nums) {\n        for (int i = 0; i < nums.size(); i++) {\n            if (nums[i] == 0) continue;\n            \n            idx_value_pairs.push_back({i, nums[i]});\n        }\n    }\n    \n    // Return the dotProduct of two sparse vectors\n    int dotProduct(SparseVector& vec) {\n        int i = 0, j = 0;\n        int result = 0;\n        \n        while (i < idx_value_pairs.size() && j < vec.idx_value_pairs.size()) {\n            if (idx_value_pairs[i].first < vec.idx_value_pairs[j].first) {\n                i++;\n            } else if (idx_value_pairs[i].first > vec.idx_value_pairs[j].first) {\n                j++;\n            } else {\n                result += (idx_value_pairs[i].second * vec.idx_value_pairs[j].second);\n                i++;\n                j++;\n            }\n        }\n        \n        return result;\n    }\n};\n\n// Your SparseVector object will be instantiated and called as such:\n// SparseVector v1(nums1);\n// SparseVector v2(nums2);\n// int ans = v1.dotProduct(v2);\n"
  },
  {
    "path": "cpp/1001-10000/1621-1630/Arithmetic Subarrays.cpp",
    "content": "class Solution {\n    \n    bool check(const vector<int>& vec) {\n        for (int i = 2; i < vec.size(); i++) {\n            if ((vec[i] - vec[i-1]) != (vec[i-1] - vec[i-2])) return false;\n        }\n        return true;\n    }\n    \npublic:\n    vector<bool> checkArithmeticSubarrays(vector<int>& nums, vector<int>& l, vector<int>& r) {\n        vector<bool> ans;\n        \n        int m = l.size();\n        \n        for (int i = 0; i < m; i++) {\n            int a1 = l[i];\n            int a2 = r[i];\n            vector<int> tmp(nums.begin()+a1, nums.begin()+a2+1);\n            \n            sort(tmp.begin(), tmp.end());\n            ans.push_back(check(tmp));\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1621-1630/Slowest Key.cpp",
    "content": "class Solution {\npublic:\n    char slowestKey(vector<int>& releaseTimes, string keysPressed) {\n        int max_time = -1;\n        char ans;\n        \n        for (int i = 0; i < releaseTimes.size(); i++) {\n            int time = (i == 0 ? releaseTimes[0] : releaseTimes[i] - releaseTimes[i-1]);\n            if (time > max_time) {\n                max_time = time;\n                ans = keysPressed[i];\n            } else if (time == max_time) {\n                ans = max(ans, keysPressed[i]);\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1631-1640/Check Array Formation Through Concatenation.cpp",
    "content": "class Solution {\npublic:\n    bool canFormArray(vector<int>& arr, vector<vector<int>>& pieces) {\n        map<int, int> mymap;\n        for (int i = 0; i < arr.size(); i++) {\n            mymap[arr[i]] = i;\n        }\n        \n        for (const vector<int>& piece : pieces) {\n            for (int i = 0; i < piece.size(); i++) {\n                if (mymap.count(piece[i]) == 0) {\n                    return false;\n                }\n            }\n        }\n        \n        for (const vector<int>& piece : pieces) {\n            for (int i = 1; i < piece.size(); i++) {\n                if (mymap[piece[i-1]] > mymap[piece[i]]) {\n                    return false;\n                }\n            }\n        }\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1631-1640/Number of Ways to Form a Target String Given a Dictionary.cpp",
    "content": "class Solution {\npublic:\n    int numWays(vector<string>& words, string target) {\n        int n = target.length();\n        long mod = 1e9 + 7;\n        vector<long> res(n + 1);\n        res[0] = 1;\n\n        for (int i = 0; i < words[0].length(); ++i) {\n            vector<int> count(26, 0);\n            \n            for (const string& w : words) {\n                count[w[i] - 'a']++;\n            }\n            \n            for (int j = n - 1; j >= 0; --j) {\n                res[j + 1] += res[j] * count[target[j] - 'a'] % mod;\n                res[j + 1] %= mod;\n            }\n        }\n        \n        return res[n];\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1631-1640/Path With Minimum Effort.cpp",
    "content": "class Solution {\npublic:\n    int minimumEffortPath(vector<vector<int>>& heights) {\n        int m = heights.size();\n        int n = heights[0].size();\n        auto cmp = [](const pair<int, pair<int, int>>& a, pair<int, pair<int, int>>& b) {\n            return a.first > b.first;\n        };\n        priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, decltype(cmp)> myqueue(cmp);\n        myqueue.push({0, {0, 0}});\n        set<pair<int, int>> visited;\n        \n        while (!myqueue.empty()) {\n            pair<int, pair<int, int>> cur = myqueue.top();\n            myqueue.pop();\n            int height = cur.first;\n            pair<int, int> pos = cur.second;\n            if (pos.first == m-1 && pos.second == n-1) return height;\n            if (visited.count(cur.second) > 0) continue;\n            visited.insert(cur.second);\n            \n            pair<int, int> dirs[4] = {{1,0}, {-1,0}, {0,1}, {0,-1}};\n            for (pair<int, int> dir : dirs) {\n                int pos_x = pos.first + dir.first;\n                int pos_y = pos.second + dir.second;\n                if (pos_x < 0 || pos_x >= m || pos_y < 0 || pos_y >= n) continue;\n                int new_height = max(height, abs(heights[pos_x][pos_y] - heights[pos.first][pos.second]));\n                myqueue.push({new_height, {pos_x, pos_y}});\n            }\n        }\n        \n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1631-1640/Rank Transform of a Matrix.cpp",
    "content": "class UF {\n    \nprivate:\n    vector<int> parent;\n    vector<int> rank;\n    int count;\n    int N;\n    \n    bool validate(int p) {\n        return (p >= 0 && p < N);\n    }\n    \npublic:\n    \n    UF(int N) : parent(N), rank(N, 0), N(N), count(N) {\n        for (int i = 0; i < N; i++) {\n            parent[i] = i;\n        }\n    }\n    \n    int find(int p) {\n        if (!validate(p)) return -1;\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];    // path compression by halving\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    int getCount() const {\n        return count;\n    }\n    \n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    void Union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rootP == rootQ) return;\n        \n        // make root of smaller rank point to root of larger rank\n        if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;\n        else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;\n        else {\n            parent[rootQ] = rootP;\n            rank[rootP]++;\n        }\n        count--;\n    }\n    \n    ~UF() {}\n};\n\nclass Solution {\n    \n    vector<vector<pair<int, int>>> group(const vector<pair<int, int>>& positions) {\n        int n = positions.size();\n        UF uf(n);\n        \n        unordered_map<int, vector<int>> rows;\n        unordered_map<int, vector<int>> cols;\n        for (int i = 0; i < positions.size(); i++) {\n            pair<int, int> pos = positions[i];\n            rows[pos.first].push_back(i);\n            cols[pos.second].push_back(i);\n        }\n        \n        for (auto &it : rows) {\n            vector<int> eles = it.second;\n            for (int i = 1; i < eles.size(); i++) {\n                uf.Union(eles[0], eles[i]);\n            }\n        }\n        for (auto &it : cols) {\n            vector<int> eles = it.second;\n            for (int i = 1; i < eles.size(); i++) {\n                uf.Union(eles[0], eles[i]);\n            }\n        }\n        \n        map<int, vector<pair<int, int>>> groups;\n        for (int i = 0; i < n; i++) {\n            groups[uf.find(i)].push_back(positions[i]);\n        }\n        \n        vector<vector<pair<int, int>>> res;\n        for (auto& it : groups) {\n            res.push_back(it.second);\n        }\n        return res;\n    }\n    \npublic:\n    vector<vector<int>> matrixRankTransform(vector<vector<int>>& matrix) {\n        int m = matrix.size();\n        int n = matrix[0].size();\n        \n        map<int, vector<pair<int, int>>> mymap;\n        \n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                int v = matrix[i][j];\n                mymap[v].push_back({i, j});\n            }\n        }\n        \n        vector<vector<int>> rank(m, vector<int>(n, 0));\n        \n        unordered_map<int, int> rank_x_max;\n        unordered_map<int, int> rank_y_max;\n        \n        for (auto& it : mymap) {\n            int val = it.first;\n            const vector<pair<int, int>>& positions = it.second;\n            vector<vector<pair<int, int>>> positions_group = group(positions);\n            \n            for (const vector<pair<int, int>>& positions : positions_group) {\n            \n                int current_rank = 1;\n\n                for (const pair<int, int>& cur : positions) {\n                    int x = cur.first; int y = cur.second;\n\n                    int rank_1 = 1;\n                    if (rank_x_max.count(x) > 0) {\n                        rank_1 = rank_x_max[x]+1;\n                    }\n\n                    int rank_2 = 1;\n                    if (rank_y_max.count(y) > 0) {\n                        rank_2 = rank_y_max[y]+1;\n                    }\n\n                    current_rank = max(current_rank, max(rank_1, rank_2));\n                }\n                \n                for (const pair<int, int>& cur : positions) {\n                    int x = cur.first; int y = cur.second;\n                    rank[x][y] = current_rank;\n                    rank_x_max[x] = current_rank;\n                    rank_y_max[y] = current_rank;\n                }\n            }\n            \n        }\n        \n        return rank;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1641-1650/Count Sorted Vowel Strings.cpp",
    "content": "class Solution {\npublic:\n    int countVowelStrings(int n) {\n        map<char, int> dp;\n        dp['a'] = 1;\n        dp['e'] = 1;\n        dp['i'] = 1;\n        dp['o'] = 1;\n        dp['u'] = 1;\n        \n        for (int i = 1; i < n; i++) {\n            map<char, int> tmp;\n            tmp['a'] = dp['a'];\n            tmp['e'] = dp['a'] + dp['e'];\n            tmp['i'] = dp['a'] + dp['e'] + dp['i'];\n            tmp['o'] = dp['a'] + dp['e'] + dp['i'] + dp['o'];\n            tmp['u'] = dp['a'] + dp['e'] + dp['i'] + dp['o'] + dp['u'];\n            dp = tmp;\n        }\n        \n        return dp['a'] + dp['e'] + dp['i'] + dp['o'] + dp['u'];\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1641-1650/Create Sorted Array through Instructions.cpp",
    "content": "// Solution 1\nclass Solution {\n    \n    vector<int> sums;\n    \n    int left(int i) { return 2 * i + 1; }\n    int right(int i) { return 2 * i + 2; }\n    \n    int query(int v_min, int v_max, int l, int r, int root) {\n        if (v_min <= l && v_max >= r) {\n            return sums[root];\n        }\n        if (v_min > r || v_max < l) {\n            return 0;\n        }\n        \n        int mid = (l+r)/2;\n        return query(v_min, v_max, l, mid, left(root)) + query(v_min, v_max, mid+1, r, right(root));\n    }\n    \n    void update(int v, int l, int r, int root) {\n        if (v < l || v > r) {\n            return;\n        }\n        \n        sums[root]++;\n        \n        if (l == r) {\n            return;\n        }\n        \n        int mid = (l+r)/2;\n        \n        if (v <= mid) update(v, l, mid, left(root));\n        else update(v, mid+1, r, right(root));\n    }\n    \npublic:\n    int createSortedArray(vector<int>& instructions) {\n        long mod = 1e9+7;\n        long cost = 0;\n        int N = *max_element(instructions.begin(), instructions.end()) + 1;\n        sums.resize(4*N+4);\n        vector<int> count(N+1, 0);\n        \n        for (int i = 0; i < instructions.size(); i++) {\n            int v = instructions[i];\n            int small = query(0, v-1, 0, N-1, 0);\n            int great = i - small -count[v];\n            cost += min(small, great);\n            cost %= mod;\n            update(v, 0, N-1, 0);\n            count[v]++;\n        }\n        \n        return cost;\n    }\n};\n\n\n// Solution 2\nclass Solution {\n    \n    vector<int> sums;\n    \n    int left(int i) { return 2 * i + 1; }\n    int right(int i) { return 2 * i + 2; }\n    \n    int query(int v_min, int v_max, int l, int r, int root) {\n        if (v_min <= l && v_max >= r) {\n            return sums[root];\n        }\n        if (v_min > r || v_max < l) {\n            return 0;\n        }\n        \n        int mid = (l+r)/2;\n        return query(v_min, v_max, l, mid, left(root)) + query(v_min, v_max, mid+1, r, right(root));\n    }\n    \n    void update(int v, int l, int r, int root) {\n        if (v < l || v > r) {\n            return;\n        }\n        \n        sums[root]++;\n        \n        if (l == r) {\n            return;\n        }\n        \n        int mid = (l+r)/2;\n        \n        if (v <= mid) update(v, l, mid, left(root));\n        else update(v, mid+1, r, right(root));\n    }\n    \npublic:\n    int createSortedArray(vector<int>& instructions) {\n        long mod = 1e9+7;\n        long cost = 0;\n        int N = *max_element(instructions.begin(), instructions.end()) + 1;\n        sums.resize(4*N+4);\n        \n        for (int v : instructions) {\n            int small = query(0, v-1, 0, N-1, 0);\n            int great = query(v+1, 9999999, 0, N-1, 0);\n            cost += min(small, great);\n            cost %= mod;\n            update(v, 0, N-1, 0);\n        }\n        \n        return cost;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1641-1650/Furthest Building You Can Reach.cpp",
    "content": "class Solution {\npublic:\n    int furthestBuilding(vector<int>& heights, int bricks, int ladders) {\n        priority_queue<int, vector<int>, std::greater<int>> myqueue;\n        for (int i = 0; i < heights.size() - 1; i++) {\n            if (heights[i+1] > heights[i]) {\n                myqueue.push(heights[i+1] - heights[i]);\n            }\n            \n            if (myqueue.size() > ladders) {\n                int h = myqueue.top();\n                myqueue.pop();\n                bricks -= h;\n                if (bricks < 0) return i;\n            }\n        }\n        \n        return heights.size() - 1;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1641-1650/Get Maximum in Generated Array.cpp",
    "content": "class Solution {\npublic:\n    int getMaximumGenerated(int n) {\n        vector<int> ans(n+1, 0);\n        int val = 0;\n        for (int i = 0; i <= n; i++) {\n            if (i == 0) ans[i] = 0;\n            else if (i == 1) ans[i] = 1;\n            else if (i % 2 == 0) ans[i] = ans[i/2];\n            else ans[i] = ans[i/2] + ans[i/2+1];\n            val = max(val, ans[i]);\n        }\n        return val;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1641-1650/Kth Smallest Instructions.cpp",
    "content": "class Solution {\npublic:\n    string kthSmallestPath(vector<int>& destination, int k) {\n        int m = destination[0]+1;\n        int n = destination[1]+1;\n        vector<vector<int>> dp(m, vector<int>(n, 0));\n        dp[m-1][n-1] = 1;\n        \n        for (int i = m - 1; i >= 0; i--) {\n            for (int j = n - 1; j >= 0; j--) {\n                if (i != m -1) dp[i][j] += dp[i+1][j];\n                if (j != n - 1) dp[i][j] += dp[i][j+1];\n            }\n        }\n        \n        string ans;\n        int i = 0; int j = 0;\n        while ( !(i == m-1 && j == n-1) ) {\n            if (i == m-1) { ans += 'H'; j++; continue; }\n            else if (j == n-1) { ans += 'V'; i++; continue; }\n            \n            int h = dp[i][j+1];\n            int v = dp[i+1][j];\n            if (k <= h) {\n                ans += 'H'; j++;\n            } else {\n                k -= h;\n                ans += 'V'; i++;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1641-1650/Lowest Common Ancestor of a Binary Tree II.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    pair<TreeNode*, int> dfs(TreeNode* root, TreeNode* p, TreeNode* q) {\n        if (root == nullptr) {\n            return {nullptr, 0};\n        }\n    \n        pair<TreeNode*, int> l_res = dfs(root->left, p, q);\n        pair<TreeNode*, int> r_res = dfs(root->right, p, q);\n        \n        if (root == p || root == q) {\n            return {root, 1 + l_res.second + r_res.second};\n        }\n    \n        if (l_res.first && r_res.first) {\n            return {root, 2};\n        }\n    \n        return l_res.first ? l_res : r_res;\n    }\n        \npublic:\n    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {\n        pair<TreeNode*, int> res = dfs(root, p, q);\n        if (res.second < 2) {\n            return nullptr;\n        }\n        return res.first;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1641-1650/Lowest Common Ancestor of a Binary Tree III.cpp",
    "content": "/*\n// Definition for a Node.\nclass Node {\npublic:\n    int val;\n    Node* left;\n    Node* right;\n    Node* parent;\n};\n*/\n\nclass Solution {\npublic:\n    Node* lowestCommonAncestor(Node* p, Node * q) {\n        Node* a = p, *b = q;\n        while (a != b) {\n            a = (a == nullptr ? q : a->parent);\n            b = (b == nullptr ? p : b->parent);\n        }\n        return a;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1641-1650/Minimum Deletions to Make Character Frequencies Unique.cpp",
    "content": "class Solution {\npublic:\n    int minDeletions(string s) {\n        map<char, int> mymap;\n        for (char ch : s) {\n            mymap[ch]++;\n        }\n        \n        set<int> used;\n        \n        int ans = 0;\n        \n        for (const auto& it : mymap) {\n            int freq = it.second;\n            while(used.count(freq) > 0) {\n                freq--;\n                ans++;\n            }\n            if (freq > 0) {\n                used.insert(freq);\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1641-1650/Sell Diminishing-Valued Colored Balls.cpp",
    "content": "class Solution {\n    \n    long get(long a, long b) {\n        return (a+b) * (b-a+1) / 2; \n    }\n    \npublic:\n    int maxProfit(vector<int>& inventory, int orders) {\n        int n = inventory.size();\n        long mod = 1e9+7;\n        long ans = 0;\n        \n        map<int, int> mymap;\n        \n        for (int v : inventory) {\n            mymap[v]++;\n        }\n        \n        priority_queue<pair<int,int>> myqueue;\n        \n        for (const auto& it : mymap) {\n            myqueue.push({it.first, it.second});\n        }\n        \n        while (orders > 0) {\n            pair<int, int> top = myqueue.top();\n            myqueue.pop();\n            \n            pair<int, int> second;\n            bool has_second = false;\n            long to_num = 0;\n            if (myqueue.size() > 0) {\n                has_second = true;\n                second = myqueue.top();\n                myqueue.pop();\n                to_num = second.first;\n            }\n            \n            long from_num = top.first;\n            long from_freq = top.second;\n            int total_orders = (from_num - to_num) * from_freq;\n            if (total_orders > orders) {\n                int consume = orders/from_freq;\n                to_num = from_num - consume;\n                ans += (get(to_num+1, from_num) % mod) * from_freq % mod;\n                orders -= from_freq*consume;\n                while (orders > 0) {\n                    ans += to_num;\n                    ans %= mod;\n                    orders--;\n                }\n            } else {\n                ans += (get(to_num+1, from_num) % mod) * from_freq % mod;\n                orders -= total_orders;\n                myqueue.push({to_num, from_freq+second.second});\n            }\n        }\n        \n        ans %= mod;\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1671-1680/Lowest Common Ancestor of a Binary Tree IV.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\n    \n    TreeNode* lowestCommonAncestor(TreeNode* root, const set<TreeNode*>& nodes_set) {\n        if (root == nullptr) {\n            return nullptr;\n        }\n    \n        if (nodes_set.count(root) > 0) {\n            return root;\n        }\n    \n        TreeNode* l = lowestCommonAncestor(root->left, nodes_set);\n        TreeNode* r = lowestCommonAncestor(root->right, nodes_set);\n    \n        if (l && r) {\n            return root;\n        }\n    \n        return l ? l : r;\n    }\n    \npublic:\n    TreeNode* lowestCommonAncestor(TreeNode* root, vector<TreeNode*> &nodes) {\n        set<TreeNode*>nodes_set(nodes.begin(), nodes.end());\n        return lowestCommonAncestor(root, nodes_set);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1671-1680/Minimum Moves to Make Array Complementary.cpp",
    "content": "class Solution {\npublic:\n    int minMoves(vector<int>& nums, int limit) {\n        int n = nums.size();\n        vector<int> delta(2*limit+2, 0);\n        \n        for (int i = 0; i < n/2; i++) {\n            int a = min(nums[i], nums[n-1-i]);\n            int b = max(nums[i], nums[n-1-i]);\n            delta[2] += 2;\n            delta[a + 1]--;\n            delta[a + b]--;\n            delta[a + b + 1]++;\n            delta[b + limit + 1]++;\n        }\n        \n        int res = 2 * n;\n        int curr = 0;\n        for (int i = 2; i <= 2 * limit; i++) {\n            curr += delta[i];\n            res = min(res, curr);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1681-1690/Delivering Boxes from Storage to Ports.cpp",
    "content": "class Solution {\npublic:\n    int boxDelivering(vector<vector<int>>& boxes, int portsCount, int maxBoxes, int maxWeight) {\n        int n = boxes.size();\n        vector<int> dp(n+1, INT_MAX);\n        dp[0] = 0;\n        \n        int weight = 0;\n        int trips = 2;\n        \n        int left = 0;\n        for (int right = 0; right < n; right++) {\n            weight += boxes[right][1];\n            \n            // If current box is different than previous one, need to make one more trip.\n            if (right > 0 && boxes[right][0] != boxes[right-1][0]) {\n                trips++;   \n            }\n            \n            while ((right - left) >= maxBoxes || weight > maxWeight || \n                  (left < right && dp[left] == dp[left+1])) {\n                weight -= boxes[left][1];\n                \n                if (boxes[left][0] != boxes[left+1][0]) {\n                    trips--;\n                }\n                \n                left++;\n            }\n            \n            dp[right+1] = dp[left] + trips;\n        }\n        \n        return dp.back();\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1681-1690/Stone Game VI.cpp",
    "content": "class Solution {\npublic:\n    int stoneGameVI(vector<int>& aliceValues, vector<int>& bobValues) {\n        vector<pair<int, int>> values;\n        for (int i = 0; i < aliceValues.size(); i++) {\n            values.push_back({aliceValues[i], bobValues[i]});\n        }\n        \n        auto cmp = [](const pair<int, int>& l, const pair<int, int>& r) {\n            return (l.first+l.second) > (r.first+r.second);\n        };\n        \n        sort(values.begin(), values.end(), cmp);\n        \n        int alice = 0;\n        int bob = 0;\n        for (int i = 0; i < values.size(); i++) {\n            if (i % 2 == 0) {\n                alice += values[i].first;\n            } else {\n                bob += values[i].second;\n            }\n        }\n        \n        if (alice > bob) return 1;\n        else if (alice < bob) return -1;\n        return 0;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1681-1690/Sum of Absolute Differences in a Sorted Array.cpp",
    "content": "class Solution {\npublic:\n    vector<int> getSumAbsoluteDifferences(vector<int>& nums) {\n        vector<int> ans;\n        \n        int tmp = 0;\n        for (int i = 1; i < nums.size(); i++) {\n            tmp += (nums[i] - nums[0]);\n        }\n        ans.push_back(tmp);\n        \n        for (int i = 1; i < nums.size(); i++) {\n            int diff = (nums[i] - nums[i-1]);\n            int left = i - 1;\n            int right = nums.size() - left - 2;\n            \n            tmp += (left*diff - right*diff);\n            ans.push_back(tmp);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1701-1710/Determine if String Halves Are Alike.cpp",
    "content": "class Solution {\npublic:\n    bool halvesAreAlike(string s) {\n        map<char, int> mymap;\n        \n        int n = s.length()/2;\n        \n        for (int i = 0; i < n; i++) {\n            mymap[tolower(s[i])]++;\n        }\n        \n        for (int i = n; i < s.length(); i++) {\n            mymap[tolower(s[i])]--;\n        }\n        \n        return (mymap['a'] + mymap['e'] + mymap['i'] + mymap['o'] + mymap['u']) == 0;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1701-1710/Maximum Number of Eaten Apples.cpp",
    "content": "class Solution {\npublic:\n    int eatenApples(vector<int>& apples, vector<int>& days) {\n        auto cmp = [](const pair<int, int>& l, const pair<int, int>& r) {\n            return l.first > r.first;\n        };\n        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp);\n        \n        int n = apples.size();\n        int ans = 0;\n        \n        int i = 0;\n        for (; i < n; i++) {\n            \n            if (apples[i] > 0) {\n                pq.push({i+days[i], apples[i]});\n            }\n            \n            while (!pq.empty()) {\n                pair<int, int> ele = pq.top();\n                pq.pop();\n\n                if (ele.first > i) {\n                    ans++;\n                    ele.second--;\n                    if (ele.second > 0) {\n                        pq.push(ele);\n                    }\n                    break;\n                }\n            }\n        }\n        \n        while (!pq.empty()) {\n            pair<int, int> ele = pq.top();\n            pq.pop();\n\n            if (ele.first > i) {\n                ans++;\n                ele.second--;\n                if (ele.second > 0) {\n                    pq.push(ele);\n                }\n                \n                i++;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1701-1710/Maximum Units on a Truck.cpp",
    "content": "class Solution {\npublic:\n    int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {\n        \n        auto cmp = [](const vector<int>& l, const vector<int>& r) {\n            return l[1] > r[1];\n        };\n        \n        sort(boxTypes.begin(), boxTypes.end(), cmp);\n        \n        int ans = 0;\n        \n        for (int i = 0; i < boxTypes.size(); i++) {\n            \n            if (truckSize <= 0) {\n                break;\n            }\n            \n            int num = boxTypes[i][0];\n            int units = boxTypes[i][1];\n            \n            ans += min(num, truckSize) * units;\n            truckSize = max(0, truckSize - num);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1701-1710/Maximum XOR With an Element From Array.cpp",
    "content": "class Solution {\n    \n    class TreeNode {\n    public:\n        TreeNode* next[2];\n        TreeNode () {next[0] = nullptr; next[1] = nullptr;};\n    };\n    TreeNode* buildTree(vector<int>& nums) {\n        TreeNode* root = new TreeNode(), *cur;\n        int n = nums.size();\n        for (int i = 0; i < n; i++) {\n            int num = nums[i];\n            cur = root;\n            for (int j = 31; j >= 0; j--) {\n                int index = ((num >> j) & 1);\n                if (cur->next[index] == nullptr)\n                    cur->next[index] = new TreeNode();\n                cur = cur->next[index];\n            }\n        }\n        return root;\n    }\n    \n    int dfs(TreeNode* root, int x, int limit, int value, int height) {\n        if (value > limit) return -1;\n        \n        if (height == -1) return x^value;\n        \n        int bit_x = (x >> height) & 1;\n        \n        if (root->next[1-bit_x] != nullptr) {\n            int v = dfs(root->next[1-bit_x], x, limit, (value | ((1-bit_x) << height)), height-1);\n            if (v >= 0) return v;\n        }\n        if (root->next[bit_x] != nullptr) {\n            int v = dfs(root->next[bit_x], x, limit, (value | (bit_x << height)), height-1);\n            if (v >= 0) return v;\n        }\n        \n        return -1;\n    }\n    \npublic:\n    vector<int> maximizeXor(vector<int>& nums, vector<vector<int>>& queries) {\n        vector<int> ans;\n        TreeNode* root = buildTree(nums);\n        \n        for (const vector<int>& query : queries) {            \n            int tmp = dfs(root, query[0], query[1], 0, 31);\n            ans.push_back(tmp);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1701-1710/Where Will the Ball Fall.cpp",
    "content": "class Solution {\n    \npublic:\n    vector<int> findBall(vector<vector<int>>& grid) {\n        vector<int> ans;\n        \n        int m = grid.size();\n        int n = grid.front().size();\n        \n        for (int i = 0; i < n; i++) {\n            int row = 0;\n            int col = i;\n            \n            while(row < m) {\n                if (grid[row][col] == 1) {\n                    if (col == n-1 || grid[row][col+1] == -1) break;\n                    col++;\n                } else {\n                    if (col == 0 || grid[row][col-1] == 1) break;\n                    col--;\n                }\n                row++;\n            }\n            \n            ans.push_back(row == m ? col : -1);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1711-1720/Count Good Meals.cpp",
    "content": "class Solution {\npublic:\n    int countPairs(vector<int>& deliciousness) {\n        \n        vector<int> delicious_vec;\n        int base = 1;\n        for (int i = 0; i <= 21; i++) {\n            delicious_vec.push_back(base);\n            base *= 2;\n        }\n        reverse(delicious_vec.begin(), delicious_vec.end());\n        \n        unordered_map<int, int> mymap;\n        long answer = 0;\n        for (int d : deliciousness) {\n            \n            for (int sum : delicious_vec) {\n                \n                int target = sum - d;\n                if (target < 0) break;\n                answer += mymap[target];\n            }\n            \n            mymap[d]++;\n        }\n        \n        long mod = 1e9+7;\n        answer = answer % mod;\n        return answer;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1711-1720/Decode XORed Array.cpp",
    "content": "class Solution {\npublic:\n    vector<int> decode(vector<int>& encoded, int first) {\n        vector<int> ans;\n        ans.push_back(first);\n        \n        for (int i = 0; i < encoded.size(); i++) {\n            ans.push_back(ans[i] ^ encoded[i]);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1711-1720/Minimum Operations to Make a Subsequence.cpp",
    "content": "class Solution {\n    \n    int lengthOfLIS(vector<int>& nums) {\n        vector<int> res;\n        for(int i=0; i<nums.size(); i++) {\n            auto it = std::lower_bound(res.begin(), res.end(), nums[i]);\n            if(it == res.end()) res.push_back(nums[i]);\n            else *it = nums[i];\n        }\n        return res.size();\n    }\n    \npublic:\n    int minOperations(vector<int>& target, vector<int>& arr) {\n        unordered_map<int, int> mymap;\n        int base = 1;\n        for (int t : target) {\n            mymap[t] = base;\n            base++;\n        }\n        \n        vector<int> new_arr;\n        for (int e : arr) {\n            if (mymap.count(e) > 0) {\n                new_arr.push_back(mymap[e]);\n            }\n        }\n        \n        return target.size() - lengthOfLIS(new_arr);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1711-1720/Ways to Split Array Into Three Subarrays.cpp",
    "content": "class Solution {\npublic:\n    int waysToSplit(vector<int>& nums) {\n        int n = nums.size();\n        vector<int> sums;\n        int sum = 0;\n        for (int num : nums) {\n            sum += num;\n            sums.push_back(sum);\n        }\n        \n        long ans = 0;\n        long mod = 1e9+7;\n        int sum_left = 0;\n        int j = 0;\n        int k = 0;\n        for (int i = 0; i < n; i++) {\n            sum_left += nums[i];\n            \n            if (sum_left*3 > sum) break;\n            \n            j = max(j, i+1);\n            while (j < n-1 && ((sums[j] - sums[i]) < sum_left)) j++;\n            \n            int sum_remain = sum - sum_left;\n            k = max(k, j);\n            while (k < n-1) {\n                int l = sums[k] - sums[i];\n                int r = sum_remain - l;\n                if (l > r) {\n                    break;\n                }\n                else k++;\n            }\n            \n            ans += (k - j);\n            \n        }\n        \n        return ans % mod;\n    }\n};\n\n\nclass Solution {\npublic:\n    int waysToSplit(vector<int>& nums) {\n        int n = nums.size();\n        vector<int> sums;\n        int sum = 0;\n        for (int num : nums) {\n            sum += num;\n            sums.push_back(sum);\n        }\n        \n        long ans = 0;\n        long mod = 1e9+7;\n        int sum_left = 0;\n        for (int left = 0; left < n; left++) {\n            sum_left += nums[left];\n            \n            auto it1 = lower_bound(sums.begin()+left+1, sums.end(), 2*sum_left);\n            if (it1 == sums.end()) break;\n            \n            int target = (sum - sum_left )/2 + sum_left;\n            auto it2 = upper_bound(it1, --sums.end(), target);\n            if (it2 == sums.end()) break;\n            \n            ans += (it2 - it1);\n        }\n        \n        return ans % mod;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1721-1730/Find Minimum Time to Finish All Jobs.cpp",
    "content": "class Solution {\n    \n    int ans;\n    \n    void dfs(vector<int>& jobs, int k, vector<int>& workers, int curr) {\n        if (curr == jobs.size()) {\n            ans = min(ans, *max_element(workers.begin(), workers.end()));\n            return;\n        }\n            \n        set<int> seen;\n        for (int i = 0; i < k; i++) {\n            if (seen.count(workers[i]) > 0) continue;\n            if (workers[i] + jobs[curr] >= ans) continue;\n            seen.insert(workers[i]);\n            \n            workers[i] += jobs[curr];\n            dfs(jobs, k, workers, curr+1);\n            workers[i] -= jobs[curr];\n        }\n    }\n    \npublic:\n    int minimumTimeRequired(vector<int>& jobs, int k) {\n        int n = jobs.size();\n        vector<int> workers(k, 0);\n        ans = INT_MAX;\n        \n        dfs(jobs, k, workers, 0);\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1721-1730/Largest Submatrix With Rearrangements.cpp",
    "content": "class Solution {\npublic:\n    int largestSubmatrix(vector<vector<int>>& matrix) {\n        int m = matrix.size();\n        int n = matrix[0].size();\n        \n        for (int j = 0; j < n; j++) {\n            for (int i = m-1; i >= 0; i--) {\n                if (matrix[i][j] == 1 && i != (m-1)) {\n                    matrix[i][j] = 1 + matrix[i+1][j];\n                }\n            }\n        }\n        \n        int ans = 0;\n        for (int i = 0; i < m; i++) {\n            sort(matrix[i].begin(), matrix[i].end(), std::greater<int>());\n            \n            for (int w = 0; w < matrix[i].size(); w++) {\n                if (matrix[i][w] == 0) break;\n                ans = max(ans, (w+1) * matrix[i][w]);\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1721-1730/Minimize Hamming Distance After Swap Operations.cpp",
    "content": "class UF {\n    \nprivate:\n    vector<int> parent;\n    vector<int> rank;\n    int count;\n    int N;\n    \n    bool validate(int p) {\n        return (p >= 0 && p < N);\n    }\n    \npublic:\n    \n    UF(int N) : parent(N), rank(N, 0), N(N), count(N) {\n        for (int i = 0; i < N; i++) {\n            parent[i] = i;\n        }\n    }\n    \n    int find(int p) {\n        if (!validate(p)) return -1;\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];    // path compression by halving\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    int getCount() const {\n        return count;\n    }\n    \n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    void Union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rootP == rootQ) return;\n        \n        // make root of smaller rank point to root of larger rank\n        if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;\n        else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;\n        else {\n            parent[rootQ] = rootP;\n            rank[rootP]++;\n        }\n        count--;\n    }\n    \n    ~UF() {}\n};\n\nclass Solution {\npublic:\n    int minimumHammingDistance(vector<int>& source, vector<int>& target, vector<vector<int>>& allowedSwaps) {\n        int n = source.size();\n        int ans = n;\n        \n        UF uf(n);\n        for (const vector<int>& allowedSwap : allowedSwaps) {\n            uf.Union(allowedSwap[0], allowedSwap[1]);\n        }\n        \n        unordered_map<int, vector<int>> groups;\n        for (int i = 0; i < n; i++) {\n            int parent = uf.find(i);\n            groups[parent].push_back(i);\n        }\n        \n        unordered_map<int, bool> visited;\n        for (int i = 0; i < n; i++) {\n            int parent = uf.find(i);\n            if (visited[parent]) {\n                continue;\n            }\n            \n            vector<int> group = groups[parent];\n            unordered_map<int, int> mymap;\n            \n            for (int index : group) {\n                mymap[target[index]]++;\n            }\n            for (int index : group) {\n                if (mymap[source[index]] > 0) {\n                    mymap[source[index]]--;\n                    ans--;\n                }\n            }\n            \n            visited[parent] = true;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1721-1730/Number Of Rectangles That Can Form The Largest Square.cpp",
    "content": "class Solution {\npublic:\n    int countGoodRectangles(vector<vector<int>>& rectangles) {\n        unordered_map<int, int> mymap;\n        \n        int max_square = 0;\n        for (const vector<int>& rec : rectangles) {\n            int v = *min_element(rec.begin(), rec.end());\n            max_square = max(max_square, v);\n            mymap[v]++;\n        }\n        \n        return mymap[max_square];\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1721-1730/Swapping Nodes in a Linked List.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode() : val(0), next(nullptr) {}\n *     ListNode(int x) : val(x), next(nullptr) {}\n *     ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* swapNodes(ListNode* head, int k) {\n        ListNode* l1 = head, *l2 = head;\n        \n        for (int i = 1; i < k; i++) {\n            l1 = l1->next;\n        }\n        \n        int len = 0;\n        while (l2 != nullptr) {\n            len++;\n            l2 = l2->next;\n        }\n        l2 = head;\n        \n        for (int i = 1; i <= (len - k); i++) {\n            l2 = l2->next;\n        }\n        \n        swap(l1->val, l2->val);\n        \n        return head;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1721-1730/Tuple with Same Product.cpp",
    "content": "class Solution {\npublic:\n    int tupleSameProduct(vector<int>& nums) {\n        \n        unordered_map<int, int> mymap;\n        \n        for (int i = 0; i < nums.size(); i++) {\n            for (int j = i+1; j < nums.size(); j++) {\n                mymap[nums[i] * nums[j]]++;\n            }\n        }\n        \n        int ans = 0;\n        for (const auto& pair : mymap) {\n            if (pair.second > 1) {\n                int v = pair.second;\n                int tmp = v * (v-1) * 4;\n                ans += tmp;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1731-1740/Building Boxes.cpp",
    "content": "class Solution {\npublic:\n    int minimumBoxes(int n) {\n        int ans = 0;\n        int tmp = 0;\n        \n        for (int i = 1;;i++) {\n            \n            tmp += i;\n            \n            if (n <= tmp) {\n                int k = 1;\n                while (n > 0) {\n                    n -= k;\n                    ans++;\n                    k++;\n                }\n                break;\n            }\n            \n            n -= tmp;\n            ans += i;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1751-1760/Closest Subsequence Sum.cpp",
    "content": "class Solution {\n    \npublic:\n    int maxValue(vector<vector<int>>& events, int k) {\n        auto cmp = [](const vector<int>& lhs, const vector<int>& rhs) {\n            return lhs[1] < rhs[1];\n        };\n        sort(events.begin(), events.end(), cmp);\n        \n        int n = events.size();\n        vector<vector<int>> dp(n+1, vector<int>(k+1, 0));\n        for (int i = 1; i <= n; i++) {\n            int non_overlap_index = 0;\n            for (int l = i - 1; l >= 1; l--) {\n                if (events[l-1][1] < events[i-1][0]) {\n                    non_overlap_index = l;\n                    break;\n                }\n            }\n            for (int j = 1; j <= k; j++) {\n                dp[i][j] = max(dp[non_overlap_index][j-1] + events[i-1][2], dp[i-1][j]);\n            }\n        }\n        return dp[n][k];\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1751-1760/Largest Merge Of Two Strings.cpp",
    "content": "class Solution {\n    \npublic:\n    string largestMerge(string word1, string word2) {\n        string ans;\n        int i = 0, j = 0;\n        while(i < word1.size() && j < word2.size()) {\n            if(word1.substr(i) > word2.substr(j)) {\n                ans.push_back(word1[i]);\n                i++;\n            } else {\n                ans.push_back(word2[j]);\n                j++;\n            }\n        }\n        \n        if(i == word1.size()) {\n            ans += word2.substr(j);\n        } else if(j == word2.size()) {\n            ans += word1.substr(i);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1751-1760/Maximum Number of Events That Can Be Attended II.cpp",
    "content": "class Solution {\n    \npublic:\n    int maxValue(vector<vector<int>>& events, int k) {\n        auto cmp = [](const vector<int>& lhs, const vector<int>& rhs) {\n            return lhs[1] < rhs[1];\n        };\n        sort(events.begin(), events.end(), cmp);\n        \n        int n = events.size();\n        vector<vector<int>> dp(n+1, vector<int>(k+1, 0));\n        for (int i = 1; i <= n; i++) {\n            int non_overlap_index = 0;\n            for (int l = i - 1; l >= 1; l--) {\n                if (events[l-1][1] < events[i-1][0]) {\n                    non_overlap_index = l;\n                    break;\n                }\n            }\n            for (int j = 1; j <= k; j++) {\n                dp[i][j] = max(dp[non_overlap_index][j-1] + events[i-1][2], dp[i-1][j]);\n            }\n        }\n        return dp[n][k];\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1751-1760/Minimum Limit of Balls in a Bag.cpp",
    "content": "class Solution {\n    \n    bool check(const vector<int>& nums, int maxOperations, int penalty) {\n        int ops = 0;\n        for (int num : nums) {\n            ops += (num-1) / penalty;\n        }\n        return ops <= maxOperations;\n    }\n    \npublic:\n    int minimumSize(vector<int>& nums, int maxOperations) {\n        int left = 1, right = *max_element(nums.begin(), nums.end());\n        \n        while (left < right) {\n            int mid = (left + right) / 2;\n            \n            bool can_do_it = check(nums, maxOperations, mid);\n            \n            if (can_do_it) {\n                right = mid;\n            } else {\n                left = mid + 1;\n            }\n        }\n        \n        return left;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1761-1770/Form Array by Concatenating Subarrays of Another Array.cpp",
    "content": "class Solution {\n    \n    int MatchGroup(const vector<int>& group, const vector<int>& nums,  int index) {\n        for (int start = index; start <= nums.size() - group.size(); start++) {\n            bool match = true;\n            for (int l = 0; l < group.size(); l++) {\n                if (group[l] != nums[start+l]) {\n                    match = false;\n                    break;\n                }\n            }\n            \n            if (match) {\n                return start + group.size();\n            }\n        }\n        \n        return -1;\n    }\n    \npublic:\n    bool canChoose(vector<vector<int>>& groups, vector<int>& nums) {\n        int index = 0;\n        for (const vector<int>& group : groups) {\n            index = MatchGroup(group, nums, index);\n            if (index < 0) {\n                return false;\n            }\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1761-1770/Map of Highest Peak.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> highestPeak(vector<vector<int>>& isWater) {\n        int m = isWater.size();\n        int n = isWater.front().size();\n        vector<vector<int>> result(m, vector<int>(n, -1));\n        \n        queue<pair<int, int>> myqueue;\n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                if (isWater[i][j] == 1) {\n                    myqueue.push({i, j});\n                    result[i][j] = 0;\n                }\n            }\n        }\n        \n        int cur_height = 0;\n        while (!myqueue.empty()) {\n            int total = myqueue.size();\n            \n            for (int k = 0; k < total; k++) {\n                pair<int, int> pos = myqueue.front();\n                myqueue.pop();\n                \n                pair<int, int> directions[4] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n                for (pair<int, int> direction : directions) {\n                    int new_pos_x = pos.first + direction.first;\n                    int new_pos_y = pos.second + direction.second;\n                    if (new_pos_x < 0 || new_pos_x >= m|| new_pos_y < 0 || new_pos_y >= n\n                        || result[new_pos_x][new_pos_y] != -1) {\n                        continue;\n                    }\n                    myqueue.push({new_pos_x, new_pos_y});\n                    result[new_pos_x][new_pos_y] = cur_height + 1;\n                }\n            }\n            \n            cur_height++;\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1761-1770/Maximum Score from Performing Multiplication Operations.cpp",
    "content": "class Solution {\npublic:\n    int maximumScore(vector<int>& nums, vector<int>& multipliers) {\n        int n = nums.size();\n        int m = multipliers.size();\n        vector<vector<int>> dp(m+1, vector<int>(m+1, 0));\n        \n        int score = INT_MIN;\n        for (int k = 1; k <= m; k++) {\n            for (int l = 0; l <= k; l++) {\n                int pick_left = (l == 0 ? INT_MIN : dp[l-1][k-l] + multipliers[k-1] * nums[l-1]);\n                int pick_right = (l == k ? INT_MIN : dp[l][k-l-1] + multipliers[k-1] * nums[n-k+l]);\n                dp[l][k-l] = max(pick_left, pick_right);\n\n                if (k == m) {\n                    score = max(score, dp[l][k-l]);\n                }\n            }\n        }\n        \n        return score;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1761-1770/Minimum Degree of a Connected Trio in a Graph.cpp",
    "content": "class Solution {\npublic:\n    int minTrioDegree(int n, vector<vector<int>>& edges) {\n        vector<unordered_set<int>> graph(n+1);\n        \n        for (const vector<int>& edge : edges) {\n            graph[edge[0]].insert(edge[1]);\n            graph[edge[1]].insert(edge[0]);\n        }\n        \n        int ans = INT_MAX;\n        for (int i = 1; i <= n; i++) {\n            const unordered_set<int>& neighbors = graph[i];\n            int tmp_a = graph[i].size() - 2;\n            if (tmp_a >= ans) {\n                continue;\n            }\n            for (int b : neighbors) {\n                int tmp_b = tmp_a + graph[b].size() - 2;\n                if (b < i || tmp_b >= ans) {\n                    continue;\n                }\n                for (int c : graph[b]) {\n                    if (neighbors.count(c) > 0) {\n                        ans = min(ans, tmp_b + (int)graph[c].size() - 2);\n                    }\n                } \n            }\n        }\n        \n        return ans == INT_MAX? -1 : ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1761-1770/Tree of Coprimes.cpp",
    "content": "class Solution {\n    \n    void dfs(int node, const vector<int>& nums, const vector<vector<int>>& graph,\n             vector<int>& result,\n             map<int, pair<int, int>>& ancestors /*value, {node, depth}*/,\n             int depth, int parent) {\n        int closest_ancestor = -1;\n        int distance = INT_MAX;\n        for (const auto& pair : ancestors) {\n            if (__gcd(nums[node], pair.first) == 1 && (depth - pair.second.second) < distance) {\n                distance = depth - pair.second.second;\n                closest_ancestor = pair.second.first;\n            }\n        }\n        result[node] = closest_ancestor;\n        \n        bool has_original_node = (ancestors.count(nums[node])) > 0;\n        pair<int, int> original_node = ancestors[nums[node]];\n        ancestors[nums[node]] = {node, depth};\n        for (int neighbor : graph[node]) {\n            if (neighbor == parent) {\n                continue;\n            }\n            dfs(neighbor, nums, graph, result, ancestors, depth + 1, node);\n        }\n        ancestors.erase(nums[node]);\n        if (has_original_node) {\n            ancestors[nums[node]] = original_node;\n        }\n    }\n    \npublic:\n    vector<int> getCoprimes(vector<int>& nums, vector<vector<int>>& edges) {\n        int n = nums.size();\n        vector<vector<int>> graph(n);\n        for (const vector<int>& edge : edges) {\n            graph[edge[0]].push_back(edge[1]);\n            graph[edge[1]].push_back(edge[0]);\n        }\n        \n        map<int, pair<int, int>> ancestors;\n        vector<int> result(n, -1);\n        dfs(/*node=*/0, nums, graph, result, ancestors, /*depth=*/0, /*parent=*/-1);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1771-1780/Car Fleet II.cpp",
    "content": "class Solution {\npublic:\n    vector<double> getCollisionTimes(vector<vector<int>>& cars) {\n        vector<double> result(cars.size(), -1.0);\n        stack<int> mystack;\n        \n        for (int i = cars.size() - 1; i >= 0; i--) {\n            // We don't need faster cars behind current car.\n            while (!mystack.empty() && cars[i][1] <= cars[mystack.top()][1]) {\n                mystack.pop();\n            }\n            \n            while (!mystack.empty()) {\n                int candidate = mystack.top();\n                double current_time = 1.0 * (cars[candidate][0] - cars[i][0]) / (cars[i][1] - cars[candidate][1]);\n                if (current_time <= result[candidate] || result[candidate] < 0) {\n                    result[i] = current_time;\n                    break;\n                }\n                // This car will collide with cars after candidate.\n                mystack.pop();\n            }\n            \n            mystack.push(i);\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1771-1780/Check if Number is a Sum of Powers of Three.cpp",
    "content": "class Solution {\npublic:\n    bool checkPowersOfThree(int n) {\n        int tmp = 3;\n        while (tmp < n) {\n            tmp *= 3;\n        }\n        \n        while (tmp > 0) {\n            if (n >= tmp) {\n                n -= tmp;\n            }\n            tmp = tmp/3;\n        }\n        \n        return n == 0;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1771-1780/Closest Dessert Cost.cpp",
    "content": "class Solution {\npublic:\n    int closestCost(vector<int>& baseCosts, vector<int>& toppingCosts, int target) {\n        bool table[20010] = {false};\n        int ans = -999999;\n        for (int base : baseCosts) {\n            table[base] = true;\n        }\n        \n        for (int cost : toppingCosts) {\n            for (int k = 1; k <= 2; k++) {\n                for (int v = 20000; v >= 0; v--) {\n                    if (v - cost >= 0 && table[v - cost] == true) {\n                        table[v] = true;\n                    }\n                }\n            }\n        }\n        \n        for (int i = 1; i <= 20001; i++) {\n            if (table[i] == true && abs(i - target) < abs(ans - target)) {\n                ans = i;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1771-1780/Equal Sum Arrays With Minimum Number of Operations.cpp",
    "content": "class Solution {\n    \n    int process(int* table1, int* table2, int diff) {\n        int ans = 0;\n        for (int k = 1; k <= 5 && diff > 0; k++) {\n            int contrib = 6 - k;\n            \n            while (table2[k] > 0 && diff > 0) {\n                diff -= contrib;\n                ans++;\n                table2[k]--;\n            }\n            while (table1[7 - k] > 0 && diff > 0) {\n                diff -= contrib;\n                ans++;\n                table1[7 - k]--;\n            }\n        }\n        \n        return ans;\n    }\n    \npublic:\n    int minOperations(vector<int>& nums1, vector<int>& nums2) {\n        if (6 * nums1.size() < nums2.size()) return -1;\n        if (6 * nums2.size() < nums1.size()) return -1;\n        int sum1 = 0;\n        int table1[7] = {0};\n        int sum2 = 0;\n        int table2[7] = {0};\n        \n        for (int num : nums1) {\n            sum1 += num;\n            table1[num]++;\n        }\n        for (int num : nums2) {\n            sum2 += num;\n            table2[num]++;\n        }\n        \n        if (sum1 == sum2) return 0;\n        else if (sum1 > sum2) return process(table1, table2, sum1 - sum2);\n        else return process(table2, table1, sum2 - sum1);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1771-1780/Find Nearest Point That Has the Same X or Y Coordinate.cpp",
    "content": "class Solution {\npublic:\n    int nearestValidPoint(int x, int y, vector<vector<int>>& points) {\n        int index = -1;\n        int distance = INT_MAX;\n        \n        for (int i = 0; i < points.size(); i++) {\n            if (x == points[i][0] || y == points[i][1]) {\n                int current_dis = abs(x - points[i][0]) + abs(y - points[i][1]);\n                if (current_dis < distance) {\n                    distance = current_dis;\n                    index = i;\n                }\n            }\n        }\n        \n        return index;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1771-1780/Maximize Palindrome Length From Subsequences.cpp",
    "content": "class Solution {\npublic:\n    int longestPalindrome(string word1, string word2) {\n        string s = word1 + word2;\n        int n = s.size();\n        vector<vector<int>> dp(n, vector<int>(n,0));\n        \n        int res = 0;\n        for (int i = n - 1; i >= 0; i--) {\n            dp[i][i] = 1;\n            for (int j = i + 1; j < n; j++) {\n                if (s[i]==s[j]) {\n                    dp[i][j] = dp[i+1][j-1] + 2;\n                    if (i < word1.length() && j >= word1.length()) {\n                        res = max(res, dp[i][j]);\n                    }\n                } else {\n                    dp[i][j] = max(dp[i+1][j], dp[i][j-1]);\n                }\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1771-1780/Shortest Path in a Hidden Grid.cpp",
    "content": "/**\n * // This is the GridMaster's API interface.\n * // You should not implement it, or speculate about its implementation\n * class GridMaster {\n *   public:\n *     bool canMove(char direction);\n *     void move(char direction);\n *     boolean isTarget();\n * };\n */\n\nclass Solution {\npublic:\n    // 0 is blocked, 1 is empty, 2 is target\n    void ConstructGrid(vector<vector<int>>& grid, GridMaster &master, int row, int col, const map<char, pair<int, int>>& directions) {\n        grid[row][col] = 1;\n        if (master.isTarget()) {\n            grid[row][col] = 2;\n        }\n        \n        for (const auto& direction : directions) {\n            int new_row = row + direction.second.first;\n            int new_col = col + direction.second.second;\n            if (grid[new_row][new_col] != -1) {\n                continue;\n            }\n            if (master.canMove(direction.first)) {\n                master.move(direction.first);\n                ConstructGrid(grid, master, new_row, new_col, directions);\n                if (direction.first == 'U') master.move('D');\n                else if (direction.first == 'D') master.move('U');\n                else if (direction.first == 'L') master.move('R');\n                else master.move('L');\n            } else {\n                grid[new_row][new_col] = 0;\n            }\n        }\n    }\n    \n    int findShortestPath(GridMaster &master) {\n        map<char, pair<int, int>> directions = {\n            {'U', {0, 1}},\n            {'D', {0, -1}},\n            {'L', {-1, 0}},\n            {'R', {1, 0}},\n        };\n        \n        vector<vector<int>> grid(1001, vector<int>(1001, -1));\n        ConstructGrid(grid, master, 501, 501, directions);\n        \n        queue<pair<int, int>> myqueue;\n        myqueue.push({501, 501});\n        grid[501][501] = 0;\n        \n        int distance = 1;\n        while (!myqueue.empty()) {\n            int queue_size = myqueue.size();\n            for (int k = 0; k < queue_size; k++) {\n                pair<int, int> cur = myqueue.front();\n                myqueue.pop();\n                \n                for (const auto& direction : directions) {\n                    int new_row = cur.first + direction.second.first;\n                    int new_col = cur.second + direction.second.second;\n                    if (grid[new_row][new_col] == 2) {\n                        return distance;\n                    }\n                    if (grid[new_row][new_col] <= 0) {\n                        continue;\n                    }\n                    // Mark as 'visited'.\n                    grid[new_row][new_col] = 0;\n                    myqueue.push({new_row, new_col});\n                }\n            }\n            \n            distance++;\n        }\n        \n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1781-1790/Check if Binary String Has at Most One Segment of Ones.cpp",
    "content": "class Solution {\npublic:\n    bool checkOnesSegment(string s) {\n        return s.find(\"01\") == string::npos;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1781-1790/Check if One String Swap Can Make Strings Equal.cpp",
    "content": "class Solution {\npublic:\n    bool areAlmostEqual(string s1, string s2) {\n        int idx1 = -1, idx2 = -1;\n        for (int i = 0; i < s1.length(); i++) {\n            if (s1[i] != s2[i]) {\n                if (idx1 == -1) {\n                    idx1 = i;\n                } else if (idx2 == -1) {\n                    idx2 = i;\n                } else {\n                    return false;\n                }\n            }\n        }\n        \n        if (idx1 < 0 && idx2 < 0) return true;\n        if (idx2 < 0) return false;\n        if (s1[idx1] == s2[idx2] && s1[idx2] == s2[idx1]) return true;\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1781-1790/Count Pairs Of Nodes.cpp",
    "content": "class Solution {\npublic:\n    vector<int> countPairs(int n, vector<vector<int>>& edges, vector<int>& queries) {\n        vector<int> sizes(n+1, 0);\n        vector<unordered_map<int, int>> graph(n + 1);\n        for (const vector<int>& edge : edges) {\n            graph[edge[0]][edge[1]]++;\n            graph[edge[1]][edge[0]]++;\n            sizes[edge[0]]++;\n            sizes[edge[1]]++;\n        }\n        \n        vector<int> prefix_sum(100001, 0);\n        for (int i = 1; i < sizes.size(); i++) {\n            prefix_sum[sizes[i]]++;\n        }\n        for (int i = 100000; i >= 1; i--) {\n            prefix_sum[i-1] += prefix_sum[i];\n        }\n        \n        vector<int> answer;\n        for (int query : queries) {\n            int total = 0;\n            \n            for (int i = 1; i <= n; i++) {\n                const unordered_map<int, int>& mymap = graph[i];\n                \n                int target = query - sizes[i];\n                int current = 0;\n                for (const auto& it : mymap) {\n                    int neighbor = it.first;\n                    if (sizes[neighbor] > target) {\n                        current--;\n                    }\n                    int count = sizes[i] + sizes[neighbor] - it.second; \n                    if (count > query) {\n                        current++;\n                    }\n                }\n                if (sizes[i] > target) {\n                    current--;\n                }\n                current += prefix_sum[target < 0 ? 0 : target+1];\n                total += current;\n            }\n            answer.push_back(total / 2);\n        }\n        \n        return answer;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1781-1790/Make the XOR of All Segments Equal to Zero.cpp",
    "content": "class Solution {\npublic:\n    int minChanges(vector<int>& nums, int k) {\n        int n = nums.size();\n        vector<vector<int>> freq(k, vector<int>(1025, 0));\n        for (int i = 0; i < n; i++) {\n            freq[i%k][nums[i]]++;\n        }\n        \n        vector<vector<int>> dp(k + 1, vector<int>(1025, 2001));\n        dp[0][0] = 0;\n        \n        for (int i = 0; i < k; i++) {\n            int total = (n + k - i - 1) / k;\n            int previous_minimum_changes = *min_element(dp[i].begin(), dp[i].end());\n            \n            for (int target = 0; target <= 1024; target++) {\n                dp[i+1][target] = total + previous_minimum_changes;\n                \n                for (int index = i; index < n; index += k) {\n                    int picked = nums[index];\n                    int previous_target = picked ^ target;\n                    if (previous_target > 1024) {\n                        continue;\n                    }\n                    dp[i+1][target] = min(dp[i+1][target],\n                                          dp[i][previous_target] + total - freq[i][picked]);\n                }\n            }\n        }\n        \n        return dp[k][0];\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1781-1790/Maximize the Beauty of the Garden.cpp",
    "content": "class Solution {\npublic:\n    int maximumBeauty(vector<int>& flowers) {\n        unordered_map<int, int> mymap;\n        int res = INT_MIN;\n        int sum = 0;\n        for (int beauty : flowers) {\n            if (mymap.count(beauty) > 0) {\n                res = max(res, sum - mymap[beauty] + 2 * beauty);\n            }\n            \n            if (beauty > 0) {\n                sum += beauty;\n            }\n            \n            if (mymap.count(beauty) == 0) {\n                mymap[beauty] = sum;\n            }\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1781-1790/Minimum Elements to Add to Form a Given Sum.cpp",
    "content": "class Solution {\npublic:\n    int minElements(vector<int>& nums, int limit, int goal) {\n        long sum = 0;\n        for (int num : nums) {\n            sum += num;\n        }\n        return (abs(goal - sum) + limit - 1) / limit;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1781-1790/Number of Restricted Paths From First to Last Node.cpp",
    "content": "class Solution {\npublic:\n    \n    void bfs(int n, const vector<vector<pair<int, int>>>& graph, vector<int>& distances, vector<int>& closest_nodes) {\n        auto cmp = [](const pair<int, int> &a, const pair<int, int> &b) {\n            return a.second > b.second;\n        };\n        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp);\n        vector<bool> visited(n+1, false);\n        pq.push({n, 0});\n        \n        while (!pq.empty()) {\n            pair<int, int> current = pq.top();\n            pq.pop();\n            int node = current.first;\n            int dis = current.second;\n            if (visited[node] == true) {\n                continue;\n            }\n            distances[node] = dis;\n            visited[node] = true;\n            closest_nodes.push_back(node);\n            \n            for (pair<int, int> neighbor : graph[node]) {\n                int neighbor_node = neighbor.first;\n                if (visited[neighbor_node] == false) {\n                    pq.push({neighbor_node, dis + neighbor.second});\n                }\n            }\n        }\n    }\n    \n    int countRestrictedPaths(int n, vector<vector<int>>& edges) {\n        vector<vector<pair<int, int>>> graph(n+1);\n        for (const vector<int>& edge : edges) {\n            graph[edge[0]].push_back({edge[1], edge[2]});\n            graph[edge[1]].push_back({edge[0], edge[2]});\n        }\n        \n        vector<int> distances(n + 1, 0);\n        vector<int> closest_nodes;\n        bfs(n, graph, distances, closest_nodes);\n        \n        vector<long> dp(n+1, 0);\n        dp[1] = 1;\n        int mod = 1e9+7;\n        for (int i = closest_nodes.size() - 1; i >= 0; i--) {\n            int node = closest_nodes[i];\n            for (pair<int, int> neighbor : graph[node]) {\n                int neighbor_node = neighbor.first;\n                if (distances[neighbor_node] < distances[node]) {\n                    dp[neighbor_node] += dp[node];\n                    dp[neighbor_node] %= mod;\n                }\n            }\n        }\n        \n        return dp[n];\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1781-1790/Sum of Beauty of All Substrings.cpp",
    "content": "class Solution {\npublic:\n    int beautySum(string s) {\n        int answer = 0;\n        \n        for (int i = 0; i < s.length(); i++) {\n            int array[26] = {0};\n            \n            for (int j = i; j < s.length(); j++) {\n                char ch = s[j];\n                array[ch-'a']++;\n                \n                int maximum = INT_MIN;\n                int minimum = INT_MAX;\n                int diff_chars = 0;\n                for (int k = 0; k < 26; k++) {\n                    maximum = max(maximum, array[k]);\n                    if (array[k] > 0) {\n                        minimum = min(minimum, array[k]);\n                        diff_chars++;\n                    }\n                }\n                \n                if (diff_chars >= 2) {\n                    answer += (maximum - minimum);\n                }\n            }\n        }\n        \n        return answer;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1791-1800/Count Pairs of Equal Substrings With Minimum Difference.cpp",
    "content": "class Solution {\npublic:\n    int countQuadruples(string firstString, string secondString) {\n        unordered_map<char, int> last_occurence;\n        for (int i = 0; i < secondString.length(); i++) {\n            last_occurence[secondString[i]] = i;\n        }\n        \n        int minimum_j_minus_a = INT_MAX;\n        int cnt = 0;\n        for (int i = 0; i < firstString.length(); i++) {\n            char ch = firstString[i];\n            if (last_occurence.count(ch) > 0) {\n                int j_minus_a = i - last_occurence[ch];\n                if (j_minus_a < minimum_j_minus_a) {\n                    minimum_j_minus_a = j_minus_a;\n                    cnt = 1;\n                } else if (j_minus_a == minimum_j_minus_a) {\n                    cnt++;\n                }\n            }\n        }\n        \n        return cnt;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1791-1800/Design Authentication Manager.cpp",
    "content": "class AuthenticationManager {\n    int ttl = 0;\n    unordered_map<string, int> tokens;\npublic:\n    AuthenticationManager(int timeToLive) {\n        ttl = timeToLive;\n    }\n    \n    void generate(string tokenId, int currentTime) {\n        tokens[tokenId] = currentTime + ttl;\n    }\n    \n    void renew(string tokenId, int currentTime) {\n        auto it = tokens.find(tokenId);\n        if (it == tokens.end()) {\n            return;\n        }\n        if (it->second <= currentTime) {\n            tokens.erase(it);\n        } else {\n            it->second = currentTime + ttl;\n        }\n    }\n    \n    int countUnexpiredTokens(int currentTime) {\n        auto it = tokens.begin();\n        while (it != tokens.end()) {\n            if (it->second <= currentTime) {\n                it = tokens.erase(it);\n            } else {\n                it++;\n            }\n        }\n        return tokens.size();\n    }\n};\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager* obj = new AuthenticationManager(timeToLive);\n * obj->generate(tokenId,currentTime);\n * obj->renew(tokenId,currentTime);\n * int param_3 = obj->countUnexpiredTokens(currentTime);\n */\n"
  },
  {
    "path": "cpp/1001-10000/1791-1800/Find Center of Star Graph.cpp",
    "content": "class Solution {\npublic:\n    int findCenter(vector<vector<int>>& edges) {\n        if (edges[0][0] == edges[1][0] || edges[0][0] == edges[1][1]) {\n            return edges[0][0];\n        } else {\n            return edges[0][1];\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1791-1800/Maximize Score After N Operations.cpp",
    "content": "class Solution {\n    int dfs(const vector<int>& nums, int round, int state, unordered_map<int, int>& cache) {\n        if (round > nums.size() / 2) {\n            return 0;\n        }\n        if (cache.count(state) > 0) {\n            return cache[state];\n        }\n        \n        int ans = 0;\n        for (int i = 0; i < nums.size(); i++) {\n            for (int j = i + 1; j < nums.size(); j++) {\n                int picked = (1 << i) | (1 << j);\n                if ((state & picked) == 0) {\n                    ans = max(ans, round * __gcd(nums[i], nums[j]) + dfs(nums, round + 1, state | picked, cache));\n                }\n            }\n        }\n\n        return cache[state] = ans;\n    }\npublic:\n    int maxScore(vector<int>& nums) {\n        unordered_map<int, int> cache;\n        return dfs(nums, /*round=*/1, /*state=*/0, cache);\n    }\n};\n\n"
  },
  {
    "path": "cpp/1001-10000/1791-1800/Maximum Ascending Subarray Sum.cpp",
    "content": "class Solution {\npublic:\n    int maxAscendingSum(vector<int>& nums) {\n        int ans = nums[0];\n        \n        int cur = nums[0];\n        for (int i = 1; i < nums.size(); i++) {\n            if (nums[i] > nums[i-1]) {\n                cur += nums[i];\n            } else {\n                cur = nums[i];\n            }\n            ans = max(ans, cur);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1791-1800/Maximum Average Pass Ratio.cpp",
    "content": "/*\n * Solution 1: Compute increase every time. It's a bit slow.\n */\nclass Solution {\npublic:\n    double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) {\n        auto cmp = [](const pair<int, int>& a, const pair<int, int>& b) {\n            double a_original = a.first * 1.0 / a.second;\n            double a_new = (a.first + 1) *1.0 / (a.second + 1);\n            double b_original = b.first * 1.0 / b.second;\n            double b_new = (b.first + 1) *1.0 / (b.second + 1);\n            return (a_new - a_original) < (b_new - b_original);\n        };\n        \n        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp);\n        for (vector<int>& myclass : classes) {\n            pq.push({myclass[0], myclass[1]});\n        }\n        \n        for (int i = 0; i < extraStudents; i++) {\n            pair<int, int> cur = pq.top();\n            pq.pop();\n            \n            cur.first++;\n            cur.second++;\n            \n            pq.push(cur);\n        }\n        \n        double sum = 0.0;\n        while (!pq.empty()) {\n            pair<int, int> cur = pq.top();\n            pq.pop();\n            sum += (1.0 * cur.first / cur.second);\n        }\n        \n        return sum / classes.size();\n    }\n};\n\n/*\n * Solution 2: Pre-compute increase.\n */\nclass Solution {\n    double GetIncrease(int dividend, int divisor) {\n        double original_value = dividend * 1.0 / divisor;\n        double new_value = (dividend + 1) * 1.0 / (divisor + 1);\n        return new_value - original_value;\n    }\npublic:\n    double maxAverageRatio(vector<vector<int>>& classes, int extraStudents) {\n        auto cmp = [](const pair<pair<int, int>, double>& a, const pair<pair<int, int>, double>& b) {\n            return a.second < b.second;\n        };\n        \n        priority_queue<pair<pair<int, int>, double>, vector<pair<pair<int, int>, double>>, decltype(cmp)> pq(cmp);\n        for (vector<int>& myclass : classes) {\n            pq.push({{myclass[0], myclass[1]}, GetIncrease(myclass[0], myclass[1])});\n        }\n        \n        for (int i = 0; i < extraStudents; i++) {\n            pair<pair<int, int>, double> cur = pq.top();\n            pq.pop();\n            \n            cur.first.first++;\n            cur.first.second++;\n            cur.second = GetIncrease(cur.first.first, cur.first.second);\n            \n            pq.push(cur);\n        }\n        \n        double sum = 0.0;\n        while (!pq.empty()) {\n            pair<pair<int, int>, double> cur = pq.top();\n            pq.pop();\n            sum += cur.first.first * 1.0 / cur.first.second;\n        }\n        \n        return sum / classes.size();\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1791-1800/Maximum Number of Consecutive Values You Can Make.cpp",
    "content": "class Solution {\npublic:\n    int getMaximumConsecutive(vector<int>& coins) {\n        sort(coins.begin(), coins.end());\n        int cur = 0;\n        \n        for (int coin : coins) {\n            if (cur + 1 >= coin) {\n                cur += coin;\n            } else {\n                break;\n            }\n        }\n        \n        return cur + 1;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1791-1800/Maximum Score of a Good Subarray.cpp",
    "content": "class Solution {\npublic:\n    int maximumScore(vector<int>& nums, int k) {\n        int mini = nums[k];\n        int ans = mini;\n        \n        int i = k;\n        int j = k;\n        \n        while (i > 0 || j < nums.size() - 1) {\n            if (i == 0 || (j+1 < nums.size() && nums[i-1] <= nums[j+1])) {\n                j++;\n                mini = min(mini, nums[j]);\n                ans = max(ans, mini * (j - i + 1));\n            } else {\n                i--;\n                mini = min(mini, nums[i]);\n                ans = max(ans, mini * (j - i + 1));\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1791-1800/Second Largest Digit in a String.cpp",
    "content": "class Solution {\npublic:\n    int secondHighest(string s) {\n        set<char> nums;\n        for (char ch : s) {\n            if (isdigit(ch)) {\n                nums.insert(ch);\n            }\n        }\n        \n        if (nums.size() < 2) {\n            return -1;\n        }\n        return *(++nums.rbegin()) - '0';\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1801-1810/Count Pairs With XOR in a Range.cpp",
    "content": "class Solution {\n    \n    const int HEIGHT = 14;\n    \n    class TreeNode {\n    public:\n        TreeNode* next[2];\n        int cnt;\n        TreeNode () {\n            next[0] = nullptr;\n            next[1] = nullptr;\n            cnt = 0;\n        };\n    };\n    \n    void insert(TreeNode* root, int num) {\n        TreeNode* cur = root;\n        for (int j = HEIGHT; j >= 0; j--) {\n            int index = ((num >> j) & 1);\n            if (cur->next[index] == nullptr)\n                cur->next[index] = new TreeNode();\n            cur = cur->next[index];\n            cur->cnt++;\n        }\n    }\n    \n    int GetCount(TreeNode* root, int num, int limit) {\n        TreeNode* cur = root;\n        int cnt = 0;\n        for (int j = HEIGHT; j >= 0; j--) {\n            int bit_num = ((num >> j) & 1);\n            int bit_limit = ((limit >> j) & 1);\n            \n            if (bit_limit == 1) {\n                // For bit_num branch, its values are all < limit\n                if (cur->next[bit_num] != nullptr) {\n                    cnt += cur->next[bit_num]->cnt;\n                }\n                // we try to pick the side so that it XOR bit_num is 1.\n                cur = cur->next[1 - bit_num];\n            } else {\n                // we pick 'bit_num' child so that it does not exceed limit.\n                cur = cur->next[bit_num];\n            }\n            \n            if (cur == nullptr) break;\n        }\n        return cnt;\n    }\n    \npublic:\n    int countPairs(vector<int>& nums, int low, int high) {\n        TreeNode* root = new TreeNode();\n        \n        int ans = 0;\n        for (int num : nums) {\n            ans += GetCount(root, num, high + 1) - GetCount(root, num, low);\n            insert(root, num);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1801-1810/Evaluate the Bracket Pairs of a String.cpp",
    "content": "class Solution {\npublic:\n    string evaluate(string s, vector<vector<string>>& knowledge) {\n        map<string, string> mymap;\n        for (const vector<string>& k : knowledge) {\n            mymap[k[0]] = k[1];\n        }\n        \n        string ans;\n        string key;\n        bool in_bracket = false;\n        for (char ch : s) {\n            if (ch == '(') {\n                in_bracket = true;\n            } else if (ch == ')') {\n                in_bracket = false;\n                if (mymap.count(key) > 0) {\n                    ans += mymap[key];\n                } else {\n                    ans += \"?\";\n                }\n                key.clear();\n            } else {\n                if (in_bracket) {\n                    key += ch;\n                } else {\n                    ans += ch;\n                }\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1801-1810/Implement Trie II (Prefix Tree).cpp",
    "content": "class Trie {\n    \n    struct TrieNode {\n        TrieNode* nodes[26];\n        int word_cnt;\n        int prefix_cnt;\n        // Initialize your data structure here.\n        TrieNode() {\n            memset(nodes, 0, sizeof(nodes));\n            word_cnt = 0;\n            prefix_cnt = 0;\n        }\n    };\n    \n    TrieNode* root;\n    \npublic:\n    Trie() {\n        root = new TrieNode();\n    }\n    \n    void insert(string word) {\n        TrieNode* tmp = root;\n        for(char ch : word) {\n            int index = ch - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                tmp->nodes[index] = new TrieNode();\n            }\n            tmp = tmp->nodes[index];\n            tmp->prefix_cnt++;\n        }\n        tmp->word_cnt++;\n    }\n    \n    int countWordsEqualTo(string word) {\n        TrieNode* tmp = root;\n        for(char ch : word) {\n            int index = ch - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                return 0;\n            }\n            tmp = tmp->nodes[index];\n        }\n        return tmp->word_cnt;\n    }\n    \n    int countWordsStartingWith(string prefix) {\n        TrieNode* tmp = root;\n        for(char ch : prefix) {\n            int index = ch - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                return 0;\n            }\n            tmp = tmp->nodes[index];\n        }\n        return tmp->prefix_cnt;\n    }\n    \n    void erase(string word) {\n        TrieNode* tmp = root;\n        TrieNode* to_be_deleted = nullptr;\n        for(char ch : word) {\n            int index = ch - 'a';\n            TrieNode* parent = tmp;\n            tmp = tmp->nodes[index];\n            tmp->prefix_cnt--;\n            \n            if (to_be_deleted != nullptr) {\n                delete to_be_deleted;\n            }\n            if (tmp->prefix_cnt == 0) {\n                if (to_be_deleted == nullptr) {\n                    parent->nodes[index] = nullptr;\n                }\n                to_be_deleted = tmp;\n            }\n        }\n        tmp->word_cnt--;\n        if (to_be_deleted != nullptr) {\n            delete to_be_deleted;\n        }\n    }\n};\n\n/**\n * Your Trie object will be instantiated and called as such:\n * Trie* obj = new Trie();\n * obj->insert(word);\n * int param_2 = obj->countWordsEqualTo(word);\n * int param_3 = obj->countWordsStartingWith(prefix);\n * obj->erase(word);\n */\n"
  },
  {
    "path": "cpp/1001-10000/1801-1810/Maximize Number of Nice Divisors.cpp",
    "content": "class Solution {\n    \n    long mod = 1e9+7;\n    \npublic:\n    int maxNiceDivisors(int primeFactors) {\n        int groups_of_3 = primeFactors/3;\n        int groups_of_2 = 0;\n        int remain = primeFactors - groups_of_3 * 3;\n        if (remain == 1) {\n            if (groups_of_3 > 0) {\n                groups_of_3--;\n                groups_of_2 = 2;\n            }\n        } else if (remain == 2) {\n            groups_of_2 = 1;\n        }\n        \n        long ans = 1;\n        \n        int num_3_used = 0;\n        int limit = sqrt(primeFactors);\n        int temp = 1;\n        while (groups_of_3 > 0) {\n            ans *= 3;\n            ans %= mod;\n            groups_of_3--;\n            num_3_used++;\n            if (num_3_used == limit) {\n                temp = ans;\n                break;\n            }\n        }\n        while (groups_of_3 >= limit) {\n            ans *= temp;\n            ans %= mod;\n            groups_of_3 -= limit;\n        }\n        while (groups_of_3 > 0) {\n            ans *= 3;\n            ans %= mod;\n            groups_of_3--;\n            num_3_used++;\n        }\n        \n        while (groups_of_2 > 0) {\n            ans *= 2;\n            ans %= mod;\n            groups_of_2--;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1801-1810/Maximum Value at a Given Index in a Bounded Array.cpp",
    "content": "class Solution {\n    \n    long getSumInRange(long peak, int length) {\n        long sum = 0;\n        if (length > peak) {\n            sum += (1 + peak) * peak / 2;\n            sum += (length - peak);\n        } else {\n            long minimum = peak - length + 1;\n            sum += (minimum + peak) * length / 2;\n        }\n        return sum;\n    }\n    \n    bool check(int n, int index, int maxSum, int peak) {\n        long sum = getSumInRange(peak, index + 1) + getSumInRange(peak, n - index) - peak;\n        return sum > (long)maxSum;\n    }\n    \npublic:\n    int maxValue(int n, int index, int maxSum) {\n        int left = 1;\n        int right = maxSum;\n        int ans = 1;\n        \n        while (left <= right) {\n            int mid = (left + right) / 2;\n            bool exceed = check(n, index, maxSum, mid);\n            if (exceed) {\n                right = mid - 1;\n            } else {\n                ans = mid;\n                left = mid + 1;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1801-1810/Minimum Path Cost in a Hidden Grid.cpp",
    "content": "/**\n * // This is the GridMaster's API interface.\n * // You should not implement it, or speculate about its implementation\n * class GridMaster {\n *   public:\n *     bool canMove(char direction);\n *     int move(char direction);\n *     boolean isTarget();\n * };\n */\n\nclass Solution {\n    pair<int, int> target;\npublic:\n    // 0 is blocked\n    void ConstructGrid(vector<vector<int>>& grid, GridMaster &master, int row, int col, const map<char, pair<int, int>>& directions, int cost) {\n        grid[row][col] = cost;\n        if (master.isTarget()) {\n            target.first = row;\n            target.second = col;\n        }\n        \n        for (const auto& direction : directions) {\n            int new_row = row + direction.second.first;\n            int new_col = col + direction.second.second;\n            if (grid[new_row][new_col] != -1) {\n                continue;\n            }\n            if (master.canMove(direction.first)) {\n                int cost = master.move(direction.first);\n                ConstructGrid(grid, master, new_row, new_col, directions, cost);\n                if (direction.first == 'U') master.move('D');\n                else if (direction.first == 'D') master.move('U');\n                else if (direction.first == 'L') master.move('R');\n                else master.move('L');\n            } else {\n                grid[new_row][new_col] = 0;\n            }\n        }\n    }\n    \n    int findShortestPath(GridMaster &master) {\n        map<char, pair<int, int>> directions = {\n            {'U', {-1, 0}},\n            {'D', {1, 0}},\n            {'L', {0, -1}},\n            {'R', {0, 1}},\n        };\n        \n        vector<vector<int>> grid(300, vector<int>(300, -1));\n        ConstructGrid(grid, master, 150, 150, directions, /*cost=*/1);\n        \n        auto cmp = [](const pair<pair<int, int>, int> &a, const pair<pair<int, int>, int> &b) {\n            return a.second > b.second;\n        };\n        priority_queue<pair<pair<int, int>, int>, vector<pair<pair<int, int>, int>>, decltype(cmp)> myqueue(cmp);\n        myqueue.push({{150, 150}, 0});\n        // mark as visited.\n        grid[150][150] = -1;\n        \n        while (!myqueue.empty()) {\n            pair<pair<int, int>, int> cur = myqueue.top();\n            myqueue.pop();\n            \n            if (cur.first == target) {\n                return cur.second;\n            }\n            int r = cur.first.first;\n            int c = cur.first.second;\n            grid[r][c] = -1;\n            \n            for (auto& [ch, direction] : directions) {\n                int new_row = r + direction.first;\n                int new_col = c + direction.second;\n                if (grid[new_row][new_col] <= 0) {\n                    continue;\n                }\n                myqueue.push({{new_row, new_col}, cur.second + grid[new_row][new_col]});\n            }\n        }\n        \n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1801-1810/Number of Different Integers in a String.cpp",
    "content": "class Solution {\npublic:\n    int numDifferentIntegers(string word) {\n        word += 'a';\n        set<string> s;\n        string tmp;\n        for (char ch : word) {\n            if (isdigit(ch)) {\n                tmp += ch;\n            } else {\n                while (tmp.length() > 1 && tmp[0] == '0') {\n                    tmp = tmp.substr(1);\n                }\n                if (!tmp.empty()) s.insert(tmp);\n               tmp = \"\"; \n            }\n        }\n        \n        return s.size();\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1801-1810/Number of Orders in the Backlog.cpp",
    "content": "class Solution {\npublic:\n    int getNumberOfBacklogOrders(vector<vector<int>>& orders) {\n        auto cmp1 = [](const vector<int> &a, const vector<int> &b) {\n            return a[0] < b[0];\n        };\n        auto cmp2 = [](const vector<int> &a, const vector<int> &b) {\n            return a[0] > b[0];\n        };\n\n        priority_queue<vector<int>, vector<vector<int>>, decltype(cmp1)> buy_backlog(cmp1);\n        priority_queue<vector<int>, vector<vector<int>>, decltype(cmp2)> sell_backlog(cmp2);\n        \n        for (vector<int> order : orders) {\n            if (order[2] == 0) {\n                // buy order\n                while (order[1] > 0 && !sell_backlog.empty()) {\n                    if (sell_backlog.top()[0] > order[0]) {\n                        break;\n                    }\n                    vector<int> sell_order = sell_backlog.top();\n                    sell_backlog.pop();\n                    \n                    if (order[1] >= sell_order[1]) {\n                        order[1] -= sell_order[1];\n                    } else {\n                        sell_order[1] -= order[1];\n                        order[1] = 0;\n                        sell_backlog.push(sell_order);\n                    }\n                }\n                if (order[1] > 0) {\n                    buy_backlog.push(order);\n                }\n            } else {\n                while (order[1] > 0 && !buy_backlog.empty()) {\n                    if (buy_backlog.top()[0] < order[0]) {\n                        break;\n                    }\n                    vector<int> buy_order = buy_backlog.top();\n                    buy_backlog.pop();\n                    \n                    if (order[1] >= buy_order[1]) {\n                        order[1] -= buy_order[1];\n                    } else {\n                        buy_order[1] -= order[1];\n                        order[1] = 0;\n                        buy_backlog.push(buy_order);\n                    }\n                }\n                if (order[1] > 0) {\n                    sell_backlog.push(order);\n                }\n            }\n        }\n        \n        int mod = 1e9+7;\n        int ans = 0;\n        while (!buy_backlog.empty()) {\n            ans += buy_backlog.top()[1];\n            ans %= mod;\n            buy_backlog.pop();\n        }\n        while (!sell_backlog.empty()) {\n            ans += sell_backlog.top()[1];\n            ans %= mod;\n            sell_backlog.pop();\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1811-1820/Count Nice Pairs in an Array.cpp",
    "content": "class Solution {\npublic:\n    int reverse(int x) {\n        int result = 0;\n        while (x > 0) {\n            result = result * 10 + (x % 10);\n            x /= 10;\n        }\n        return result;\n    }\n    \n    int countNicePairs(vector<int>& nums) {\n        unordered_map<int, int> mymap;\n        int mod = 1e9+7;\n        int res = 0;\n        for (int num : nums) {\n            int rnum = reverse(num);\n            int diff = num - rnum;\n            res += mymap[diff];\n            res %= mod;\n            mymap[diff]++;\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1811-1820/Determine Color of a Chessboard Square.cpp",
    "content": "class Solution {\npublic:\n    bool squareIsWhite(string coordinates) {\n        return ((coordinates[0] - 'a') % 2) == ((coordinates[1] - '0') % 2);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1811-1820/Finding the Users Active Minutes.cpp",
    "content": "class Solution {\npublic:\n    vector<int> findingUsersActiveMinutes(vector<vector<int>>& logs, int k) {\n        vector<int> res(k, 0);\n        \n        map<int, set<int>> activities;\n        for (const vector<int>& log : logs) {\n            activities[log[0]].insert(log[1]);\n        }\n        \n        for (auto [id, activity] : activities) {\n            res[activity.size() - 1]++;\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1811-1820/Maximum Number of Accepted Invitations.cpp",
    "content": "class Solution {\n    int m, n;\npublic:\n    bool BipartiteMatch(const vector<vector<int>>& grid, int u, vector<bool>& visited, vector<int>& girls) {\n        for (int v = 0; v < n; v++) {\n            if (grid[u][v] == 0 || visited[v]) {\n                continue;\n            }\n            \n            visited[v] = true;\n            if (girls[v] < 0 || BipartiteMatch(grid, girls[v], visited, girls)) {\n                girls[v] = u;\n                return true;\n            }\n       }\n        \n       return false;\n    }\n    \n    int maximumInvitations(vector<vector<int>>& grid) {\n        m = grid.size();\n        n = grid[0].size();\n        vector<int> grils(n, -1);\n        int matches = 0;\n\n        for (int u = 0; u < m; u++) {\n            vector<bool> visited(n, false);\n            if (BipartiteMatch(grid, u, visited, grils)) {\n                matches++;\n            }\n        }\n        return matches;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1811-1820/Maximum Number of Groups Getting Fresh Donuts.cpp",
    "content": "class Solution {\npublic:\n    string GetKey(const vector<int>& cnts) {\n        stringstream ss;\n        for (int i = 1; i < cnts.size(); i++) {\n            ss << i << \":\" << cnts[i] << \":\";\n        }\n        return ss.str();\n    }\n    \n    int dfs(vector<int>& cnts, int remain, int batchSize, unordered_map<string, int>& cache) {\n        string key = GetKey(cnts);\n        if (cache.count(key) > 0) {\n            return cache[key];\n        }\n        \n        int res = 0;\n        for (int i = 1; i < cnts.size(); i++) {\n            if (cnts[i] == 0) continue;\n            \n            int tmp = (remain == 0 ? 1 : 0);\n            cnts[i]--;\n            tmp += dfs(cnts, (remain - i + batchSize) % batchSize, batchSize, cache);\n            cnts[i]++;\n            res = max(res, tmp);\n        }\n        return cache[key] = res;\n    }\n    \n    int maxHappyGroups(int batchSize, vector<int>& groups) {\n        int res = 0;\n        vector<int> cnts(batchSize, 0);\n        for (int group : groups) {\n            int g = group % batchSize;\n            if (g == 0) {\n                res++;\n            } else if (cnts[batchSize - g] > 0) {\n                res++;\n                cnts[batchSize - g]--;\n            } else {\n                cnts[g]++;\n            }\n        }\n        \n        // batchSize = 4, groups = [1,3,2,5,2,2,1,6]\n        // cnts = [0, 3, 4, 1] -> [0, 2, 0, 0] res = 3\n        unordered_map<string, int> cache;\n        return res + dfs(cnts, /*remain=*/0, batchSize, cache);\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1811-1820/Minimum Absolute Sum Difference.cpp",
    "content": "class Solution {\npublic:\n    int minAbsoluteSumDiff(vector<int>& nums1, vector<int>& nums2) {\n        int mod = 1e9 + 7;\n        int res = 0;\n        for (int i = 0; i < nums1.size(); i++) {\n            res += abs(nums1[i] - nums2[i]);\n            res %= mod;\n        }\n        \n        int minus = 0;\n        vector<int> copy_nums = nums1;\n        sort(copy_nums.begin(), copy_nums.end());\n        for (int i = 0; i < nums1.size(); i++) {\n            int original = abs(nums1[i] - nums2[i]);\n            int dis = 0;\n            auto it = lower_bound(copy_nums.begin(), copy_nums.end(), nums2[i]);\n            if (it == copy_nums.end()) {\n                it--;\n                dis = abs(*it - nums2[i]);\n            } else {\n                dis = abs(*it - nums2[i]);\n                if (it != copy_nums.begin()) {\n                    it--;\n                    dis = min(dis, abs(*it - nums2[i]));\n                }\n            }\n            \n            minus = max(minus, original - dis);\n        }\n        \n        res -= minus;\n        if (res < 0) res += mod;\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1811-1820/Number of Different Subsequences GCDs.cpp",
    "content": "class Solution {\npublic:\n    int countDifferentSubsequenceGCDs(vector<int>& nums) {\n        int max_num = *max_element(nums.begin(), nums.end());\n        vector<bool> vec(max_num + 1, false);\n        for (int num: nums) {\n            vec[num] = true;\n        }\n        int ans = 0;\n        for (int i = 1; i <= max_num; i++) {\n            int gcd = 0;\n            for (int j = i; j <= max_num; j += i) {\n                if (vec[j] == true) {\n                    gcd = __gcd(gcd, j);\n                }\n            }\n            if (gcd == i) ans++;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1811-1820/Sentence Similarity III.cpp",
    "content": "class Solution {\npublic:\n    vector<string> split(const string &s, char delim) {\n        vector<string> elems;\n        stringstream ss(s);\n        string item;\n        while (getline(ss, item, delim)) {\n            if (item.length() > 0) {\n                elems.push_back(item);\n            }\n        }\n        return elems;\n    }\n    \n    bool areSentencesSimilar(string sentence1, string sentence2) {\n        vector<string> words1 = split(sentence1, ' ');\n        vector<string> words2 = split(sentence2, ' ');\n        int i1 = 0, i2 = 0;\n        int j1 = words1.size() - 1, j2 = words2.size() - 1;\n        while (i1 <= j1 && i2 <= j2) {\n            if (words1[i1] == words2[i2]) {\n                i1++;\n                i2++;\n            } else if (words1[j1] == words2[j2]) {\n                j1--;\n                j2--;\n            } else {\n                return false;\n            }\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1811-1820/Truncate Sentence.cpp",
    "content": "class Solution {\npublic:\n    string truncateSentence(string s, int k) {\n        int space_idx = -1;\n        int num_spaces = 0;\n        for (int i = 0; i < s.length(); i++) {\n            if (s[i] == ' ') {\n                num_spaces++;\n            }\n            if (num_spaces == k) {\n                space_idx = i;\n                break;\n            }\n        }\n        \n        if (space_idx < 0) {\n            return s;\n        } else {\n            return s.substr(0, space_idx);\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1821-1830/Faulty Sensor.cpp",
    "content": "class Solution {\npublic:\n    int badSensor(vector<int>& sensor1, vector<int>& sensor2) {\n        int n = sensor1.size();\n        for (int i = 0; i < n - 1; i++) {\n            if (sensor1[i] == sensor2[i]) {\n                continue;\n            }\n            \n            bool is_sensor_1 = true;\n            for (int j = i; j < n - 1; j++) {\n                if (sensor1[j] != sensor2[j+1]) {\n                    is_sensor_1 = false;\n                    break;\n                }\n            }\n            if (is_sensor_1) return 1;\n            \n            bool is_sensor_2 = true;\n            for (int j = i; j < n - 1; j++) {\n                if (sensor1[j+1] != sensor2[j]) {\n                    is_sensor_2 = false;\n                    break;\n                }\n            }\n            if (is_sensor_2) return 2;\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1821-1830/Finding MK Average.cpp",
    "content": "class MKAverage {\n    int m;\n    int k;\n    queue<int> window;\n    \n    multiset<int> smaller_nums;\n    multiset<int> larger_nums;\n    multiset<int> middles;\n    \n    long middles_sum = 0;\n    \n    void InitializeMultiset() {\n        vector<int> nums;\n        queue<int> current_window = window;\n        while (!current_window.empty()) {\n            nums.push_back(current_window.front());\n            current_window.pop();\n        }\n        sort(nums.begin(), nums.end());\n        for (int i = 0; i < m; i++) {\n            if (i < k) {\n                smaller_nums.insert(nums[i]);\n            } else if (i > m - k - 1) {\n                larger_nums.insert(nums[i]);\n            } else {\n                middles_sum += nums[i];\n                middles.insert(nums[i]);\n            }\n        }\n    }\npublic:\n    MKAverage(int m, int k) {\n        this->m = m;\n        this->k = k;\n    }\n\n    void AddElement(int val) {\n        window.push(val);\n        if (middles.empty()) {\n            // It only run once.\n            if (window.size() == m) {\n                InitializeMultiset();\n            }\n        } else if (val < *smaller_nums.rbegin()) {\n            int middle_candidate = *smaller_nums.rbegin();\n            smaller_nums.erase(--smaller_nums.end());\n            smaller_nums.insert(val);\n            middles.insert(middle_candidate);\n            middles_sum += middle_candidate;\n        } else if (val > *larger_nums.begin()) {\n            int middle_candidate = *larger_nums.begin();\n            larger_nums.erase(larger_nums.begin());\n            larger_nums.insert(val);\n            middles.insert(middle_candidate);\n            middles_sum += middle_candidate;            \n        } else {\n            middles.insert(val);\n            middles_sum += val;\n        }\n    }\n\n    void RemoveElement() {\n        int val = window.front();\n        window.pop();\n        if (val <= *smaller_nums.rbegin()) {\n            smaller_nums.erase(smaller_nums.lower_bound(val));\n            int small_candidate = *middles.begin();\n            smaller_nums.insert(small_candidate);\n            middles.erase(middles.begin());\n            middles_sum -= small_candidate;\n        } else if (val >= * larger_nums.begin()) {\n            larger_nums.erase(larger_nums.lower_bound(val));\n            int large_candidate = *middles.rbegin();\n            larger_nums.insert(large_candidate);\n            middles.erase(--middles.end());\n            middles_sum -= large_candidate;\n        } else {\n            middles.erase(middles.lower_bound(val));\n            middles_sum -= val;\n        }\n    }\n\n    void addElement(int num) {\n        AddElement(num);\n        if (window.size() > m) {\n            RemoveElement();\n        }\n    }\n\n    int calculateMKAverage() {\n        return window.size() < m ? -1 : middles_sum / middles.size();\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1821-1830/Maximum XOR for Each Query.cpp",
    "content": "class Solution {\npublic:\n    vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {\n        int n = nums.size();\n        vector<int> ans;\n        \n        int sum = 0;\n        for (int num : nums) sum ^= num;\n        \n        int max_num = 0;\n        for (int k = 1; k <= maximumBit; k++) {\n            max_num *= 2;\n            max_num++;\n        }\n        \n        for (int i = nums.size() - 1; i >= 0; i--) {\n            ans.push_back(max_num ^ sum);\n            sum ^= nums[i];\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1821-1830/Minimum Number of Operations to Make String Sorted.cpp",
    "content": "class Solution {\n    int mod = 1e9 + 7;\n    \n    long pow(long a, long p, long mod) {\n        long ans = 1;\n        while (p > 0) {\n            if (p & 1) {\n                ans = ans * a % mod;\n            }\n            a = a * a % mod;\n            p = p >> 1;\n        }\n        return ans;\n    }\npublic:\n    \n    int makeStringSorted(string s) {\n        map<int, int> freq; \n        for (char ch: s) {\n            freq[ch - 'a']++;\n        }\n        \n        int n = s.length();\n        vector<long> fact(s.size() + 1, 1);\n        for (int i = 1; i <= s.size(); i++) {\n            fact[i] = (fact[i - 1] * i) % mod;\n        }\n        \n        long ans = 0;\n        for (char ch : s) {\n            long freq_sum = 0;\n            long duplicates = 1;\n            for (int i = 0; i < 26; i++) {\n                if (i < (ch - 'a')) {\n                    freq_sum += freq[i];\n                }\n                duplicates = (duplicates * fact[freq[i]]) % mod;\n            }\n            ans += (freq_sum * fact[n - 1] % mod) * pow(duplicates, mod - 2, mod);\n            ans %= mod;\n            n--;\n            freq[ch - 'a']--;\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1821-1830/Minimum Operations to Make the Array Increasing.cpp",
    "content": "class Solution {\npublic:\n    int minOperations(vector<int>& nums) {\n        int ans = 0;\n        for (int i = 1; i < nums.size(); i++) {\n            int previous = nums[i-1];\n            int current = nums[i];\n            \n            if (current <= previous) {\n                current = previous + 1;\n                ans += (current - nums[i]);\n                nums[i] = current;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1821-1830/Minimum Sideway Jumps.cpp",
    "content": "class Solution {\npublic:\n    int minSideJumps(vector<int>& obstacles) {\n        int n = obstacles.size();\n        vector<vector<int>> dp (n, vector<int>(3, 99999999));\n        dp[0][1] = 0;\n        dp[0][0] = dp[0][2] = 1;\n        \n        for (int i = 1; i < n; i++) {\n            for (int k = 0; k < 3; k++) {\n                if (obstacles[i - 1] == (k + 1) || obstacles[i] == (k + 1)) {\n                    dp[i][k] = 99999999;\n                } else {\n                    int a_lane = (k + 1) % 3;\n                    int b_lane = (k + 2) % 3;\n                    dp[i][k] = min(dp[i - 1][k], min(dp[i - 1][a_lane], dp[i - 1][b_lane]) + 1);\n                }\n            }\n        }\n        \n        return min(dp[n-1][0], min(dp[n-1][1], dp[n-1][2]));\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1821-1830/Queries on Number of Points Inside a Circle.cpp",
    "content": "class Solution {\npublic:\n    vector<int> countPoints(vector<vector<int>>& points, vector<vector<int>>& queries) {\n        vector<int> ans;\n        \n        for (const vector<int>& query : queries) {\n            int num = 0;\n            int threshold = query[2] * query[2];\n            for (const vector<int>& point : points) {\n                int dis_square = (point[0] - query[0]) * (point[0] - query[0]) + (point[1] - query[1]) * (point[1] - query[1]);\n                if (dis_square <= threshold) {\n                    num++;\n                }\n            }\n            ans.push_back(num);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1821-1830/Sign of the Product of an Array.cpp",
    "content": "class Solution {\npublic:\n    int arraySign(vector<int>& nums) {\n        int res = 1;\n        for (int num : nums) {\n            if (num > 0) continue;\n            else if (num == 0) return 0;\n            else res *= -1;\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1831-1840/Check if the Sentence Is Pangram.cpp",
    "content": "class Solution {\npublic:\n    bool checkIfPangram(string sentence) {\n        set<char> letters;\n        for (char ch : sentence) {\n            letters.insert(ch);\n        }\n        return letters.size() == 26;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1831-1840/Find XOR Sum of All Pairs Bitwise AND.cpp",
    "content": "class Solution {\npublic:\n    int getXORSum(vector<int>& arr1, vector<int>& arr2) {\n        vector<int> bits(32, 0);\n        for (int v : arr2) {\n            int pos = 0;\n            while (v > 0) {\n                if (v & 1) {\n                    bits[pos]++;\n                }\n                v = v >> 1;\n                pos++;\n            }\n        }\n        \n        int res = 0;\n        \n        for (int v : arr1) {\n            int pos = 0;\n            int tmp = 0;\n            while (v > 0) {\n                if (v & 1) {\n                    if (bits[pos] % 2 == 1) {\n                        tmp |= (1 << pos);\n                    }\n                }\n                v = v >> 1;\n                pos++;\n            }\n            \n            res ^= tmp;\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1831-1840/Longest Substring Of All Vowels in Order.cpp",
    "content": "class Solution {\npublic:\n    int longestBeautifulSubstring(string word) {\n        int cnt = 1;\n        int len = 1;\n        int max_len = 0;\n        for (int i = 1; i != word.size(); ++i) {\n            if (word[i - 1] == word[i]) {\n                ++len;\n            } else if (word[i - 1] < word[i]) {\n                ++len;\n                ++cnt;\n            } else {\n                cnt = 1;\n                len = 1;\n            }\n            \n            if (cnt == 5) {\n                max_len = max(max_len, len);\n            }\n        }\n        return max_len;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1831-1840/Maximum Building Height.cpp",
    "content": "class Solution {\npublic:\n    int maxBuilding(int n, vector<vector<int>>& restrictions) {\n        restrictions.push_back({1, 0});\n        restrictions.push_back({n, n - 1});\n        sort(restrictions.begin(), restrictions.end());\n        \n        for (int i = 1; i < restrictions.size(); i++) {\n            restrictions[i][1] = min(restrictions[i][1], restrictions[i-1][1] + restrictions[i][0] - restrictions[i-1][0]);\n        }\n        for (int i = restrictions.size() - 2; i >= 0; --i) {\n            restrictions[i][1] = min(restrictions[i][1], restrictions[i+1][1] + restrictions[i+1][0] - restrictions[i][0]);\n        }\n        \n        int res = 0;\n        for (int i = 1; i < restrictions.size(); i++) {\n            int left_restriction = restrictions[i-1][1];\n            int right_restriction = restrictions[i][1];\n            res = max(res, max(left_restriction, right_restriction) + (restrictions[i][0] - restrictions[i-1][0] - abs(left_restriction - right_restriction)) / 2);\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1831-1840/Maximum Ice Cream Bars.cpp",
    "content": "class Solution {\npublic:\n    int maxIceCream(vector<int>& costs, int coins) {\n        sort(begin(costs), end(costs));\n        int num = 0;\n        for (int cost : costs) {\n            if (coins >= cost) {\n                num++;\n                coins -= cost;\n            } else {\n                break;\n            }\n        }\n        return num;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1831-1840/Remove Duplicates From an Unsorted Linked List.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode() : val(0), next(nullptr) {}\n *     ListNode(int x) : val(x), next(nullptr) {}\n *     ListNode(int x, ListNode *next) : val(x), next(next) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* deleteDuplicatesUnsorted(ListNode* head) {\n        ListNode sudo_head(-1);\n        \n        unordered_map<int, int> mymap;\n        for (ListNode* tmp = head; tmp != nullptr; tmp = tmp->next) {\n            mymap[tmp->val]++;\n        }\n        \n        ListNode* p = &sudo_head;\n        for (ListNode* tmp = head; tmp != nullptr; tmp = tmp->next) {\n            if (mymap[tmp->val] > 1) {\n                continue;\n            }\n            \n            p->next = tmp;\n            p = tmp;\n        }\n        p->next = nullptr;\n        \n        return sudo_head.next;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1831-1840/Single-Threaded CPU.cpp",
    "content": "class Solution {\npublic:\n    vector<int> getOrder(vector<vector<int>>& tasks) {\n        vector<int> idx(tasks.size());\n        iota(begin(idx), end(idx), 0);\n        sort(begin(idx), end(idx), [&](int i, int j) { return tasks[i][0] < tasks[j][0]; });\n        \n        vector<int> res;\n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;\n        long time = 1;\n        for (int i = 0; i < idx.size() || !pq.empty();) {\n            while (i < idx.size() && tasks[idx[i]][0] <= time) {\n                pq.push({tasks[idx[i]][1], idx[i]});\n                ++i;\n            }\n            if (!pq.empty()) {\n                auto [processing_time, j] = pq.top();\n                pq.pop();\n                time += processing_time;\n                res.push_back(j);\n            } else {\n                time = tasks[idx[i]][0];\n            }\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1831-1840/Sum of Digits in Base K.cpp",
    "content": "class Solution {\npublic:\n    int sumBase(int n, int k) {\n        int res = 0;\n        \n        while (n > 0) {\n            res += (n % k);\n            n /= k;\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1841-1850/Closest Room.cpp",
    "content": "class Solution {\npublic:\n    vector<int> closestRoom(vector<vector<int>>& rooms, vector<vector<int>>& queries) {\n        int m = queries.size();\n        vector<int> idx(m);\n        std::iota(idx.begin(), idx.end(), 0);\n\n        std::sort(idx.begin(), idx.end(), [&queries](int idx1, int idx2) {\n            return queries[idx1][1] > queries[idx2][1];\n        });\n        std::sort(rooms.begin(), rooms.end(), [](const vector<int>& room1, const vector<int>& room2) {\n            return room1[1] > room2[1];\n        });\n        \n        vector<int> ans(m, -1);\n        int room_idx = 0;\n        set<int> valid_rooms;\n        for (int e : idx) {\n            int preferred = queries[e][0];\n            int min_size = queries[e][1];\n            \n            while (room_idx < rooms.size() && rooms[room_idx][1] >= min_size) {\n                valid_rooms.insert(rooms[room_idx][0]);\n                room_idx++;\n            }\n            \n            if (valid_rooms.empty()) {\n                continue;\n            }\n            \n            auto it = valid_rooms.upper_bound(preferred);\n            if (it != valid_rooms.end()) {\n                ans[e] = *it;\n            }\n            if (it != valid_rooms.begin()) {\n                it--;\n                if (ans[e] == -1) {\n                    ans[e] = *it;\n                } else if (preferred - *it <= ans[e] - preferred) {\n                    ans[e] = *it;\n                }\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1841-1850/Minimum Adjacent Swaps to Reach the Kth Smallest Number.cpp",
    "content": "class Solution {\npublic:\n    int getMinSwaps(string num, int k) {\n        string copy = num;\n        while (k > 0) {\n            std::next_permutation(begin(copy), end(copy));\n            k--;\n        }\n        \n        int res = 0;\n        for (int i = 0; i < num.length(); i++) {\n            if (num[i] == copy[i]) continue;\n            \n            int j = i + 1;\n            for (; j < copy.length(); j++) {\n                if (num[i] == copy[j]) {\n                    break;\n                }\n            }\n            res += (j - i);\n            copy = copy.substr(0, i) + copy[j] + copy.substr(i, j - i) + copy.substr(j + 1); \n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/1001-10000/1851-1860/Minimum Interval to Include Each Query.cpp",
    "content": "class Solution {\npublic:\n    vector<int> minInterval(vector<vector<int>>& intervals, vector<int>& queries) {\n        int m = queries.size();\n\n        sort(intervals.begin(), intervals.end(),[](const vector<int>& lhs, const vector<int>& rhs){\n            return lhs[1] - lhs[0] < rhs[1] - rhs[0];\n        });\n        \n        set<pair<int, int>> myset;\n        for (int i = 0; i < m; i++) {\n            myset.insert({queries[i], i});\n        }\n        \n        vector<int> ans(m, -1);\n        for (const vector<int>& interval : intervals) {\n            auto it = myset.lower_bound({interval[0], 0});\n            \n            while (it != myset.end() && it->first <= interval[1]) {\n                ans[it->second] = interval[1] - interval[0] + 1;\n                it = myset.erase(it);\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/101-110/Balanced Binary Tree.cpp",
    "content": "class Solution {\n    \n    int help(TreeNode *root, bool& flag) {\n        if (root == nullptr) return 0;\n        int left = 1 + help(root->left, flag);\n        int right = 1 + help(root->right, flag);\n        \n        if (abs(left - right) > 1) flag = false;\n        return max(left, right);\n    }\n    \npublic:\n    bool isBalanced(TreeNode *root) {\n        bool flag = true;\n        help(root, flag);\n        return flag;\n    }\n};\n"
  },
  {
    "path": "cpp/101-110/Binary Tree Level Order Traversal II.cpp",
    "content": "class Solution {\n    \n    void help(TreeNode *root, int level, vector<vector<int>>& results)\n    {\n        if(root)\n        {\n            if(results.size() == level)\n            {\n                vector<int> v;\n                results.push_back(v);\n            }\n            results[level].push_back(root->val);\n            help(root->left, level+1, results);\n            help(root->right, level+1, results);\n        }\n    }\n    \npublic:\n    vector<vector<int> > levelOrderBottom(TreeNode *root) {\n        vector<vector<int>> results;\n        help(root, 0, results);\n        reverse(results.begin(), results.end());\n        return results;\n    }\n};\n"
  },
  {
    "path": "cpp/101-110/Binary Tree Level Order Traversal.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<vector<int>> levelOrder(TreeNode* root) {\n        vector<vector<int>> result;\n        if (!root) return result;\n        queue<TreeNode*> myqueue({root, nullptr});\n        \n        vector<int> tmp;\n        while (!myqueue.empty()) {\n            TreeNode* currentNode = myqueue.front();\n            myqueue.pop();\n            if (currentNode == nullptr) {\n                result.push_back(tmp);\n                tmp.clear();\n                if (!myqueue.empty()) myqueue.push(nullptr);\n            } else {\n                tmp.push_back(currentNode->val);\n                if (currentNode->left) myqueue.push(currentNode->left);\n                if (currentNode->right) myqueue.push(currentNode->right);\n            }\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/101-110/Binary Tree Zigzag Level Order Traversal.cpp",
    "content": "class Solution {\n    \npublic:\n    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {\n        vector<vector<int>> result;\n        if (!root) return result;\n        queue<TreeNode*> myqueue;\n        myqueue.push(root);\n        \n        bool flag = true;\n        \n        while (!myqueue.empty()) {\n            int size_ = myqueue.size();\n            vector<int> n_vec(size_, 0);\n            \n            for (int i = 0; i < size_; i++) {\n                TreeNode* ele = myqueue.front();\n                myqueue.pop();\n                if (flag) n_vec[i] = ele->val;\n                else n_vec[size_ - i - 1] = ele->val;\n                \n                if (ele->left) {\n                    myqueue.push(ele->left);\n                }\n                if (ele->right) {\n                    myqueue.push(ele->right);\n                }\n            }\n            \n            flag = !flag;\n            \n            result.emplace_back(n_vec);\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/101-110/Construct Binary Tree from Inorder and Postorder Traversal.cpp",
    "content": "class Solution {\n\nTreeNode* helper(vector<int>& postorder,int i,int j,vector<int>& inorder,int ii,int jj) {\n        if (i >= j) return nullptr;\n        int mid = postorder[j-1];\n        auto f = find(inorder.begin() + ii,inorder.begin() + jj,mid);\n        int dis = f - inorder.begin() - ii;\n        TreeNode* root = new TreeNode(mid);\n        root -> left = helper(postorder, i, i + dis, inorder, ii, ii + dis);\n        root -> right = helper(postorder, i + dis, j-1, inorder, ii + dis + 1, jj);\n        return root;\n    }\n\npublic:\n    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {\n        return helper(postorder,0,postorder.size(),inorder,0,inorder.size());\n    }\n};\n"
  },
  {
    "path": "cpp/101-110/Construct Binary Tree from Preorder and Inorder Traversal.cpp",
    "content": "class Solution {\n\nTreeNode* helper(vector<int>& preorder,int i,int j,vector<int>& inorder,int ii,int jj) {\n        if(i >= j) return nullptr;\n        int mid = preorder[i];\n        auto f = find(inorder.begin() + ii,inorder.begin() + jj,mid);\n        int dis = f - inorder.begin() - ii;\n        TreeNode* root = new TreeNode(mid);\n        root -> left = helper(preorder,i + 1,i + 1 + dis,inorder,ii,ii + dis);\n        root -> right = helper(preorder,i + 1 + dis,j,inorder,ii + dis + 1,jj);\n        return root;\n    }\n\npublic:\n    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {\n        return helper(preorder,0,preorder.size(),inorder,0,inorder.size());\n    }\n};\n"
  },
  {
    "path": "cpp/101-110/Convert Sorted Array to Binary Search Tree.cpp",
    "content": "class Solution {\n    \n    TreeNode *help(vector<int>::iterator it1, vector<int>::iterator it2) {\n        if (it1 == it2)\n            return new TreeNode(*it1);\n        if (it1 > it2)\n            return nullptr;\n        vector<int>::iterator midit = it1+(it2-it1)/2;\n        TreeNode *node = new TreeNode(*midit);\n        node->left = help(it1,midit-1);\n        node->right = help(midit+1, it2);\n        return node;\n    }\n    \npublic:\n    TreeNode *sortedArrayToBST(vector<int> &num) {\n        if (num.size() == 0)\n            return nullptr;\n        return help(num.begin(), num.end()-1);\n    }\n};\n"
  },
  {
    "path": "cpp/101-110/Convert Sorted List to Binary Search Tree.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\n/**\n * Definition for binary tree\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    ListNode *mylist;\n    \n    int len(ListNode *head)\n    {\n        int l = 0;\n        while(head) {\n            l++;\n            head = head->next;\n        }\n        return l;\n    }\n    \n    TreeNode *help(int n)\n    {\n        if(n == 0) return nullptr;\n        TreeNode *l = help(n/2);\n        TreeNode *newnode = new TreeNode(mylist->val);\n        newnode->left = l;\n        mylist = mylist->next;\n        newnode->right = help(n - n/2 - 1);\n        return newnode;\n    }\n    \npublic:\n    TreeNode *sortedListToBST(ListNode *head) {\n        this->mylist = head;\n        return help(len(head));\n    }\n};"
  },
  {
    "path": "cpp/101-110/Maximum Depth of Binary Tree.cpp",
    "content": "class Solution {\npublic:\n    int maxDepth(TreeNode *root) {\n        if(!root)\n            return 0;\n        return 1 + max(maxDepth(root->left), maxDepth(root->right));\n    }\n};\n"
  },
  {
    "path": "cpp/101-110/Symmetric Tree.cpp",
    "content": "class Solution {\npublic:\n    bool isSymmetric(TreeNode *root) {\n        \n        queue<TreeNode*> low;\n        if(!root)\n            return true;\n        low.push(root->left);\n        low.push(root->right);\n        \n        while(!low.empty())\n        {\n            TreeNode *left = low.front();\n            low.pop();\n            TreeNode *right = low.front();\n            low.pop();\n            if(!left && !right)\n                continue;\n            if( (left && !right) || (!left && right) )\n                return false;\n            if( left->val != right->val )\n                return false;\n            low.push(left->left);\n            low.push(right->right);\n            low.push(left->right);\n            low.push(right->left);\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/111-120/Distinct Subsequences.cpp",
    "content": "class Solution {\npublic:\n    int numDistinct(string s, string t) {\n        int n = s.length();\n        int m = t.length();\n\n        vector<vector<int>> dp(n+1, vector<int>(m + 1, 0));\n        \n        for(int k = 0; k <= n; k++)\n            dp[k][0] = 1;\n        \n        for(int i = 1; i <= n; i++) {\n            for(int j = 1; j <= m; j++) {\n                dp[i][j] = dp[i-1][j];\n                if(s[i-1] == t[j-1])\n                    dp[i][j] += dp[i-1][j-1];\n            }\n        }\n        \n        return dp[n][m];\n    }\n};\n"
  },
  {
    "path": "cpp/111-120/Flatten Binary Tree to Linked List.cpp",
    "content": "class Solution {\n    \n    TreeNode* flatten(TreeNode* root, TreeNode* pre) {\n        if (root == nullptr) return pre;\n        pre = flatten(root->right, pre);\n        pre = flatten(root->left, pre);\n        root->right = pre;\n        root->left = nullptr;\n        pre = root;\n        return root;\n    }\n    \npublic:\n    void flatten(TreeNode* root) {\n        flatten(root, nullptr);\n    }\n};\n"
  },
  {
    "path": "cpp/111-120/Minimum Depth of Binary Tree.cpp",
    "content": "class Solution {\n    \n    int help(TreeNode *root)\n    {\n        if(!root->left && !root->right)\n            return 1;\n        else if(root->left && root->right)\n            return 1+min(help(root->left), help(root->right));\n        else if(!root->left && root->right)\n            return 1+help(root->right);\n        else\n            return 1+help(root->left);\n    }\n    \npublic:\n    int minDepth(TreeNode *root) {\n        if(!root)\n            return 0;\n        return help(root);\n    }\n};\n"
  },
  {
    "path": "cpp/111-120/Pascal's Triangle II.cpp",
    "content": "class Solution {\npublic:\n    vector<int> getRow(int rowIndex) {\n        vector<int> result(rowIndex + 1, 1);\n        for (int row = 0; row < rowIndex; row++) {\n            for (int col = row; col > 0; col--) {\n                result[col] += result[col - 1];\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/111-120/Pascal's Triangle.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int> > generate(int numRows) {\n        vector<vector<int> > result;\n        if (numRows <= 0) return result;        \n        for(int i = 0; i < numRows; i++) {\n            vector<int> row(i+1);\n            row[0] = row[i] = 1;\n            for(int j = 1; j < i; j++) \n                row[j] = result[i-1][j-1] + result[i-1][j];\n            result.push_back(row);\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/111-120/Path Sum II.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> pathSum(TreeNode* root, int sum) {\n        vector<vector<int> > paths;\n        vector<int> path;\n        findPaths(root, sum, path, paths);\n        return paths;  \n    }\nprivate:\n    void findPaths(TreeNode* node, int sum, vector<int>& path, vector<vector<int> >& paths) {\n        if (node == nullptr) return;\n        path.push_back(node -> val);\n        if (!(node -> left) && !(node -> right) && sum == node -> val)\n            paths.push_back(path);\n        findPaths(node -> left, sum - node -> val, path, paths);\n        findPaths(node -> right, sum - node -> val, path, paths);\n        path.pop_back();\n    }\n};\n"
  },
  {
    "path": "cpp/111-120/Path Sum.cpp",
    "content": "class Solution {\n    \npublic:\n    bool hasPathSum(TreeNode *root, int sum) {\n        if (root == nullptr) return false;\n        if (root->left == nullptr && root->right == nullptr && sum == root->val) return true;\n        return hasPathSum(root->left,sum - root->val) || hasPathSum(root->right,sum - root->val);\n    }\n};\n"
  },
  {
    "path": "cpp/111-120/Populating Next Right Pointers in Each Node II.cpp",
    "content": "/**\n * Definition for binary tree with next pointer.\n * struct TreeLinkNode {\n *  int val;\n *  TreeLinkNode *left, *right, *next;\n *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    void connect(TreeLinkNode *root) {\n        while (root) {\n            TreeLinkNode *tln = root;\n            TreeLinkNode *prev = new TreeLinkNode(0);\n            TreeLinkNode *temp = prev;\n            \n            while (tln) {\n                \n                if (tln->left) {\n                    prev->next = tln->left;\n                    prev = prev->next;\n                }\n                \n                if(tln->right) {\n                    prev->next = tln->right;\n                    prev = prev->next;\n                }\n                \n                tln = tln->next;\n            }\n            \n            root = temp -> next;\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/111-120/Populating Next Right Pointers in Each Node.cpp",
    "content": "class Solution {\npublic:\n    void connect(TreeLinkNode *root) {\n\n        TreeLinkNode *ancestor = root;\n        while(ancestor)\n        {\n            TreeLinkNode *tln = ancestor;\n            if(!tln->left) break;\n            while(tln)\n            {\n                tln->left->next = tln->right;\n                if(tln->next) tln->right->next = tln->next->left;\n                tln = tln->next;\n            }\n            ancestor = ancestor->left;\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/111-120/Triangle.cpp",
    "content": "class Solution {\npublic:\n    int minimumTotal(vector<vector<int> > &triangle) {\n        \n        // Dp method, record the minimum value for that position\n        vector<int> dp {triangle[0][0]};\n        \n        for (int i = 1; i < triangle.size(); i++) {\n            vector<int> temp(dp.size() + 1);\n            for (int j = 0; j < triangle[i].size(); j++) {\n                if(j == 0) {\n                    temp[j] = triangle[i][j] + dp.front();\n                } else if(j == triangle[i].size()-1) {\n                    temp[j] = triangle[i][j]+dp.back();\n                } else {\n                    temp[j] = triangle[i][j] + min(dp[j-1], dp[j]);\n                }\n            }\n            // swap if faster than dp = temp\n            dp.swap(temp);\n        }\n        \n        return *min_element(dp.begin(), dp.end());\n    }\n};\n"
  },
  {
    "path": "cpp/121-130/Best Time to Buy and Sell Stock II.cpp",
    "content": "class Solution {\npublic:\n    int maxProfit(vector<int> &prices) {\n        \n        if(prices.size() < 2) return 0;\n        \n        int profit(0);\n        \n        for(int i = 0;i < prices.size()-1;i++)\n            if(prices[i+1] > prices[i])\n                profit += (prices[i+1] - prices[i]);\n        \n        return profit;\n    }\n};"
  },
  {
    "path": "cpp/121-130/Best Time to Buy and Sell Stock III.cpp",
    "content": "class Solution {\n    \n\n    \npublic:\n    int maxProfit(vector<int> &prices) {\n        \n        if(prices.size() < 2)\n            return 0;\n        int n = prices.size();\n        vector<vector<int>> p (2, vector<int>(n,0));\n        \n        int minimum(INT_MAX),result(0);\n        for(int i = 0;i < prices.size();i++)\n        {\n            minimum = min(minimum, prices[i]);\n            result = max(result, prices[i]-minimum);\n            p[0][i] = result;\n        }\n        int maximum = INT_MIN;\n        result = 0;\n        for(int i = n-1;i >= 0;i--)\n        {\n            maximum = max(maximum, prices[i]);\n            result = max(result, maximum - prices[i]);\n            p[1][i] = result;\n        }\n        \n        \n        int profit(0);\n        for(int k = 0;k < n;k++)\n        {\n            if(k == n-1)\n                profit = max(profit, p[0][k]);\n            else\n                profit = max(profit, p[0][k]+p[1][k+1]);\n        }\n        \n        return profit;\n        \n    }\n};\n"
  },
  {
    "path": "cpp/121-130/Best Time to Buy and Sell Stock.cpp",
    "content": "class Solution {\npublic:\n    int maxProfit(vector<int> &prices) {\n        \n        int minimum(INT_MAX),result(0);\n        \n        for(vector<int>::iterator it = prices.begin(); it != prices.end(); it++)\n        {\n            minimum = min(minimum, *it);\n            result = max(result, *it-minimum);\n            \n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/121-130/Binary Tree Maximum Path Sum.cpp",
    "content": "class Solution {\n    \n    int dfs(TreeNode *root, int& result) {\n        if (root == nullptr) {\n            return 0;\n        }\n\n        int l = max(0, dfs(root->left, result));\n        int r = max(0, dfs(root->right, result));\n        result = max(result, l + r + root->val);\n\n        return root->val + max(l, r);\n    }\n    \npublic:\n    int maxPathSum(TreeNode *root) {\n        int result = INT_MIN;\n        dfs(root, result);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/121-130/Longest Consecutive Sequence.cpp",
    "content": "class Solution {\npublic:\n    int longestConsecutive(vector<int>& nums) {\n        int longest = 0;\n        unordered_map<int, int> mymap;\n        for (int v : nums) {\n            if (mymap.count(v) > 0) {\n                continue;\n            }\n            mymap[v] = 1;\n            \n            int end = v;\n            int begin = v;\n            if(mymap.count(v + 1) > 0) {\n                end = v + mymap[v + 1];\n            }\n            if(mymap.count(v - 1) > 0) {\n                begin = v - mymap[v - 1];\n            }\n            \n            longest = max(longest, end - begin + 1);\n            mymap[end] = end - begin + 1;\n            mymap[begin] = end - begin + 1;\n        }\n        \n        return longest;\n    }\n};\n"
  },
  {
    "path": "cpp/121-130/Sum Root to Leaf Numbers.cpp",
    "content": "class Solution {\n    \n    int help(TreeNode *root, int pVal)\n    {\n        if(!root->left && !root->right)\n            return root->val + 10*pVal;\n            \n        root->val += 10*pVal;\n        \n        if(root->left && root->right)\n            return help(root->left, root->val)+help(root->right, root->val);\n        else if(root->left && !root->right)\n            return help(root->left, root->val);\n        else\n            return help(root->right, root->val);\n    }\n    \npublic:\n    int sumNumbers(TreeNode *root) {\n        \n        if(!root) return 0;\n        \n        return help(root, 0);\n        \n    }\n};\n"
  },
  {
    "path": "cpp/121-130/Surrounded Regions.cpp",
    "content": "class Solution {\n    \n    void help(vector<vector<char>> &board, int ii, int jj)\n    {\n        if (board[ii][jj] == 0 || board[ii][jj] == 'X') return;\n        board[ii][jj] = 0;\n        queue<pair<int,int>>q;\n        q.push(make_pair(ii,jj));\n        while (!q.empty())\n        {\n            pair<int,int> cur = q.front(); q.pop();\n            pair<int, int> adjs[4] = {{cur.first-1, cur.second}, \n            {cur.first+1, cur.second}, \n            {cur.first, cur.second-1},\n            {cur.first, cur.second+1}};\n            for (int i = 0; i < 4; ++i)\n            {\n                int adjW = adjs[i].first;\n                int adjL = adjs[i].second;\n                if ((adjW >= 0) && (adjW < board.size()) && (adjL >= 0) && (adjL < board[adjW].size()) && (board[adjW][adjL] == 'O'))\n                {\n                    q.push(make_pair(adjW, adjL));\n                    board[adjW][adjL] = 0;\n                }\n            }\n        }\n        return;\n    }\n    \npublic:\n    void solve(vector<vector<char>> &board) {\n        \n        if (board.empty()) return;\n        \n        for (int i = 0;i < board.size();i++)\n        {\n            if (board[i].front() == 'O')\n                help(board, i, 0);\n            if (board[i].back() == 'O')\n                help(board, i, board[i].size()-1);\n        }\n        \n        for (int i = 0;i < board[0].size();i++)\n        {\n            if (board.front()[i] == 'O')\n                help(board, 0, i);\n            if (board.back()[i] == 'O')\n                help(board, board.size()-1, i);\n        }\n        \n        for (int i = 0;i < board.size();i++)\n        {\n            for (int j = 0;j < board[i].size();j++)\n            {\n                if (board[i][j] == 'O')\n                    board[i][j] = 'X';\n                else if (board[i][j] == 0)\n                    board[i][j] = 'O';\n            }\n        }\n        \n    }\n};\n"
  },
  {
    "path": "cpp/121-130/Valid Palindrome.cpp",
    "content": "class Solution {\n\npublic:\n    bool isPalindrome(string s) {\n        int i = 0, j = s.length() - 1;\n        while (i < j) {\n            while (!isalpha(s[i]) && !isdigit(s[i]) && i <= j) {\n                i++;\n            }\n            while (!isalpha(s[j]) && !isdigit(s[j]) && i <= j) {\n                j--;\n            }\n            if (i >= j) {\n                break;\n            }\n            if (toupper(s[i]) != toupper(s[j])) {\n                return false;\n            }\n            \n            i++;\n            j--;\n        }\n        \n        return true;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/121-130/Word Ladder II.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {\n        unordered_set<string> dict(begin(wordList), end(wordList));\n        unordered_map<string, vector<string>> traces;\n        unordered_map<string, int> dis;\n        queue<string> q;\n        dis[beginWord] = 1;\n        q.push(beginWord);\n        while (!q.empty()) {\n            string word = q.front(); q.pop();\n            if (word == endWord) break;\n            for (int i = 0; i < word.size(); i++) {\n                for (int j = 0; j < 26; j++) {\n                    string newWord = word;\n                    newWord[i] = 'a' + j;\n                    if (dict.count(newWord) > 0) {\n                        if( dis.count(newWord) == 0 ) {\n                            dis[newWord] = dis[word] + 1;\n                            vector<string> tmp;\n                            tmp.push_back(word);\n                            traces[newWord] = tmp;\n                            q.push(newWord);\n                        } else if(dis[word] + 1 == dis[newWord]){\n                            traces[newWord].push_back(word);\n                        }\n                    }\n                }\n            }\n        }\n        vector<vector<string>>paths;\n        vector<string> empty;\n        helper(beginWord, endWord, traces, paths, empty);\n        return paths;\n    }\n    \n    void helper(string start, string end, unordered_map<string, vector<string>>& traces, vector<vector<string>>& path, vector<string> onepath)\n    {\n        onepath.insert(onepath.begin(), end);\n        if(start == end)\n            path.push_back(onepath);\n        else {\n            vector<string> node = traces[end];\n            for(int i = 0;i < node.size();i++)\n            {\n                string end = node[i];\n                helper(start, end, traces, path, onepath);\n            }\n        }\n        \n    }\n};\n\n"
  },
  {
    "path": "cpp/121-130/Word Ladder.cpp",
    "content": "\n   \nclass Solution {\npublic:\n    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {\n        unordered_set<string> dict(begin(wordList), end(wordList));\n        queue<string> q;\n        q.push(beginWord);\n        unordered_set<string> visited;\n        visited.insert(beginWord);\n        int step = 1;\n        while (!q.empty()) {\n            int k = q.size();\n            for (int i = 0; i < k; i++) {\n                string word = q.front();\n                q.pop();\n                if (word == endWord) {\n                    return step;\n                }\n                for (int i = 0; i < word.size(); i++) {\n                    char ch = word[i];\n                    for (int j = 0; j < 26; j++) {\n                        word[i] = 'a' + j;\n                        if (visited.count(word) == 0 && dict.count(word) > 0) {\n                            visited.insert(word);\n                            q.push(word);\n                        }\n                    }\n                    word[i] = ch;\n                }\n            }\n            \n            step++;\n        }\n        \n        return 0;\n    }\n};\n"
  },
  {
    "path": "cpp/131-140/Candy.cpp",
    "content": "class Solution {\npublic:\n    int candy(vector<int>& ratings) {\n        int len = ratings.size();\n        vector<int>v(len, 1);\n        \n        for (int i = 1;i < len;i++)\n            if (ratings[i] > ratings[i-1])\n                v[i] = v[i-1] + 1;\n                \n        for (int i = len-1;i > 0;i--)\n             if(ratings[i-1] > ratings[i])\n                v[i-1] = max(v[i]+1, v[i-1]);\n                \n        int result(0);\n        for (auto e : v)\n            result += e;\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/131-140/Clone Graph.cpp",
    "content": "/*\n// Definition for a Node.\nclass Node {\npublic:\n    int val;\n    vector<Node*> neighbors;\n\n    Node() {}\n\n    Node(int _val, vector<Node*> _neighbors) {\n        val = _val;\n        neighbors = _neighbors;\n    }\n};\n*/\nclass Solution {\n    unordered_map<Node*, Node*> dict;\npublic:\n    \n    Node* cloneGraph(Node* node) {\n        //if (!node) return nullptr;\n        if (dict.count(node) == 0) {\n            dict[node] = new Node();\n            dict[node]->val = node->val;\n            for (Node* neighbor : node->neighbors) {\n                dict[node]->neighbors.push_back(cloneGraph(neighbor));\n            }\n        }\n        return dict[node];\n    }\n};\n"
  },
  {
    "path": "cpp/131-140/Copy List with Random Pointer.cpp",
    "content": "class Solution {\npublic:\n    RandomListNode *copyRandomList(RandomListNode *head) {\n        if(!head) return NULL;\n        RandomListNode *n = head;\n        RandomListNode *h = new RandomListNode(0);\n        RandomListNode *result = h;\n        unordered_map<RandomListNode*, RandomListNode*>maps;\n\n        while(head)\n        {\n            RandomListNode *newnode = new RandomListNode(head->label);\n            maps[head] = newnode;\n            h -> next = newnode;\n            h = h->next;\n            head = head->next;\n        }\n        \n        RandomListNode *r = result->next;\n        while(n)\n        {\n            r->random = maps[n->random];\n            r = r->next;\n            n = n->next;\n        }\n        \n        return result->next;\n    }\n};\n"
  },
  {
    "path": "cpp/131-140/Gas Station.cpp",
    "content": "class Solution {\npublic:\n    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {\n        int totalSum(0), start(0), now(0);\n        for (int i = 0;i < gas.size();i++) {\n            int tmp = gas[i] - cost[i];\n            totalSum += tmp;\n            now += tmp;\n            if(now < 0) {\n                start = i+1;\n                now = 0;\n            }\n        }\n        return totalSum >= 0 ? start : -1;\n    }\n};\n"
  },
  {
    "path": "cpp/131-140/Palindrome Partitioning II.cpp",
    "content": "class Solution {\npublic:\n    int minCut(string s) {\n\n        vector<vector<int> >p(s.length(), vector<int>(s.length(), 100000));\n        for(int i = 0;i < s.length();i++)\n            for(int j = 0;j < s.length()-i;j++)\n                if(s[j] == s[j+i])\n                    p[j][j+i] = j+1 <= j+i-1 ? p[j+1][j+i-1] : 0;\n\n\n        for(int j = 1;j < s.length();j++)\n            for(int i = 0;i < j;i++)\n                p[0][j] = min(p[0][j], p[0][i]+p[i+1][j]+1);\n\n\n        return p[0][s.length()-1];\n    }\n};\n"
  },
  {
    "path": "cpp/131-140/Palindrome Partitioning.cpp",
    "content": "class Solution {\n    \n    void dfs(int index, string& s, vector<string>& path, vector<vector<string> >& ret, vector<vector<bool>> &p) {\n        if (index == s.size()) {\n            ret.push_back(path);\n            return;\n        }\n        for(int i = index; i < s.size(); ++i) {\n            if(p[index][i]) {\n                path.push_back(s.substr(index, i - index + 1));\n                dfs(i+1, s, path, ret, p);\n                path.pop_back();\n            }\n        }\n    }\n    \n    \npublic:\n    vector<vector<string>> partition(string s) {\n        vector<vector<string> > ret;\n        if(s.empty()) return ret;\n        \n        vector<vector<bool>>p(s.length(), vector<bool>(s.length(), false));\n        for (int i = 0;i < s.length();i++) {\n            for (int j = 0;j < s.length()-i;j++) {\n                if(i == 0)\n                    p[j][j] = true;\n                else {\n                    if(s[j] == s[j+i])\n                        p[j][j+i] = j+1 <= j+i-1 ? p[j+1][j+i-1] : true;\n                    else\n                        p[j][j+i] = false;\n                }\n            }\n        }\n\n        vector<string> path;\n        dfs(0, s, path, ret, p);\n\n        return ret;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/131-140/Single Number II.cpp",
    "content": "class Solution {\npublic:\n    int singleNumber(vector<int>& nums) {\n        \n        vector<int> v(32, 0);\n        for(auto e : nums)\n        {\n            for(int i = 0;i < 32;i++)\n            {\n                v[i] += e & 1;\n                e = e >> 1;\n            }\n        }\n        \n        int result(0);\n        for(int i = 0;i < 32;i++)\n            if(v[i] % 3 != 0)\n                result |= (1 << i);\n                \n        return result;\n        \n    }\n};\n"
  },
  {
    "path": "cpp/131-140/Single Number.cpp",
    "content": "class Solution {\npublic:\n    int singleNumber(vector<int>& nums) {\n        int r(0);\n        for(auto e : nums)\n            r ^= e;\n        return r;\n    }\n};\n"
  },
  {
    "path": "cpp/131-140/Word Break II.cpp",
    "content": "class Solution {\n    \n    unordered_map<string, vector<string>>m;\n    \n    vector<string> dfs(string s, unordered_set<string>& dict) {\n        if (m.count(s) > 0) return m[s];\n        vector<string> words;\n        int len = s.length();\n        for(int i = 1;i <= len;i++) {\n            string first = s.substr(0, i);\n            unordered_set<string>::const_iterator got = dict.find(first);\n            if (got != dict.end()) {\n                if(i == len)\n                    words.push_back(first);\n                else {\n                    string remain = s.substr(i);\n                    vector<string> remainVec = dfs(remain, dict);\n                    for (int k = 0;k < remainVec.size();k++)\n                        words.push_back(first + \" \" + remainVec[k]);\n                }\n            }\n        }\n        m[s] = words;\n        return words;\n    }\n    \npublic:\n    vector<string> wordBreak(string s, vector<string>& wordDict) {\n        unordered_set<string> dict(begin(wordDict), end(wordDict));\n        return dfs(s, dict);\n    }\n};\n"
  },
  {
    "path": "cpp/131-140/Word Break.cpp",
    "content": "class Solution {\npublic:\n    bool wordBreak(string s, vector<string>& wordDict) {\n        unordered_set<string> dict(begin(wordDict), end(wordDict));\n        vector<bool> p(s.length()+1, false);\n        p[0]=true;\n        for(int i = 0;i < s.length();i++) {\n            for(int j = 0;j <= i;j++) {\n                if(p[j] == true) {\n                    string tmp = s.substr(j,i+1-j);\n                    if (dict.find (tmp) != dict.end()) {\n                        p[i+1] = true;\n                        break;\n                    }\n                }\n            }\n        }\n        return p[s.length()];\n    }\n};\n"
  },
  {
    "path": "cpp/141-150/Binary Tree Postorder Traversal.cpp",
    "content": "class Solution {\npublic:\n    vector<int> postorderTraversal(TreeNode* root) {\n        vector<int> result;\n        if (root == nullptr) return result;\n        stack<TreeNode*> nodes_ready_for_visiting;\n        nodes_ready_for_visiting.emplace(root);\n        \n        while (!nodes_ready_for_visiting.empty())\n        {\n            root = nodes_ready_for_visiting.top();\n            nodes_ready_for_visiting.pop();\n            result.emplace(result.end(), root->val);\n            \n            if (root->left)\n                nodes_ready_for_visiting.emplace(root->left);\n            if (root->right)\n                nodes_ready_for_visiting.emplace(root->right);\n        }\n        reverse(result.begin(), result.end());\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/141-150/Evaluate Reverse Polish Notation.cpp",
    "content": "class Solution {\npublic:\n    int evalRPN(vector<string> &tokens) {\n        stack<int> nums;\n        for (int i = 0; i < tokens.size(); i++) {\n            string s = tokens[i];\n            if (isdigit(s[0]) || s.size() > 1) {\n                nums.push(stoi(s));\n                continue;\n            }\n            int a = nums.top();\n            nums.pop();\n            int b = nums.top();\n            nums.pop();\n            if (s == \"+\") {\n                nums.push(a+b);\n            } else if (s == \"-\") {\n                nums.push(b-a);\n            } else if (s == \"*\") {\n                nums.push(a*b);\n            } else {\n                nums.push(b/a);\n            }\n        }\n        return nums.top();\n    }\n};\n"
  },
  {
    "path": "cpp/141-150/Insertion Sort List.cpp",
    "content": "class Solution {\n    \npublic:\n    ListNode *insertionSortList(ListNode *head) {\n        ListNode result(INT_MIN);\n\n        while (head) {\n            ListNode* iter = &result;\n            while (iter->next && iter->next->val < head->val)\n                iter = iter->next;\n            ListNode* next = head->next;\n            head->next = iter->next;\n            iter->next = head;\n            head = next;\n        }\n\n        return result.next;\n    }\n\n};\n"
  },
  {
    "path": "cpp/141-150/LRU Cache.cpp",
    "content": "class LRUCache {\npublic:\n    LRUCache(int capacity) : _capacity(capacity) {}\n    \n    int get(int key) {\n        auto it = cache.find(key);\n        if (it == cache.end()) return -1;\n        touch(it);\n        return it->second.first;\n    }\n    \n    void set(int key, int value) {\n        auto it = cache.find(key);\n        if (it != cache.end()) touch(it);\n        else {\n            if (cache.size() == _capacity) {\n\t\tcache.erase(used.back());\n\t\tused.pop_back();\n            }\n            used.push_front(key);\n        }\n        cache[key] = { value, used.begin() };\n    }\n    \nprivate:\n    typedef list<int> LI;\n    typedef pair<int, LI::iterator> PII;\n    typedef unordered_map<int, PII> HIPII;\n    \n    void touch(HIPII::iterator it) {\n        int key = it->first;\n        used.erase(it->second.second);\n        used.push_front(key);\n        it->second.second = used.begin();\n    }\n    \n    HIPII cache;\n    LI used;\n    int _capacity;\n};\n"
  },
  {
    "path": "cpp/141-150/Linked List Cycle II.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode *detectCycle(ListNode *head) {\n        if (head == nullptr) return nullptr;\n        \n        ListNode *slow(head), *fast(head);\n        \n        while (fast && fast->next) {\n            slow = slow->next;\n            fast = fast->next->next;\n            if (slow == fast) break;\n        }\n        \n        if (fast == nullptr || fast->next == nullptr)\n            return nullptr;\n        slow = head;\n        while (slow != fast) {\n            slow = slow->next;\n            fast = fast->next;\n        }\n        return slow;\n    }\n};\n"
  },
  {
    "path": "cpp/141-150/Linked List Cycle.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    bool hasCycle(ListNode *head) {\n        if (head == nullptr)\n            return false;\n        \n        ListNode *first = head, *second = head->next;\n        \n        while (second != nullptr) {\n            if (first == second)\n                return true;\n            first = first->next;\n            second = second->next;\n            if (second != nullptr)\n                second = second->next;\n        }\n        \n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/141-150/Max Points on a Line.cpp",
    "content": "class Solution {\npublic:\n    int maxPoints(vector<vector<int>> &points) {\n        if (points.size() <= 2) {\n            return points.size();\n        }\n        \n        int maxNum = 0;\n        \n        for (int i = 0; i < points.size(); i++) {\n            int localmax = 0, overlap = 0;\n            map<pair<int, int>, int> statistic;\n            for (int j = i + 1; j < points.size(); j++) {\n                if (points[j][0] == points[i][0] && points[j][1] == points[i][1]) {\n                    overlap++;\n                    continue;\n                } else {\n                    int x = points[j][0] - points[i][0];\n                    int y = points[j][1] - points[i][1];\n                    int divide = __gcd(x,y);\n                    x /= divide;\n                    y /= divide;\n                    pair<int, int>p(x,y);\n                    statistic[p]++;\n                    localmax = max(statistic[p], localmax);\n                }\n            }\n            maxNum=max(maxNum, localmax + overlap + 1);\n        }\n        \n        return maxNum;\n    }\n};\n"
  },
  {
    "path": "cpp/141-150/Reorder List.cpp",
    "content": "class Solution {\n    \n    ListNode* reverse(ListNode *head)\n    {\n        ListNode* tmp = head->next;\n        ListNode* p = nullptr;\n        head->next = NULL;\n        while (tmp)\n        {\n            p = tmp->next;\n            tmp -> next = head;\n            head = tmp;\n            tmp = p;\n        }\n        return head;\n    }\n    \npublic:\n    void reorderList(ListNode *head) {\n        if (!head || !head->next) return;\n        \n        ListNode *head1 = head;\n        ListNode *head2 = head->next;\n        \n        while (head2 && head2->next) {\n            head1 = head1->next;\n            head2 = head2->next->next;\n        }\n\n        head2 = head1 -> next;\n        head1 -> next = nullptr;\n        head1 = head;\n        head2 = reverse(head2);\n\n        ListNode *tmp = head1 -> next;\n        while (head2){\n            head1 -> next = head2;\n            head1 = head2;\n            head2 = tmp;\n            tmp = head1->next;\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/141-150/Sort List.cpp",
    "content": "class Solution {\n    \npublic:\n    \n    ListNode* merge(ListNode *node1, int n1, ListNode *node2, int n2, ListNode *before)\n    {\n        ListNode *first(node1), *second(node2);\n        int len1(n1), len2(n2);\n        if(node1 -> val > node2 ->val)\n        {\n            first = node2;\n            second = node1;\n            len1 = n2;\n            len2 = n1;\n        }\n        ListNode *head(first), *answer(first);\n        \n        while(1)\n        {\n            if(first->val <= second->val)\n            {\n                if(len1 == 1)\n                {\n                    first -> next = second;\n                    break;\n                }\n                else\n                {\n                    len1--;\n                    head = first;\n                    first = first -> next;\n                    continue;\n                }\n            }\n            \n            else {\n                len2--;\n                ListNode *temp = second;\n                second = second->next;\n                temp->next = first;\n                head->next = temp;\n                head = temp;\n                if(len2 == 0)   break;\n            }\n        }\n        \n        if(before)\n            before->next = answer;\n        ListNode *t = answer;\n        int l = n1+n2;\n        while(l-- > 1)\n            t = t->next;\n        t->next = NULL;\n\n        return t;\n    }\n    \n    int lengthOfList(ListNode *node)\n    {\n        int len = 0;\n        while(node)\n        {\n            len++;\n            node = node->next;\n        }\n        return len;\n    }\n\n    ListNode* find(ListNode* node, int L)\n    {\n        while(node && L > 0)\n        {\n            node = node->next;\n            L--;\n        }\n        return node;\n    }\n    \n    ListNode *sortList(ListNode *head) {\n        int num = 1;\n        int len = lengthOfList(head);\n        ListNode *ans = head;\n        ListNode *tmp = head;\n        while(num < len)\n        {\n            for(int i = num;i > 0&&tmp->next;i--)\n                tmp = tmp->next;\n            if(ans->val > tmp->val) ans = tmp;\n            ListNode *tail = NULL;\n            ListNode *node1(head), *node2(tmp);\n\n            while(node2)\n            {\n                ListNode *nextnode = node2;\n                int p = num;\n                while(nextnode && p > 0)\n                {\n                    nextnode = nextnode->next;\n                    p--;\n                }\n                nextnode = find(node2,num);\n                tail = merge(node1, num, node2, num-p, tail);\n                node1 = nextnode;\n                node2 = find(node1,num);\n                if(node1 || !node2)\n                    tail->next = node1;\n            }\n            \n            head = ans;\n            tmp = head;\n            num *= 2;\n        }\n        return ans;\n    }\n\n};\n"
  },
  {
    "path": "cpp/141-150/Tree Preorder Traversal.cpp",
    "content": "class Solution {\npublic:\n    vector<int> preorderTraversal(TreeNode *root) {\n        vector<int> result;\n        if (root == nullptr) return result;\n        stack<TreeNode*> nodes_ready_for_visiting;\n        nodes_ready_for_visiting.emplace(root);\n        \n        while (!nodes_ready_for_visiting.empty())\n        {\n            root = nodes_ready_for_visiting.top();\n            nodes_ready_for_visiting.pop();\n            result.emplace(result.end(), root->val);\n            \n            if (root->right)\n                nodes_ready_for_visiting.push(root->right);\n            if (root->left)\n                nodes_ready_for_visiting.push(root->left);\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/151-160/Binary Tree Upside Down.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n\npublic:\n\n    TreeNode* upsideDownBinaryTree(TreeNode* root) {\n        if (!root || !root->left) return root;\n        TreeNode* cur_left = root->left;\n        TreeNode* cur_right = root->right;\n        TreeNode* new_root = upsideDownBinaryTree(root->left);\n        cur_left->right = root;\n        cur_left->left = cur_right;\n        root->left = nullptr;\n        root->right = nullptr;\n        return new_root;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/151-160/Find Minimum in Rotated Sorted Array II.cpp",
    "content": "class Solution {\npublic:\n    int findMin(vector<int>& nums) {\n        int i = 0;\n        int j = nums.size() - 1;\n        \n        while (i < j) {\n            int mid = (i + j) / 2;\n            if (nums[mid] < nums[j]) {\n                j = mid;\n            } else if (nums[mid] > nums[j]) {\n                i = mid + 1;\n            } else {\n                j--;\n            }\n        }\n        \n        return nums[i];\n    }\n};\n"
  },
  {
    "path": "cpp/151-160/Find Minimum in Rotated Sorted Array.cpp",
    "content": "class Solution {\npublic:\n    int findMin(vector<int>& nums) {\n        int i = 0;\n        int j = nums.size() - 1;\n        \n        while (i < j) {\n            int mid = (i + j) / 2;\n            if (nums[mid] < nums[j]) {\n                j = mid;\n            } else {\n                i = mid + 1;\n            }\n        }\n        \n        return nums[i];\n    }\n};\n"
  },
  {
    "path": "cpp/151-160/Intersection of Two Linked Lists.cpp",
    "content": "class Solution {\n    \n    int getLen(ListNode *head) {\n        int len(0);\n        while (head) {\n            head = head->next;\n            len++;\n        }\n        return len;\n    }\n    \npublic:\n    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {\n        int len1 = getLen(headA);\n        int len2 = getLen(headB);\n        if (len2 > len1) {\n            swap(headA, headB);\n            swap(len1, len2);\n        }\n        \n        while (len1-- != len2) headA = headA->next;\n        while (headA != headB) {\n            headA = headA->next;\n            headB = headB->next;\n        }\n        return headA;\n    }\n};\n"
  },
  {
    "path": "cpp/151-160/Longest Substring with At Most Two Distinct Characters.cpp",
    "content": "class Solution {\npublic:\n    int lengthOfLongestSubstringTwoDistinct(string s) {\n        int current = 0;\n        int longest = 0;\n        int previouspos = 0;\n        unordered_map<char, int> m;\n        \n        for (int i = 0; i < s.length(); i++) {\n            m[s[i]]++;\n            if (m[s[i]] == 1) {\n                current++;\n            }\n\n            while (current > 2) {\n                char ch = s[previouspos];\n                previouspos++;\n                m[ch]--;\n                if (m[ch] == 0) {\n                    current--;\n                }\n            }\n            \n            longest = max(longest, i - previouspos + 1);\n        }\n        \n        return longest;\n    }\n};\n"
  },
  {
    "path": "cpp/151-160/Maximum Product Subarray.cpp",
    "content": "class Solution {\npublic:\n    int maxProduct(vector<int>& nums) {\n        if (nums.size() == 0) return 0;\n        int maxEndHere = nums[0];\n        int minEndHere = nums[0];\n        int maxSoFar = nums[0];\n\n        for (int i = 1; i < nums.size(); i++) {\n            int num = nums[i];\n            if (num >= 0) {\n                maxEndHere = max(maxEndHere * num, num);\n                minEndHere = min(minEndHere * num, num);\n            } else {\n                int temp = maxEndHere;\n                maxEndHere = max(minEndHere * num, num);\n                minEndHere = min(temp * num, num);\n            }\n            maxSoFar = max(maxEndHere, maxSoFar);\n        }\n        return maxSoFar;\n    }\n};\n"
  },
  {
    "path": "cpp/151-160/Min Stack.cpp",
    "content": "class MinStack {\n    \n    stack<int> s1;\n    stack<int> s2;\n    \npublic:\n    void push(int x) {\n        s1.push(x);\n        if (s2.empty() || s2.top() >= x) s2.push(x);\n    }\n\n    void pop() {\n        int tmp = s1.top();\n        s1.pop();\n        if (tmp == s2.top())\n            s2.pop();\n    }\n\n    int top() {\n        return s1.top();\n    }\n\n    int getMin() {\n        return s2.top();\n    }\n};\n\n/**\n * Your MinStack object will be instantiated and called as such:\n * MinStack obj = new MinStack();\n * obj.push(x);\n * obj.pop();\n * int param_3 = obj.top();\n * int param_4 = obj.getMin();\n */\n"
  },
  {
    "path": "cpp/151-160/Read N Characters Given Read4 II - Call multiple times.cpp",
    "content": "class Solution {\nprivate:\n    char cache[4];\n    int cache_ind = 0;\n    int cache_cnt = 0;\npublic:\n    /**\n     * @param buf Destination buffer\n     * @param n   Number of characters to read\n     * @return    The number of actual characters read\n     */\n    int read(char *buf, int n) {\n        int ind = 0;\n        while (true) {\n            while (cache_cnt > 0 && ind < n) {\n                buf[ind] = cache[cache_ind];\n                ind++;\n                cache_ind++;\n                cache_cnt--;\n            }\n            if (ind == n) {\n                return ind;\n            }\n            cache_ind = 0;\n            cache_cnt = read4(cache);\n            if (cache_cnt == 0) {\n                break;\n            }\n        }\n        return ind;\n    }\n};\n"
  },
  {
    "path": "cpp/151-160/Read N Characters Given Read4.cpp",
    "content": "/**\n * The read4 API is defined in the parent class Reader4.\n *     int read4(char *buf4);\n */\n\nclass Solution {\npublic:\n    int read(char *buf, int n) {\n        int ind = 0;\n        while (ind < n) {\n            char cache[4];\n            int cache_cnt = read4(cache);\n            if (cache_cnt == 0) {\n                break;\n            }\n            int cache_ind = 0;\n            while (cache_cnt > 0 && ind < n) {\n                buf[ind] = cache[cache_ind];\n                cache_ind++;\n                ind++;\n                cache_cnt--;\n            }\n        }\n        return ind;\n    }\n};\n"
  },
  {
    "path": "cpp/151-160/Reverse Words in a String.cpp",
    "content": "class Solution {\npublic:\n    void reverseWords(string &s) {\n        reverse(s.begin(), s.end());\n        int storeIndex(0);\n        for (int i = 0; i < s.size(); i++) {\n            if (s[i] != ' ') {\n                if (storeIndex != 0) s[storeIndex++] = ' ';\n                int j = i;\n                while (j < s.size() && s[j] != ' ') { s[storeIndex++] = s[j++]; }\n                reverse(s.begin() + storeIndex - (j - i), s.begin() + storeIndex);\n                i = j;\n            }\n        }\n        s.resize(storeIndex);\n    }\n};\n"
  },
  {
    "path": "cpp/161-170/Compare Version Numbers.cpp",
    "content": "class Solution {\npublic:\n    int compareVersion(string version1, string version2) {\n        int i(0), j(0);\n        int n1(version1.size()), n2(version2.size());\n        int num1(0), num2(0);\n        \n        while (i<n1 || j<n2) {\n            while (i<n1 && version1[i]!='.') {\n                num1 = num1*10+(version1[i]-'0');\n                i++;\n            }\n            \n            while (j<n2 && version2[j]!='.') {\n                num2 = num2*10+(version2[j]-'0');;\n                j++;\n            }\n            \n            if (num1>num2) return 1;\n            else if (num1 < num2) return -1;\n            \n            num1 = 0;\n            num2 = 0;\n            i++;\n            j++;\n        }\n        return 0;\n    }\n};\n"
  },
  {
    "path": "cpp/161-170/Excel Sheet Column Title.cpp",
    "content": "class Solution {\npublic:\n    string convertToTitle(int n) {\n        return n == 0 ? \"\" : convertToTitle((n-1) / 26) + (char) ((n-1) % 26 + 'A');\n    }\n};\n"
  },
  {
    "path": "cpp/161-170/Find Peak Element.cpp",
    "content": "class Solution {\npublic:\n    int findPeakElement(const vector<int> &num) \n    {\n        int low(0), high(num.size()-1);\n        \n        while(low < high)\n        {\n            int mid1 = (low+high)/2;\n            int mid2 = mid1+1;\n            num[mid1] < num[mid2] ?  low = mid2 : high = mid1;\n        }\n        return low;\n    }\n};\n"
  },
  {
    "path": "cpp/161-170/Fraction to Recurring Decimal.cpp",
    "content": "class Solution {\npublic:\n    string fractionToDecimal(int64_t numerator, int64_t denominator) {\n        bool flag = false;\n        \n        if (numerator > 0 && denominator < 0) {\n            flag = true;\n        } else if (numerator < 0 && denominator > 0) {\n            flag = true;\n        }\n        numerator = abs(numerator);\n        denominator = abs(denominator);\n        \n        int64_t remain = numerator % denominator;\n        int64_t d = numerator/denominator;\n        string result = to_string(d);\n        if (flag) result = \"-\"+result;\n        if (remain == 0)\n            return result;\n        \n        unordered_map<int, int>p;\n        string small = \"\";\n        int index = 0;\n        \n        while (remain > 0) {\n            p[remain] = index;\n            int64_t tmp = remain*10;\n            int64_t digit = tmp/denominator;\n            remain = tmp%denominator;\n            small += to_string(digit);\n            \n            if (p.count(remain) > 0) {\n                small.insert(p[remain], \"(\");\n                small += \")\";\n                break;\n            }\n            index++;\n        }\n\n        return result+\".\"+small;\n    }\n};\n"
  },
  {
    "path": "cpp/161-170/Majority Element.cpp",
    "content": "class Solution {\npublic:\n    int majorityElement(vector<int> &num) {\n        stack<int> s;\n        for(int i = 0;i < num.size();i++)\n        {\n            if(s.empty())\n                s.push(num[i]);\n            else{\n                int t = s.top();\n                if(t != num[i])\n                    s.pop();\n                else\n                    s.push(num[i]);\n            }\n        }\n        return s.top();\n    }\n};\n"
  },
  {
    "path": "cpp/161-170/Maximum Gap.cpp",
    "content": "class Solution {\npublic:\n    int maximumGap(vector<int> &num) {\n        if(num.size() < 2) return 0;\n        \n        int minium = *min_element(num.begin(), num.end());\n        int maxium = *max_element(num.begin(), num.end());\n        \n        int gap = (int)ceil((maxium - minium)*1.0/(num.size()-1));\n        int* maxBucket = new int[num.size()];\n        int* minBucket = new int[num.size()];\n        \n        fill(maxBucket, maxBucket+num.size(), INT_MIN);\n        fill(minBucket, minBucket+num.size(), INT_MAX);\n        \n        for(int i = 0;i < num.size();i++)\n        {\n            int idx = (num[i] - minium)/gap;\n            maxBucket[idx] = max(maxBucket[idx], num[i]);\n            minBucket[idx] = min(minBucket[idx], num[i]);\n        }\n        \n        int MaxGap = -1;\n        int temp = minium;\n        for(int i = 0;i < num.size();i++)\n        {\n            if(maxBucket[i] == INT_MIN)\n                continue;\n            MaxGap = max(MaxGap, minBucket[i] - temp);\n            temp = maxBucket[i];\n        }\n        return MaxGap;\n    }\n};"
  },
  {
    "path": "cpp/161-170/Missing Ranges.cpp",
    "content": "class Solution {\n    \n    inline string get_range(int start, int end) {\n        return start==end? to_string(start) : to_string(start)+\"->\"+to_string(end);\n    }\n    \npublic:\n\n    vector<string> findMissingRanges(vector<int>& nums, int lower, int upper) {\n        vector<string> result;\n        int pre = lower-1;\n        for (int i = 0; i <= nums.size(); i++) {\n            int cur = (i==nums.size()? upper+1:nums[i]);\n            if (cur-pre>=2)\n                result.push_back(get_range(pre+1,cur-1));\n            pre = cur;\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/161-170/One Edit Distance.cpp",
    "content": "class Solution {\n    \npublic:\n    bool isOneEditDistance(string s, string t) {\n        if (abs((int)s.length() - (int)t.length()) >= 2) return false;\n        if (s == t) return false;\n        if (s.length() == t.length()) {\n            int diff(0);\n            for (int i = 0;i < s.length();i++)\n            {\n                if (s[i] != t[i]) diff++;\n                if (diff >= 2) return false;\n            }\n            return true;\n        }\n        if (s.length() > t.length()) return isOneEditDistance(t, s);\n        \n        int i(0), j(0);\n        while (i < s.length() && j < t.length())\n        {\n            if (s[i] == t[j]){\n                i++;\n                j++;\n            } else {\n                j++;\n            }\n        }\n        if (i == s.length() && j == t.length()) return true;\n        if (j == i) return true;\n        return false;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/161-170/Two Sum II - Input array is sorted.cpp",
    "content": "class Solution {\npublic:\n    vector<int> twoSum(vector<int>& numbers, int target) {\n        \n        int i(0), j(numbers.size()-1);\n        vector<int> result;\n        \n        while (i < j)\n        {\n            int sum = numbers[i] + numbers[j];\n            if (sum == target)\n            {\n                result.push_back(i+1);\n                result.push_back(j+1);\n                return result;\n            }\n            sum > target? j-- : i++;\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/161-170/Two Sum III - Data structure design.cpp",
    "content": "class TwoSum {\n    unordered_multiset<int> nums;\npublic:\n    void add(int number) {\n        nums.insert(number);\n    }\n    bool find(int value) {\n        for (int i : nums) {\n            int count = i == value - i ? 1 : 0;\n            if (nums.count(value - i) > count) {\n                return true;\n            }\n        }\n        return false;\n    }\n};\n\n// Your TwoSum object will be instantiated and called as such:\n// TwoSum twoSum;\n// twoSum.add(number);\n// twoSum.find(value);"
  },
  {
    "path": "cpp/171-180/Binary Search Tree Iterator.cpp",
    "content": "class BSTIterator {\n    \n    stack<TreeNode *> s;\n    \npublic:\n    BSTIterator(TreeNode *root) {\n        \n        while(root)\n        {\n            s.push(root);\n            root = root->left;\n        }\n        \n    }\n\n    /** @return whether we have a next smallest number */\n    bool hasNext() {\n        return !s.empty();\n    }\n\n    /** @return the next smallest number */\n    int next() {\n        TreeNode *cur = s.top();\n        s.pop();\n        int val = cur->val;\n        \n        if(cur->right)\n        {\n            cur = cur->right;\n            while(cur)\n            {\n                s.push(cur);\n                cur = cur->left;\n            }\n        }\n        \n        return val;\n    }\n};\n"
  },
  {
    "path": "cpp/171-180/Dungeon Game.cpp",
    "content": "class Solution {\npublic:\n    int calculateMinimumHP(vector<vector<int> > &dungeon) {\n        \n        int M = dungeon.size();\n        int N = dungeon[0].size();\n        \n        vector<vector<int>> v(M, vector<int>(N, 0) );\n        \n        for(int i = M-1;i >= 0;i--) {\n            \n            for(int j = N-1;j >=0;j--) {\n                if(i == M-1 && j == N-1) {\n                    v[i][j] = max(1, 1 - dungeon[i][j]);\n                } else if(i == M-1) {\n                    v[i][j] = max(1, v[i][j+1] - dungeon[i][j]);\n                } else if(j == N-1) {\n                    v[i][j] = max(1, v[i+1][j] - dungeon[i][j]);\n                } else {\n                    v[i][j] = max(1, min(v[i+1][j],v[i][j+1]) - dungeon[i][j]);\n                }\n            }\n        }\n\n        return v[0][0];\n    }\n};\n"
  },
  {
    "path": "cpp/171-180/Excel Sheet Column Number.cpp",
    "content": "class Solution {\npublic:\n    int titleToNumber(string s) {\n        return s.length() == 0 ? 0 : (s.back() - 'A' + 1 ) + 26*titleToNumber(s.substr(0,s.length()-1));\n    }\n};\n"
  },
  {
    "path": "cpp/171-180/Factorial Trailing Zeroes.cpp",
    "content": "class Solution {\npublic:\n    int trailingZeroes(int n) {\n        return n == 0 ? 0 : n/5 + trailingZeroes(n/5);\n    }\n};\n"
  },
  {
    "path": "cpp/171-180/Largest Number.cpp",
    "content": "class Solution {\npublic:\n    string largestNumber(vector<int>& nums) {\n        string res;\n        bool flag = false;\n        vector<string> numStr;\n        for (int num : nums) {\n            if (num != 0) flag = true;\n            numStr.emplace_back(to_string(num));\n        }\n        auto cmp = [](const string& i, const string& j) {\n            return i + j > j + i;\n        };\n        sort(numStr.begin(), numStr.end(), cmp);\n        for (const string& str : numStr) {\n            res += str;\n        }\n        return flag ? res : \"0\";\n    }\n};\n"
  },
  {
    "path": "cpp/181-190/Best Time to Buy and Sell Stock IV.cpp",
    "content": "class Solution {\n    \n    int help(vector<int> &prices)\n    {\n        int res(0);\n        for(int i = 0;i < prices.size()-1;i++)\n            if(prices[i+1] > prices[i])\n                res += (prices[i+1] - prices[i]);\n        return res;\n    }\n    \npublic:\n    int maxProfit(int k, vector<int> &prices) {\n        \n        int len = prices.size();\n        if(len < 2) return 0;\n        if(k >= len/2) return help(prices);\n    \n        vector<vector<int> >p(k+1, vector<int>(len+1, 0));\n        for(int i = 1;i <= k;i++)\n        {\n            int tmp = -prices[0];\n            for(int j = 1;j <= len;j++)\n            {\n                p[i][j] = max(p[i][j-1], tmp+prices[j-1]);\n                tmp = max(tmp, p[i-1][j-1] - prices[j-1]);\n            }\n        }\n        \n        return p[k][len];\n    }\n};\n"
  },
  {
    "path": "cpp/181-190/Repeated DNA Sequences.cpp",
    "content": "class Solution {\n    \nprivate:\n    inline int change(char ch) {\n        if (ch == 'A') return 0;\n        if (ch == 'C') return 1;\n        if (ch == 'G') return 2;\n        return 3;\n    }\n\npublic:\n    vector<string> findRepeatedDnaSequences(string s) {\n        unordered_map<int, int> m;\n        int len = s.length();\n        vector<string>results;\n        \n        int tmp(0);\n        \n        for(int i = 0;i < 10;i++) {\n            tmp *= 4;\n            tmp += change(s[i]);\n        }\n        m[tmp] = 1;\n\n        for (int i = 1; i <= len-10; i++) {\n            tmp = tmp - change(s[i-1])*262144;\n            tmp *= 4;\n            tmp += change(s[i+9]);\n            if (m[tmp] == -1) continue;\n            else if(m[tmp] == 1) { results.push_back(s.substr(i,10)); m[tmp] = -1; }\n            else m[tmp] = 1;\n        }\n\n        return results;\n    }\n};\n"
  },
  {
    "path": "cpp/181-190/Reverse Bits.cpp",
    "content": "class Solution {\npublic:\n    uint32_t reverseBits(uint32_t n) {\n        uint32_t result(0);\n        for(int i = 0; i < 32; i++)\n            result = (result<<1) + (n>>i &1);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/181-190/Reverse Words in a String II.cpp",
    "content": "class Solution {\npublic:\n    void reverseWords(string &s) {\n        reverse(s.begin(), s.end());\n        int storeIndex(0);\n        for (int i = 0; i < s.size(); i++) {\n            if (s[i] != ' ') {\n                if (storeIndex != 0) s[storeIndex++] = ' ';\n                int j = i;\n                while (j < s.size() && s[j] != ' ') { s[storeIndex++] = s[j++]; }\n                reverse(s.begin() + storeIndex - (j - i), s.begin() + storeIndex);\n                i = j;\n            }\n        }\n        s.resize(storeIndex);\n    }\n};\n"
  },
  {
    "path": "cpp/181-190/Rotate Array.cpp",
    "content": "class Solution {\npublic:\n    void rotate(vector<int>& nums, int k) {\n        \n        int base(0);\n        int n = nums.size();\n        \n        for(; k %= n; n -= k)\n            for(int i = 0;i < k;i++)\n                swap(nums[base++], nums[n-k+base]);\n        \n    }\n};\n"
  },
  {
    "path": "cpp/191-200/Binary Tree Right Side View.cpp",
    "content": "#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nusing namespace std;\n\n\nstruct TreeNode {\n    int val;\n    TreeNode *left;\n    TreeNode *right;\n    TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n};\n\nclass Solution {\npublic:\n    vector<int> rightSideView(TreeNode *root) {\n        vector<int> r;\n        if(root == NULL) return r;\n        \n        vector<TreeNode*>node;\n        node.push_back(root);\n        \n        while(node.size() > 0)\n        {\n            r.push_back(node.back()->val);\n            \n            size_t len = node.size();\n            for(int i = 0;i < len;i++)\n            {\n                if(node[i]->left)node.push_back(node[i]->left);\n                if(node[i]->right)node.push_back(node[i]->right);\n            }\n            \n            node.erase(node.begin(), node.begin()+len);\n        }\n        \n        return r;\n    }\n    \n};\n\nint main()\n{\n    Solution s;\n    \n    struct TreeNode* root = new TreeNode(1);\n    root->left = new TreeNode(2);\n    root->right = new TreeNode(3);\n    root->left->left = new TreeNode(4);\n    root->left->right = new TreeNode(5);\n    root->right->left = new TreeNode(6);\n    root->right->right = new TreeNode(7);\n    root->right->left->right = new TreeNode(8);\n    \n    cout << s.rightSideView(root).size();\n    return 0;\n}"
  },
  {
    "path": "cpp/191-200/House Robber.cpp",
    "content": "class Solution {\npublic:\n    int rob(vector<int> &num) {\n        if (num.empty()) return 0;\n        \n        int p[num.size()];\n        p[0] = num[0];\n        p[1] = max(num[0], num[1]);\n        \n        for (int i = 2;i < num.size();i++)\n            p[i] = max(p[i-2] + num[i], p[i-1]);\n        return p[num.size()-1];\n    }\n};\n"
  },
  {
    "path": "cpp/191-200/Number of 1 Bits.cpp",
    "content": "class Solution {\npublic:\n    int hammingWeight(uint32_t n) {\n        int hamming_weight(0);\n        while (n > 0) {\n            n = n & (n-1);\n            hamming_weight++;\n        }\n        return hamming_weight;\n    }\n};\n"
  },
  {
    "path": "cpp/191-200/Number of Islands.cpp",
    "content": "class Solution {\n    \n    inline bool valid(int i, int j) {\n        if (i >= 0 && j >= 0 && i < M && j < N) return true;\n        return false;\n    }\n    \n    void mark(vector<vector<char>> &grid, int i, int j) {\n        if (grid[i][j] == '0') return;\n        grid[i][j] = '0';\n        if (valid(i+1,j)) mark(grid, i+1, j);\n        if (valid(i-1,j)) mark(grid, i-1, j);\n        if (valid(i,j+1)) mark(grid, i, j+1);\n        if (valid(i,j-1)) mark(grid, i, j-1);\n    }\n    \n    size_t M;\n    size_t N;\npublic:\n    \n    int numIslands(vector<vector<char>> &grid) {\n        int result(0);\n        if (grid.empty() || grid[0].empty()) return 0;\n        M = grid.size();\n        N = grid[0].size();\n        \n        for (int i = 0;i < M;i++) {\n            for (int j = 0;j < N;j++) {\n                if(grid[i][j] == '1') {\n                    result++;\n                    mark(grid, i, j);\n                }\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/191-200/Reverse Bits.cpp",
    "content": "#include <iostream>\n#include <unordered_map>\n#include <vector>\n\nusing namespace std;\n\nclass Solution {\npublic:\n    uint32_t reverseBits(uint32_t n) {\n        \n        uint32_t r(0);\n        \n        for(int i = 0;i < 32;i++)\n            r += ((n >> i) & 1) * (1 << (31-i));\n        \n        return r;\n    }\n    \n};\n\nint main()\n{\n    Solution s;\n    \n    cout << s.reverseBits(43261596);\n}"
  },
  {
    "path": "cpp/201-210/Bitwise AND of Numbers Range.cpp",
    "content": "class Solution {\n    \n    int maxBit(int num) {\n        int ans = 0;\n        while(num > 0) {\n            num = num >> 1;\n            if(ans == 0) ans = 1;\n            else ans *= 2;\n        }\n        return ans;\n    }\n    \npublic:\n    int rangeBitwiseAnd(int m, int n) {\n        if(m == 0) return 0;\n        \n        int m_maxbit = maxBit(m);\n        int n_maxbit = maxBit(n);\n        if(m_maxbit != n_maxbit) return 0;\n        return m_maxbit + rangeBitwiseAnd(m - m_maxbit, n - n_maxbit);\n    }\n};\n"
  },
  {
    "path": "cpp/201-210/Count Primes.cpp",
    "content": "#include <iostream>\n#include <string>\n#include <vector>\n#include <cmath>\n\nusing namespace std;\n\n\nclass Solution {\npublic:\n    int countPrimes(int n) {\n        \n        if(n < 3) return 0;\n        \n        int limit = sqrt(n);\n        int r(n-2);\n        \n        bool *A = new bool[n+1];\n        memset(A, true, n+1);\n        \n        \n        for(int i = 2;i <= limit;i++)\n        {\n            if(A[i] == true)\n            {\n                for(int j = i*i;j < n;j += i)\n                {\n                    if(A[j] == true) r--;\n                    A[j] = false;\n                }\n            }\n            \n        }\n        return r;\n    }\n};\n\nint main()\n{\n    Solution s;\n    cout << s.countPrimes(2);\n}"
  },
  {
    "path": "cpp/201-210/Course Schedule II.cpp",
    "content": "struct Node {\n    int state;\n    vector<int> edges;\n    Node() : state(0) { }\n};\n\nclass Solution {\n    \n    vector<Node>  Nodes;\n    \n    bool DFS_VISIT(int u, vector<int>& v) {\n        Nodes[u].state = 1;\n        for (int i = 0;i < Nodes[u].edges.size();i++) {\n            int num = Nodes[u].edges[i];\n            if (Nodes[num].state == 0) {\n                bool hascircle = !DFS_VISIT(num, v);\n                if(hascircle) return false;\n            } else if (Nodes[num].state == 1) {\n                return false;\n            }\n        }\n        Nodes[u].state = 2;\n        v.push_back(u);\n        return true;\n    }\n    \npublic:\n    vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) {\n        vector<int>orders;\n        Nodes.resize(numCourses);\n        \n        for (int i = 0;i < prerequisites.size();i++)\n            Nodes[prerequisites[i].first].edges.push_back(prerequisites[i].second);\n        \n        for (int i = 0;i < numCourses;i++) {\n            if (Nodes[i].state != 0) continue;\n            bool hascircle = !DFS_VISIT(i, orders);\n            if (hascircle) return vector<int>();\n        }\n        return orders;\n    }\n};\n"
  },
  {
    "path": "cpp/201-210/Course Schedule.cpp",
    "content": "struct Node {\n    int state;\n    vector<int> edges;\n    Node() : state(0) { }\n};\n \nclass Solution {\n\n    vector<struct Node>  Nodes;\n    \n    bool dfs_visit(int u) {\n        Nodes[u].state = 1;\n        for (int i = 0;i < Nodes[u].edges.size();i++) {\n            int num = Nodes[u].edges[i];\n            if(Nodes[num].state == 0) {\n                bool hascircle = !dfs_visit(num);\n                if(hascircle) return false;\n            } else if(Nodes[num].state == 1) {\n                return false;\n            }\n        }\n        Nodes[u].state = 2;\n        return true;\n    }\n    \npublic:\n    bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) {\n        Nodes.resize(numCourses);\n        for (int i = 0;i < prerequisites.size();i++)\n            Nodes[prerequisites[i].first].edges.push_back(prerequisites[i].second);\n        \n        for (int i = 0;i < numCourses;i++) {\n            bool hascircle = !dfs_visit(i);\n            if(hascircle) return false;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/201-210/Happy Number.cpp",
    "content": "class Solution {\n    \n    int SumSquare(int n)\n    {\n        int r(0);\n        while(n > 0)\n        {\n            int tmp = n%10;\n            n = (n - tmp)/10;\n            r += tmp*tmp;\n        }\n        return r;\n    }\n    \npublic:\n    bool isHappy(int n) {\n        set<int> _set;\n        \n        while(true)\n        {\n            if (_set.count(n) == 1)\n                return false;\n            if (n == 1) return true;\n            _set.insert(n);\n            n = SumSquare(n);\n        }\n        return false;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/201-210/Implement Trie (Prefix Tree).cpp",
    "content": "struct TrieNode {\n    TrieNode *nodes[26];\n    bool word;\n    // Initialize your data structure here.\n    TrieNode(): word(false) {\n        memset(nodes, 0, sizeof(nodes));\n    }\n};\n\nclass Trie {\n    \npublic:\n    Trie() {\n        root = new TrieNode();\n    }\n    \n    // Inserts a word into the trie.\n    void insert(const string& s) {\n        TrieNode *tmp = root;\n        for(char ch : s) {\n            int index = ch - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                tmp->nodes[index] = new TrieNode();\n            }\n            tmp = tmp->nodes[index];\n        }\n        tmp->word = true;\n    }\n    \n    // Returns if the word is in the trie.\n    bool search(const string& key) const {\n        TrieNode *tmp = root;\n        for(char ch : key) {\n            int index = ch - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                return false;\n            }\n            tmp = tmp->nodes[index];\n        }\n        return tmp->word;\n    }\n    \n    // Returns if there is any word in the trie\n    // that starts with the given prefix.\n    bool startsWith(const string& prefix) const {\n        TrieNode *tmp = root;\n        for(char ch : prefix) {\n            int index = ch - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                return false;\n            }\n            tmp = tmp->nodes[index];\n        }\n        return true;\n    }\n    \nprivate:\n    TrieNode* root;\n};\n"
  },
  {
    "path": "cpp/201-210/Isomorphic Strings.cpp",
    "content": "class Solution {\npublic:\n    bool isIsomorphic(string s, string t) { \n        map<char, char>_m;\n        bool _p[256] = {false};\n        int len1 = s.length();\n        for (int i = 0;i < len1;i++) {\n            char c1 = s[i];\n            char c2 = t[i];\n            if (_m.count(c1) == 0) {\n                if(_p[c2]) return false;\n                _m[c1] = c2;\n                _p[c2] = true;\n            } else {\n                if (_m[c1] != c2) \n                    return false;\n            }\n        }\n        return true;\n        \n    }\n};\n"
  },
  {
    "path": "cpp/201-210/Minimum Size Subarray Sum.cpp",
    "content": "class Solution {\npublic:\n    int minSubArrayLen(int s, vector<int>& nums) {\n        \n        int i(0),j(0),sum(0);\n        int len(INT_MAX);\n        nums.push_back(-1);\n        \n        while (j < nums.size())\n        {\n            if (sum >= s)\n            {\n                len = min(len, j-i);\n                sum -= nums[i];\n                i++;\n            } else {\n                sum += nums[j];\n                j++;\n            }\n            \n        }\n        \n        if (len == INT_MAX) return 0;\n        return len;\n    }\n};\n"
  },
  {
    "path": "cpp/201-210/Remove Linked List Elements.cpp",
    "content": "class Solution {\npublic:\n    ListNode* removeElements(ListNode* head, int val) {\n        ListNode* res = new ListNode(1);\n        res->next = head;\n        ListNode* backup = res;\n        \n        //res -> head -> head->next\n        while (head) {\n            if (head->val == val)\n                res->next = head->next;\n            else \n                res = head;\n            head = head->next;\n        }\n        \n        return backup->next;\n    }\n};\n"
  },
  {
    "path": "cpp/201-210/Reverse Linked List.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* reverseList(ListNode* head) {\n        ListNode *tmp(nullptr), *prev(nullptr);\n        while (head != nullptr) {\n            tmp = head->next;\n            head->next = prev;\n            prev = head;\n            head = tmp;\n        }\n        return prev;\n    }\n};\n"
  },
  {
    "path": "cpp/211-220/Add and Search Word - Data structure design.cpp",
    "content": "class TrieNode {\n    \npublic:\n    TrieNode *nodes[26];\n    bool word;\n    // Initialize your data structure here.\n    TrieNode() {\n        word = false;\n        for(int i = 0;i < 26;i++)\n            nodes[i] = nullptr;\n    }\n};\n\nclass Trie {\n    \n    bool _search(string word, int offset, TrieNode *node) {\n        if (node == nullptr) return false;\n        if (offset == word.length()) return node->word;\n        \n        if (word[offset] == '.') {\n            for (int j = 0; j < 26; j++) {\n                bool fff = _search(word, offset+1, node->nodes[j]);\n                if (fff) return true;\n            }\n            return false;\n        } else {\n            return _search(word, offset+1, node->nodes[word[offset]-'a']);\n        }\n    }\n    \npublic:\n    Trie() {\n        root = new TrieNode();\n    }\n    \n    // Inserts a word into the trie.\n    void insert(string s) {\n        TrieNode *tmp = root;\n        for (int i = 0; i < s.length(); i++) {\n            int index = s[i] - 'a';\n            if(tmp->nodes[index] == nullptr)\n                tmp->nodes[index] = new TrieNode();\n            tmp = tmp->nodes[index];\n        }\n        tmp->word = true;\n    }\n    \n    // Returns if the word is in the trie.\n    bool search(string word) {\n        return _search(word, 0, root);\n    }\n    \nprivate:\n    TrieNode* root;\n};\n\nclass WordDictionary {\n    \n    Trie trie;\n    \npublic:\n\n    // Adds a word into the data structure.\n    void addWord(string word) {\n        trie.insert(word);\n    }\n\n    // Returns if the word is in the data structure. A word could\n    // contain the dot character '.' to represent any one letter.\n    bool search(string word) {\n        return trie.search(word);\n    }\n};\n\n// Your WordDictionary object will be instantiated and called as such:\n// WordDictionary wordDictionary;\n// wordDictionary.addWord(\"word\");\n// wordDictionary.search(\"pattern\");\n"
  },
  {
    "path": "cpp/211-220/Combination Sum III.cpp",
    "content": "class Solution {\n    \n    void help(vector<int>& now, int index, int num, int target, vector<vector<int>>& results) {\n        if (num == 0) {\n            return;\n        }\n        for (int i = index; i <= 9; i++) {\n            if (i < target) {\n                now.push_back(i);\n                help(now, i+1, num-1, target-i, results);\n                now.pop_back();\n            } else if (i == target && num == 1) {\n                now.push_back(i);\n                results.push_back(now);\n                now.pop_back();\n            }\n        }\n        \n    }\n    \npublic:\n    vector<vector<int>> combinationSum3(int k, int n) {\n        vector<vector<int>> results;\n        vector<int>tmp;\n        help(tmp, 1, k, n, results);\n        \n        return results;\n    }\n};\n"
  },
  {
    "path": "cpp/211-220/Contains Duplicate II.cpp",
    "content": "class Solution {\npublic:\n    bool containsNearbyDuplicate(vector<int>& nums, int k) \n    {\n        unordered_map<int,int> m;\n        for (int i = 0; i < nums.size(); i++)\n        {\n            if (m.find(nums[i]) != m.end() && i - m[nums[i]] <= k)return true;\n            else m[nums[i]] = i;\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/211-220/Contains Duplicate III.cpp",
    "content": "class Solution {\npublic:\n    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {\n        set<long> window; // set is ordered automatically\n        for (int i = 0; i < nums.size(); i++) {\n            if (i > k) window.erase(nums[i-k-1]); // keep the set contains nums i j at most k\n            // -t <= x - nums[i] <= t;\n            auto pos = window.lower_bound((long)nums[i] - (long)t); // x >= nums[i] - t\n            if (pos != window.end() && *pos - nums[i] <= t) // x <= nums[i] + t\n                return true;\n            window.insert(nums[i]);\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/211-220/Contains Duplicate.cpp",
    "content": "class Solution {\npublic:\n    bool containsDuplicate(std::vector<int>& nums) {\n        std::sort(nums.begin(), nums.end());\n        for (int i = 1; i < nums.size(); ++i)\n            if (nums[i] == nums[i - 1])\n                return true;\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/211-220/House Robber II.cpp",
    "content": "class Solution {\npublic:\n    int rob(vector<int>& nums) {\n        \n        if (nums.size() == 0)\n            return 0;\n        if (nums.size() == 1)\n            return nums[0];\n\n        int pre1(0), cur1(0);\n        for (int i = 0; i < nums.size() - 1; ++ i)\n        {\n            int temp = pre1;\n            pre1 = cur1;\n            cur1 = max(temp + nums[i], pre1);\n        }\n\n        int pre2(0), cur2(0);\n        for (int i = 1; i < nums.size(); ++ i)\n        {\n            int temp = pre2;\n            pre2 = cur2;\n            cur2 = max(temp + nums[i], pre2);\n        }\n\n        return max(cur1, cur2);\n    }\n};\n"
  },
  {
    "path": "cpp/211-220/Kth Largest Element in an Array.cpp",
    "content": "class Solution {\n    \n    int kthSmallest(vector<int>& arr, int l, int r, int k)\n    {\n        if (k > 0 && k <= r - l + 1)\n        {\n            int pos = randomPartition(arr, l, r);\n        \n            if (pos-l == k-1)\n                return arr[pos];\n            else if (pos-l > k-1)\n                return kthSmallest(arr, l, pos-1, k);\n            else\n                return kthSmallest(arr, pos+1, r, k-pos+l-1);\n        }\n        return INT_MAX;\n    }\n\n    int partition(vector<int>& arr, int l, int r)\n    {\n        int x = arr[r], i = l;\n        for (int j = l; j <= r - 1; j++)\n        {\n            if (arr[j] <= x)\n            {\n                swap(arr[i], arr[j]);\n                i++;\n            }\n        }\n        swap(arr[i], arr[r]);\n        return i;\n    }\n\n    int randomPartition(vector<int>& arr, int l, int r)\n    {\n        int n = r-l+1;\n        int pivot = rand() % n;\n        swap(arr[l + pivot], arr[r]);\n        return partition(arr, l, r);\n    }\n    \npublic:\n    int findKthLargest(vector<int>& nums, int k) {\n        return kthSmallest(nums, 0, nums.size()-1, nums.size()-k+1);\n    }\n};\n"
  },
  {
    "path": "cpp/211-220/Shortest Palindrome.cpp",
    "content": "class Solution {\n    \nprivate:\n    string preProcess(string s) {\n        int n = s.length();\n        if (n == 0) return \"^$\";\n        string ret = \"^\";\n        for (int i = 0; i < n; i++)\n        ret += \"#\" + s.substr(i, 1);\n        \n        ret += \"#$\";\n        return ret;\n    }\n    \npublic:\n    string shortestPalindrome(string s) {\n        \n        string T = preProcess(s);\n        int n = T.length();\n        int P[n];\n        int c = 0,r = 0;\n        \n        for(int i = 1;i < n;i++) {\n            int mirror_i = 2*c-i;\n            P[i] = r > i ? min(P[mirror_i], r-i) : 0;\n            \n            while (T[i + 1 + P[i]] == T[i - 1 - P[i]])\n            P[i]++;\n            \n            if (i + P[i] > r) {\n                c = i;\n                r = i + P[i];\n            }\n        }\n        \n        int maxLen = 0;\n        int centerIndex = 0;\n        for (int i = 1; i < n-1; i++) {\n            if (1==i-P[i]) maxLen = P[i];\n        }\n        string temp = s.substr(maxLen);\n        reverse(temp.begin(),temp.end());\n        return temp+s;\n    }\n    \n    \n};\n"
  },
  {
    "path": "cpp/211-220/The Skyline Problem.cpp",
    "content": "class Solution {\npublic:\n    vector<pair<int, int>> getSkyline(vector<vector<int>>& buildings) {\n        vector<pair<int, int> > ret;\n        auto cmp = [&](const pair<int, int> &a, const pair<int, int> &b){ return a.first >= b.first; };\n        priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> points(cmp);\n        for(const auto& e : buildings) {\n            points.push(make_pair(e[0], e[2]));\n            points.push(make_pair(e[1], e[2] * -1));\n        }\n        multiset<int, std::greater<int>> sky;\n        sky.insert(0);\n        while (!points.empty()){\n            int last_height = *sky.begin();\n            int cur = points.top().first;\n            while (!points.empty() && points.top().first == cur){\n                int height = points.top().second;\n                if (height > 0){\n                    sky.insert(height);\n                }else{\n                    sky.erase(sky.find(height * -1));\n                }\n                points.pop();\n            }\n            if (*sky.begin() != last_height){\n                ret.push_back(make_pair(cur, *sky.begin()));\n            }\n        }\n        return ret;\n    }\n};\n"
  },
  {
    "path": "cpp/211-220/Word Search II.cpp",
    "content": "const int ALPHA_NUM = 26;\n\nstruct TrieNode{\n     TrieNode* childs[ALPHA_NUM];\n     TrieNode* father;\n     char ch;\n     bool isEndOfWord;\n     TrieNode() :isEndOfWord(false), father(NULL), ch(0)\n     {\n         fill_n(childs, ALPHA_NUM, nullptr);\n     }\n };\n\n\n class Solution {\n     TrieNode *root;\n     unordered_set<TrieNode *> visitedNodes;\n     vector<string> res;\n     \n public:\n     Solution(){\n         root = new TrieNode();\n     }\n     \n     void insert(string word){\n         TrieNode *curnode = root;\n         for (auto ch : word)\n         {\n             int curidx = ch - 'a';\n             if (curnode->childs[curidx] == NULL)\n             {\n                 curnode->childs[curidx] = new TrieNode();\n                 curnode->childs[curidx]->father = curnode;\n                 curnode->childs[curidx]->ch = ch;\n             }\n             curnode = curnode->childs[curidx];\n         }\n         curnode->isEndOfWord = true;\n     }\n     \n     string getWord(TrieNode *curnode){\n         string res = \"\";\n         while (curnode->father != NULL)\n         {\n             res.push_back(curnode->ch);\n             curnode = curnode->father;\n         }\n         reverse(res.begin(), res.end());\n         return res;\n     }\n     \n     void DFS(vector<vector<char>>& board, int r, int c, TrieNode *curnode){\n\n         if (curnode->isEndOfWord)\n         {\n             if (visitedNodes.find(curnode) == visitedNodes.end())\n             {\n                 visitedNodes.insert(curnode);\n                 res.push_back(getWord(curnode));\n             }\n         }\n         \n         pair<int, int> pos[4] = {{0,1},{0,-1},{1,0},{-1,0}};\n         \n         for(int i = 0;i < 4;i++)\n         {\n             int nr = r + pos[i].first;\n             int nc = c + pos[i].second;\n             if(nr >= 0 && nr < board.size() && nc >= 0 && nc < board[0].size() && board[nr][nc] != '-')\n             {\n                 int curidx = board[nr][nc] - 'a';\n                 if (curnode->childs[curidx] != NULL)\n                 {\n                     board[nr][nc] = '-';\n                     DFS(board, nr, nc, curnode->childs[curidx]);\n                     board[nr][nc] = curidx + 'a';\n                 }\n             }\n         }\n     }\n     \n     vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {\n         for (int i = 0;i < words.size();i++)\n             insert(words[i]);\n             \n         for (int j = 0; j < board.size(); ++j)\n         {\n             for (int k = 0; k < board[j].size(); ++k)\n             {\n                 int curidx = board[j][k] - 'a';\n                 if (root->childs[curidx] != NULL)\n                 {\n                     board[j][k] = '-';\n                     DFS(board, j, k, root->childs[curidx]);\n                     board[j][k] = curidx + 'a';\n                 }\n             }\n         }\n         return res;\n     }\n };\n"
  },
  {
    "path": "cpp/221-230/Basic Calculator II.cpp",
    "content": "class Solution {\n    \n    void apply(stack<int>& s, stack<char>& symbol) {\n        char c = symbol.top();symbol.pop();\n        int b = s.top();s.pop();\n        int a = s.top();s.pop();\n        if (c == '+') s.push(a+b);\n        else if (c == '-') s.push(a-b);\n        else if (c == '*') s.push(a*b);\n        else s.push(a/b);\n    }\n    \npublic:\n    int calculate(string s) {\n        stack<char> symbol;\n        stack<int>ss;\n        int v = 0;\n        bool number = false;\n        for (char e : s) {\n            if (number && !isdigit(e)) {\n                ss.push(v);\n                v = 0;\n                number = false;\n            }\n            \n            if (e == ' ') continue;\n            if (isdigit(e)) {\n                v = 10*v + (e-'0');\n                number = true;\n            } else if (e == '+' || e == '-') {\n                while (!symbol.empty()) {\n                    apply(ss, symbol);\n                }\n                symbol.push(e);\n            } else if (e == '*' || e == '/') {\n                if (!symbol.empty()) {\n                    if (symbol.top() == '*' || symbol.top() == '/') {\n                        apply(ss, symbol);\n                    }\n                }\n                symbol.push(e);\n            }\n        }\n        \n        if (number)\n            ss.push(v);\n        \n        while (!symbol.empty()) {\n            apply(ss, symbol);\n        }\n        \n        return ss.top();\n    }\n};\n"
  },
  {
    "path": "cpp/221-230/Basic Calculator.cpp",
    "content": "class Solution {\n    \n    void apply(stack<int>& s, stack<char>& symbol) {\n        char c = symbol.top();\n        symbol.pop();\n        int b = s.top();s.pop();\n        int a = s.top();s.pop();\n        if(c == '+') s.push(a+b);\n        else s.push(a-b);\n    }\n    \npublic:\n    int calculate(string s) {\n        s = \"(\" + s + \")\";\n        \n        stack<char> symbol;\n        stack<int> nums;\n        int v = 0;\n        bool number = false;\n        for (char e : s) {\n            if (number && !isdigit(e)) {\n                nums.push(v);\n                v = 0;\n                number = false;\n            }\n            \n            if (e == ')') {\n                while (symbol.top() != '(') {\n                    apply(nums, symbol);\n                }\n                symbol.pop();\n            } else if (e == '(') {\n                symbol.push('(');\n            } else if (isdigit(e)) {\n                v = 10*v + (e-'0');\n                number = true;\n            } else if (e == '+' || e == '-') {\n                if (!symbol.empty() && symbol.top() != '(') {\n                    apply(nums, symbol);\n                }\n                symbol.push(e);\n            }\n        }\n\n        return nums.top();\n    }\n};\n"
  },
  {
    "path": "cpp/221-230/Count Complete Tree Nodes.cpp",
    "content": "class Solution {\n    \npublic:\n    int countNodes(TreeNode* root) {\n        \n        if(!root) return 0;\n        \n        int lh(0),rh(0);\n        \n        TreeNode *l(root), *r(root);\n        \n        while(l) {\n            lh++;\n            l = l->left;\n        }\n        \n        while(r) {\n            rh++;\n            r = r->right;\n        }\n        \n        if(lh == rh) return pow(2, lh) - 1;\n        else return 1 + countNodes(root->left) + countNodes(root->right);\n    }\n};"
  },
  {
    "path": "cpp/221-230/Implement Stack using Queues.cpp",
    "content": "class Stack {\n    \n    queue<int> q1;\n    queue<int> q2;\n    int v;\n    \npublic:\n    // Push element x onto stack.\n    void push(int x) {\n        if (!q1.empty())\n            q1.push(x);\n        else\n            q2.push(x);\n        v = x;\n    }\n\n    // Removes the element on top of the stack.\n    void pop() {\n        if (!q1.empty())\n        {\n            while (!q1.empty())\n            {\n                int tmp = q1.front();\n                if (q1.size() > 1) q2.push(tmp);\n                if (q1.size() == 2) v= tmp;\n                q1.pop();\n            }\n        } else {\n            while (!q2.empty())\n            {\n                int tmp = q2.front();\n                if (q2.size() > 1) q1.push(tmp);\n                if (q2.size() == 2) v= tmp;\n                q2.pop();\n            }\n        }\n    }\n\n    // Get the top element.\n    int top() {\n        return v;\n    }\n\n    // Return whether the stack is empty.\n    bool empty() {\n        return q1.empty() && q2.empty();\n    }\n};\n"
  },
  {
    "path": "cpp/221-230/Invert Binary Tree.cpp",
    "content": "class Solution {\npublic:\n    TreeNode* invertTree(TreeNode* root) {\n        \n        if(!root) return nullptr;\n        \n        swap(root->left, root->right);\n        invertTree(root->left);\n        invertTree(root->right);\n        \n        return root;\n    }\n};\n"
  },
  {
    "path": "cpp/221-230/Kth Smallest Element in a BST.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int kthSmallest(TreeNode* root, int k) {\n        stack<TreeNode*>s;\n        TreeNode *p = root;\n        \n        while(p || !s.empty()) {\n            while(p) {\n                s.push(p);\n                p = p->left;\n            }\n            \n            p = s.top();\n            s.pop();\n            k--;\n            if (k == 0) return p->val;\n            p = p->right;\n        }\n        \n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/221-230/Majority Element II.cpp",
    "content": "class Solution {\npublic:\n    vector<int> majorityElement(vector<int>& nums) {\n        int cnt1 = 0, cnt2 = 0, a = 0, b = 1;\n\n        for(int n: nums){\n            if (a == n) {\n                cnt1++;\n            } else if (b == n) {\n                cnt2++;\n            } else if (cnt1 == 0) {\n                a = n;\n                cnt1 = 1;\n            } else if (cnt2 == 0){\n                b = n;\n                cnt2 = 1;\n            } else {\n                cnt1--;\n                cnt2--;\n            }\n        }\n\n        cnt1 = cnt2 = 0;\n        for (int n: nums){\n            if (n == a)   cnt1++;\n            else if (n == b)  cnt2++;\n        }\n\n        vector<int> res;\n        if (cnt1 > nums.size()/3)   res.push_back(a);\n        if (cnt2 > nums.size()/3)   res.push_back(b);\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/221-230/Maximal Square.cpp",
    "content": "class Solution {\npublic:\n    int maximalSquare(vector<vector<char>>& matrix) {\n        if (matrix.empty() || matrix.front().empty()) return 0;\n        int m = matrix.size();\n        int n = matrix.front().size();\n        vector<vector<int>> dp(m, vector<int>(n, 0));\n        int maxLen = 0;\n        \n        for (int i = 0; i < m; i++) {\n            for (int j = 0;j < n; j++) {\n                if (matrix[i][j] == '1') {\n                    dp[i][j] = 1;\n                    if (i > 0 && j > 0) {\n                        int tmp = min(dp[i-1][j-1], min(dp[i][j-1], dp[i-1][j]));\n                        dp[i][j] = max(dp[i][j], tmp+1);\n                    }\n                }\n                maxLen = max(maxLen, dp[i][j]);\n            }\n        }\n        \n        return maxLen*maxLen;\n    }\n};\n"
  },
  {
    "path": "cpp/221-230/Rectangle Area.cpp",
    "content": "class Solution {\n    \n    int overlapLen(int a1, int a2, int b1, int b2) {\n        if (a1 > b1) return overlapLen(b1, b2, a1, a2);\n        int left = b1;\n        int right = min(a2, b2);\n        if (right <= left) return 0;\n        return right - left;\n    }\n    \npublic:\n    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {\n        int area1 = (C - A) * (D - B);\n        int area2 = (G - E) * (H - F);\n        int width = overlapLen(A, C, E, G);\n        int height = overlapLen(B, D, F, H);\n        return area1 + area2 - width*height;\n    }\n};\n"
  },
  {
    "path": "cpp/221-230/Summary Ranges.cpp",
    "content": "class Solution {\npublic:\n    vector<string> summaryRanges(vector<int>& nums) {\n        vector<string> res;\n        if (nums.empty()) return res;\n        \n        int i(0);\n        while (i < nums.size()) {\n            int start(nums[i]);\n            while (i+1 < nums.size() && nums[i] == nums[i+1]-1)\n                i++;\n            if (start == nums[i])\n                res.push_back(to_string(start));\n            else\n                res.push_back(to_string(start)+\"->\"+to_string(nums[i]));\n            i++;\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/231-240/Delete Node in a Linked List.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    void deleteNode(ListNode* node) {\n        ListNode* nextNode = node->next;\n        *node = *nextNode;\n        delete nextNode;\n    }\n};\n"
  },
  {
    "path": "cpp/231-240/Implement Queue using Stacks.cpp",
    "content": "class MyQueue {\n    stack<int>s1;\n    stack<int>s2;\npublic:\n    /** Initialize your data structure here. */\n    MyQueue() {\n        \n    }\n    \n    /** Push element x to the back of queue. */\n    void push(int x) {\n        s1.push(x);\n    }\n    \n    /** Removes the element from in front of queue and returns that element. */\n    int pop() {\n        int x = peek();\n        s2.pop();\n        return x;\n    }\n    \n    /** Get the front element. */\n    int peek() {\n        if(s2.empty()) transit();\n        return s2.top();\n    }\n    \n    void transit() {\n        while(!s1.empty())\n        {\n            int v = s1.top();\n            s1.pop();\n            s2.push(v);\n        }\n    }\n    \n    /** Returns whether the queue is empty. */\n    bool empty() {\n        return s1.empty() && s2.empty();\n    }\n};\n\n/**\n * Your MyQueue object will be instantiated and called as such:\n * MyQueue obj = new MyQueue();\n * obj.push(x);\n * int param_2 = obj.pop();\n * int param_3 = obj.peek();\n * bool param_4 = obj.empty();\n */\n"
  },
  {
    "path": "cpp/231-240/Lowest Common Ancestor of a Binary Search Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {\n        int v1(p->val), v2(q->val);\n        while (root) {\n            int v = root->val;\n            if ((v > v1 && v > v2)) root = root->left;\n            else if (v < v1 && v < v2) root = root->right;\n            else return root;\n        }\n        return root;\n    }\n};\n"
  },
  {
    "path": "cpp/231-240/Lowest Common Ancestor of a Binary Tree.cpp",
    "content": "class Solution {\npublic:\n    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {\n        if (root == nullptr) {\n            return nullptr;\n        }\n    \n        if (root == p || root == q) {\n            return root;\n        }\n    \n        TreeNode* l = lowestCommonAncestor(root->left, p, q);\n        TreeNode* r = lowestCommonAncestor(root->right, p, q);\n    \n        if (l && r) {\n            return root;\n        }\n    \n        return l ? l : r;\n    }\n};\n"
  },
  {
    "path": "cpp/231-240/Number of Digit One.cpp",
    "content": "class Solution {\n    \npublic:\n    int countDigitOne(int n) {\n        int res(0), m(1), r(1);\n        while(n > 0)\n        {\n            res += ((n+8)/10 * m + (n%10 == 1? r : 0));\n            r += (n%10)*m;\n            m *= 10;\n            n /= 10;\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "cpp/231-240/Palindrome Linked List.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    bool isPalindrome(ListNode* head) {\n        if(!head || !head->next)\n            return true;\n        ListNode *slow(head),*fast(head);\n        \n        while(fast->next && fast->next->next){\n            slow = slow->next;\n            fast = fast->next->next;\n        }\n        \n        slow = reverseList(slow->next);\n        while(slow){\n            if(head->val != slow->val)\n                return false;\n            head = head->next;\n            slow = slow->next;\n        }\n        return true;\n    }\n    \n    ListNode* reverseList(ListNode* head) {\n        ListNode *tmp(NULL),*prev(NULL);\n        while(head)\n        {\n            tmp = head->next;\n            head->next = prev;\n            prev = head;\n            head = tmp;\n        }\n        return prev;\n    }\n};\n"
  },
  {
    "path": "cpp/231-240/Power of Two.cpp",
    "content": "class Solution {\npublic:\n    bool isPowerOfTwo(int n) {\n        return n > 0 && !(n & (n-1));\n    }\n};"
  },
  {
    "path": "cpp/231-240/Product of Array Except Self.cpp",
    "content": "class Solution {\npublic:\n    vector<int> productExceptSelf(vector<int>& nums) {\n        vector<int>res(nums.size(), 1);\n        \n        for (int i = 1; i < nums.size(); i++) {\n            res[i] = res[i-1] * nums[i-1];\n        }\n        \n        int tmp = 1;\n        for (int i = nums.size() - 1; i >= 0; i--) {\n            res[i] *= tmp;\n            tmp *= nums[i];\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/231-240/Search a 2D Matrix II.cpp",
    "content": "class Solution {\npublic:\n    bool searchMatrix(vector<vector<int>>& matrix, int target) {\n        if (matrix.empty() || matrix.front().empty()) return false;\n        int i = matrix.size()-1;\n        int j = 0;\n        while (i >= 0 && j <= matrix[0].size()-1) {\n            if(matrix[i][j] == target) return true;\n            else if(matrix[i][j] < target) j++;\n            else i--;\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/231-240/Sliding Window Maximum.cpp",
    "content": "class Solution {\npublic:\n    vector<int> maxSlidingWindow(vector<int>& nums, int k) {\n        deque<int> myqueue;\n        vector<int> res;\n        \n        for(int i = 0;i < nums.size();i++){\n            if(!myqueue.empty() && myqueue.front() == i - k) myqueue.pop_front();\n            while(!myqueue.empty() && nums[myqueue.back()] < nums[i]) myqueue.pop_back();\n            myqueue.push_back(i);\n            if(i >= k - 1) res.push_back(nums[myqueue.front()]);\n        }\n        \n        return res;\n    }\n};"
  },
  {
    "path": "cpp/241-250/Count Univalue Subtrees.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    int result;\n    \n    bool help(TreeNode* root)\n    {\n        if(!root) return true;\n        if(!root->left && !root->right) {result++;return true;}\n        bool left = help(root->left);\n        bool right = help(root->right);\n        if(!left || !right) return false;\n        if(root->left && root->right) {\n            if(root->left->val == root->val && root->right->val == root->val) {\n                result++;\n                return true;\n            } else return false;\n        }\n        else if(root->left && root->left->val == root->val) {\n            result++;\n            return true;\n        }\n        else if(root->right && root->right->val == root->val) {\n            result++;\n            return true;\n        }\n        return false;\n    }\n    \npublic:\n    int countUnivalSubtrees(TreeNode* root) {\n        result = 0;\n        help(root);\n        return result;\n    }\n};"
  },
  {
    "path": "cpp/241-250/Different Ways to Add Parentheses.cpp",
    "content": "class Solution {\npublic:\n    vector<int> diffWaysToCompute(string input) {\n        vector<int> output;\n        for (int i=0; i<input.size(); i++) {\n            char c = input[i];\n            if (ispunct(c))\n                for (int a : diffWaysToCompute(input.substr(0, i)))\n                    for (int b : diffWaysToCompute(input.substr(i+1)))\n                        output.push_back(c=='+' ? a+b : c=='-' ? a-b : a*b);\n        }\n        return output.size() ? output : vector<int>{stoi(input)};\n    }\n};"
  },
  {
    "path": "cpp/241-250/Group Shifted Strings.cpp",
    "content": "class Solution {\n    \n    bool pattern_match(const string &s1, const string &s2) {\n        if (s1.length() != s2.length()) return false;\n        int v(-1);\n        for (int i = 0; i < s1.length(); i++) {\n            int temp = (s2[i]-s1[i])%26;\n            if (temp < 0) temp += 26;\n            if (v < 0) v= temp;\n            if (temp != v) return false;\n        }\n        return true;\n    }\n    \npublic:\n    vector<vector<string>> groupStrings(vector<string>& strings) {\n        vector<vector<string>> result;\n        \n        for (int i = 0; i < strings.size(); i++) {\n            string cur = strings[i];\n            bool match(false);\n            for (int j = 0; j < result.size(); j++) {\n                if (pattern_match(cur, result[j][0])) {\n                    result[j].push_back(cur);\n                    match = true;\n                    break;\n                }\n            }\n            if (!match) {\n                vector<string> pattern;\n                pattern.push_back(cur);\n                result.push_back(pattern);\n            }\n        }\n        \n        for (int i = 0; i < result.size(); i++)\n            sort(result[i].begin(), result[i].end());\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/241-250/Shortest Word Distance II.cpp",
    "content": "class WordDistance {\n    \n    unordered_map<string, vector<int>> m;\n    \npublic:\n    WordDistance(vector<string>& words) {\n        for (int i = 0; i < words.size(); i++) {\n            m[words[i]].push_back(i);\n        }\n    }\n    \n    int shortest(string word1, string word2) {\n        const vector<int>& v1 = m[word1];\n        const vector<int>& v2 = m[word2];\n        int i = 0;\n        int j = 0;\n        int res = INT_MAX;\n        \n        while (i < v1.size() && j < v2.size()) {\n            int i1 = v1[i];\n            int i2 = v2[j];\n            res = min(abs(i1-i2), res);\n            if(i1 > i2) {\n                j++;\n            } else {\n                i++;\n            }\n        }\n\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/241-250/Shortest Word Distance III.cpp",
    "content": "class Solution {\npublic:\n    int shortestWordDistance(vector<string>& words, string word1, string word2) {\n        int index1(-1), index2(-1), shortest(INT_MAX);\n        \n        if(word1 == word2) {\n            int i = 0;\n            while(index1 == -1)\n            {\n                if(words[i] == word1) index1 = i;\n                i++;\n            }\n            \n            while(i < words.size())\n            {\n                if(words[i] == word1)\n                {\n                    shortest = min(i - index1, shortest);\n                    index1 = i;\n                }\n                i++;\n            }\n        }\n        \n        else {\n            for(int i = 0;i < words.size();i++)\n            {\n                if(words[i] == word1) {\n                    index1 = i;\n                } else if(words[i] == word2) {\n                    index2 = i;\n                }\n                \n                if(index1 == -1 || index2 == -1) continue;\n                shortest = min(abs(index1 - index2), shortest);\n            }\n        }\n        \n        return shortest;\n    }\n};"
  },
  {
    "path": "cpp/241-250/Shortest Word Distance.cpp",
    "content": "class Solution {\npublic:\n    int shortestDistance(vector<string>& words, string word1, string word2) {\n        \n        int index1(-1), index2(-1), shortest(INT_MAX);\n        for(int i = 0;i < words.size();i++)\n        {\n            if(words[i] == word1) {\n                index1 = i;\n            } else if(words[i] == word2) {\n                index2 = i;\n            }\n            \n            if(index1 == -1 || index2 == -1) continue;\n            shortest = min(abs(index1 - index2), shortest);\n        }\n        \n        return shortest;\n    }\n};"
  },
  {
    "path": "cpp/241-250/Strobogrammatic Number II.cpp",
    "content": "class Solution {\npublic:\n    vector<string> findStrobogrammatic(int n) {\n        return helper(n , n);\n    }\n    vector<string> helper(int m, int n){\n        if(m == 0) return vector<string>({\"\"});\n        if(m == 1) return vector<string>({\"0\", \"1\", \"8\"});\n        vector<string> tmp = helper(m - 2, n), res;\n        for(int i = 0; i < tmp.size(); i++){\n            if(m != n) res.push_back(\"0\" + tmp[i] + \"0\");\n            res.push_back(\"1\" + tmp[i] + \"1\");\n            res.push_back(\"6\" + tmp[i] + \"9\");\n            res.push_back(\"8\" + tmp[i] + \"8\");\n            res.push_back(\"9\" + tmp[i] + \"6\");\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/241-250/Strobogrammatic Number III.cpp",
    "content": "class Solution {\n    \n    int r = 0;\n    map<char, char> m;\n    char chs[5] = {'1','6','9','8','0'};\n    \n    bool check(const string& low, const string& high) {\n        if (high.length() > low.length()) return true;\n        if (high.length() < low.length()) return false;\n        return high >= low;\n    }\n    \n    void help(string temp, int cur, int n, const string& low, const string& high) {\n        if (n >= 2 && temp[0] == '0') return;\n        if (cur == (n+1)/2) {\n            if (check(low, temp) && check(temp, high)) {r++;}\n            return;\n        }\n        \n        for (int i = 0; i <= 4; i++) {\n            temp[cur] = chs[i];\n            temp[n - cur - 1] = m[chs[i]];\n            if (n % 2 == 1 && cur == n/2 && chs[i] != m[chs[i]]) {}\n            else help(temp, cur+1, n, low, high);\n        }\n    }\n    \npublic:\n    int strobogrammaticInRange(string low, string high) {\n        m['6'] = '9';\n        m['9'] = '6';\n        m['1'] = '1';\n        m['8'] = '8';\n        m['0'] = '0';\n        \n        int n1 = low.length();\n        int n2 = high.length();\n        for (int n = n1; n <= n2; n++) {\n            string temp(n,'1');\n            help(temp, 0, n, low, high);\n        }\n        \n        return r;\n    }\n};\n"
  },
  {
    "path": "cpp/241-250/Strobogrammatic Number.cpp",
    "content": "class Solution {\n    \npublic:\n    bool isStrobogrammatic(string num) {\n        unordered_map<char, char> m = {{'0', '0'}, {'1', '1'}, {'6','9'}, {'8','8'}, {'9', '6'}};\n        int len(num.length());\n        \n        for (int i = 0;i < (len+1)/2;i++)\n        {\n            if(m.count(num[i]) == 0) return false;\n            if(m[num[i]] != num[len - i - 1]) return false;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/241-250/Valid Anagram.cpp",
    "content": "class Solution {\npublic:\n    bool isAnagram(string s, string t) {\n        \n        int a[255] = {0};\n        \n        for(auto e : s)\n            a[e]++;\n        for(auto e : t)\n            a[e]--;\n        for(int i = 0;i < 255;i++)\n            if(a[i] != 0)\n                return false;\n        return true;\n        \n    }\n};"
  },
  {
    "path": "cpp/251-260/3Sum Smaller.cpp",
    "content": "class Solution {\npublic:\n    int threeSumSmaller(vector<int>& nums, int target) {\n        if (nums.size() < 3) return 0;\n        sort(nums.begin(), nums.end());\n        int result(0);\n        for (int i = 0;i < nums.size()-2;i++) {\n            int j(i+1), k(nums.size()-1);\n            int remain = target - nums[i];\n            while(j < k) {\n                if(nums[j] + nums[k] >= remain) {\n                    k--;\n                } else {\n                    result += (k - j);\n                    j++;\n                }\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/251-260/Add Digits.cpp",
    "content": "class Solution {\npublic:\n    int addDigits(int num) {\n        return 1 + (num - 1) % 9;\n    }\n};\n"
  },
  {
    "path": "cpp/251-260/Binary Tree Paths.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    void help(TreeNode* root, string path, vector<string>&paths)\n    {\n        path = path+to_string(root->val);\n        if(root->left)\n            help(root->left, path+\"->\", paths);\n        if(root->right)\n            help(root->right, path+\"->\", paths);\n        if(!root->left && !root->right)\n            paths.push_back(path);\n    }\n    \npublic:\n    vector<string> binaryTreePaths(TreeNode* root) {\n        vector<string> res;\n        if(root == nullptr) return res;\n        help(root, \"\", res);\n        return res;\n    }\n};"
  },
  {
    "path": "cpp/251-260/Factor Combinations.cpp",
    "content": "class Solution {\nprivate:\n    vector<vector<int>> res;\npublic:\n    vector<vector<int>> getFactors(int n) {\n        getFHelp(n, 2, vector<int>());\n        return res;\n    }\n    \n    void getFHelp(int n, int bottom, vector<int> line) {\n        for (int i = bottom; i<=sqrt(n); i++){\n            if (n%i == 0) {\n                vector<int> new_line(line);\n                new_line.push_back(i);\n                getFHelp(n/i, i, new_line);\n                new_line.push_back(n/i);\n                res.push_back(new_line);\n            }\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/251-260/Flatten 2D Vector.cpp",
    "content": "class Vector2D {\n    \n    int j;\n    vector<vector<int>>::iterator i, iEnd;\n    \npublic:\n    Vector2D(vector<vector<int>>& vec2d) {\n        j = 0;\n        i = vec2d.begin();\n        iEnd = vec2d.end();\n    }\n    \n    int next() {\n        hasNext();\n        return (*i)[j++];\n    }\n    \n    bool hasNext() {\n        while (i != iEnd && j == (*i).size()) {\n            i++;\n            j = 0;\n        }\n        return i != iEnd;\n    }\n};\n\n/**\n * Your Vector2D object will be instantiated and called as such:\n * Vector2D i(vec2d);\n * while (i.hasNext()) cout << i.next();\n */\n"
  },
  {
    "path": "cpp/251-260/Meeting Rooms II.cpp",
    "content": "/**\n * Definition for an interval.\n * struct Interval {\n *     int start;\n *     int end;\n *     Interval() : start(0), end(0) {}\n *     Interval(int s, int e) : start(s), end(e) {}\n * };\n */\nclass Solution {\npublic:\n    int minMeetingRooms(vector<Interval>& intervals) {\n        map<int, int> mymap;\n        for (const Interval& interval : intervals) {\n            mymap[interval.start]++;\n            mymap[interval.end]--;\n        }\n\n        int cnt = 0, maxCnt = 0;\n        for (auto it = mymap.begin(); it != mymap.end(); it++) {\n            cnt += it->second;\n            maxCnt = max(cnt, maxCnt);\n        }\n\n        return maxCnt;\n    }\n};\n"
  },
  {
    "path": "cpp/251-260/Meeting Rooms.cpp",
    "content": "/**\n * Definition for an interval.\n * struct Interval {\n *     int start;\n *     int end;\n *     Interval() : start(0), end(0) {}\n *     Interval(int s, int e) : start(s), end(e) {}\n * };\n */\nclass Solution {\npublic:\n    bool canAttendMeetings(vector<Interval>& intervals) {\n        auto comp = [&](const Interval &a, const Interval &b) { return a.start < b.start; };\n        sort(intervals.begin(), intervals.end(), comp);\n        int n = intervals.size();\n        for (int i = 0; i < n - 1; i++)\n            if (overlap(intervals[i], intervals[i + 1]))\n                return false;\n        return true;\n    }\nprivate:\n    bool overlap(Interval& interval1, Interval& interval2) {\n        return interval1.end > interval2.start;\n    }\n};\n"
  },
  {
    "path": "cpp/251-260/Paint House.cpp",
    "content": "class Solution {\npublic:\n    int minCost(vector<vector<int>>& costs) {\n        if(costs.size() == 0) return 0;\n        int i1(costs[0][0]), i2(costs[0][1]), i3(costs[0][2]);\n        \n        for(int i = 1;i < costs.size();i++)\n        {\n            int o1(i1),o2(i2),o3(i3);\n            i1 = min(o2,o3) + costs[i][0];\n            i2 = min(o1,o3) + costs[i][1];\n            i3 = min(o1,o2) + costs[i][2];\n        }\n        \n        int result = min(i1,i2);\n        result = min(result, i3);\n        return result;\n    }\n};"
  },
  {
    "path": "cpp/251-260/Single Number III.cpp",
    "content": "class Solution {\npublic:\n    vector<int> singleNumber(vector<int>& nums) {\n        int diff = accumulate(nums.begin(), nums.end(), 0, bit_xor<int>());\n        diff &= -diff;\n        vector<int> res(2, 0);\n        for (int e : nums) {\n            if(e & diff)\n                res[0] ^= e;\n            else\n                res[1] ^= e;\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/251-260/Verify Preorder Sequence in Binary Search Tree.cpp",
    "content": "/*\n        10\n    5         15\n 1    6     12   17\n \n 10  5   1   6   15  12   17\n*/\n\nclass Solution {\npublic:\n    bool verifyPreorder(vector<int>& preorder) {\n        stack<int> mystack;\n        int lower_bound_num(INT_MIN);\n        \n        for (int v : preorder) {\n            if (v < lower_bound_num) return false;\n            while (!mystack.empty() && v > mystack.top()) {\n                lower_bound_num = mystack.top();\n                mystack.pop();\n            }\n            mystack.push(v);\n        }\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/261-270/Alien Dictionary.cpp",
    "content": "class Solution {\n    bool dfs(char ch,\n             unordered_map<char, vector<char>>& graph,\n             unordered_map<char, int>& colors,\n             string& order) {\n        colors[ch] = 1;\n        for (char neighbor : graph[ch]) {\n            if (colors[neighbor] == 1) {\n                return true;\n            }\n            if (colors[neighbor] == 0) {\n                bool has_circle = dfs(neighbor, graph, colors, order);\n                if (has_circle) {\n                    return true;\n                }\n            }\n        }\n        order.push_back(ch);\n        colors[ch] = 2;\n        return false;\n    }\n    \npublic:\n    string alienOrder(vector<string>& words) {\n        unordered_map<char, vector<char>> graph;\n        for (int i = 1; i < words.size(); i++) {\n            int len = min(words[i-1].size(), words[i].size());\n            for (int j = 0; j < len; j++) {\n                if (words[i-1][j] != words[i][j]) {\n                    graph[words[i-1][j]].push_back(words[i][j]);\n                    break;\n                }\n                if (j == len - 1 && words[i].size() < words[i-1].size()) {\n                    return \"\";\n                }\n            }\n        }\n        \n        unordered_map<char, int> colors;\n        for (const string& word : words) {\n            for (char ch : word) {\n                colors[ch] = 0;\n            }\n        }\n        \n        string res;\n        for (const auto& [ch, color] : colors) {\n            if (color == 0) {\n                if (dfs(ch, graph, colors, res)) {\n                    return \"\";\n                }\n            }\n        }\n        reverse(res.begin(), res.end());\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/261-270/Closest Binary Search Tree Value.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int closestValue(TreeNode* root, double target) {\n        int v = root->val;\n        double diff(fabs(v - target));\n        \n        while (root != nullptr) {\n            if(fabs(root->val - target) <= diff) {\n                diff = fabs(root->val - target);\n                v = root->val;\n            }\n            if (target <= root->val) {\n                root = root->left;\n            } else {\n                root = root->right;\n            }\n        }\n        \n        return v;\n    }\n};\n"
  },
  {
    "path": "cpp/261-270/Factor Combinations.cpp",
    "content": "class Solution {\n    \n    void help(vector<vector<int>>& result, vector<int>& factors, vector<int> temp, int cur, int n)\n    {\n        if(n == 1 && temp.size() > 0)\n        {\n            result.push_back(temp);\n            return;\n        }\n        \n        if(cur == factors.size() || n < factors[cur]) return;\n        \n        if(n % factors[cur] == 0) {\n            temp.push_back(factors[cur]);\n            help(result, factors, temp, cur, n/factors[cur]);\n            temp.pop_back();\n        }\n        help(result, factors, temp, cur+1, n);\n    }\n    \npublic:\n    vector<vector<int>> getFactors(int n) {\n        vector<vector<int>> result;\n        vector<int> factors;\n        \n        for(int i = 2; i <= n/2;i++)\n            if(n % i == 0 && n > i)\n                factors.push_back(i);\n        vector<int> temp;\n        \n        help(result, factors, temp, 0, n);\n        return result;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/261-270/Graph Valid Tree.cpp",
    "content": "class Solution {\n    \n    int findParent(const vector<int>& vec, int node) {\n        while (node != vec[node]) {\n            node = vec[node];\n        }\n        \n        return node;\n    }\n    \npublic:\n    bool validTree(int n, vector<vector<int>>& edges) {\n        if (edges.size() + 1 != n) {\n            return false;\n        }\n        \n        vector<int> vec(n, 0);\n        for (int i = 0; i < n; i++) {\n            vec[i] = i;\n        }\n        \n        for (const vector<int>& edge : edges) {\n            int p1 = findParent(vec, edge[0]);\n            int p2 = findParent(vec, edge[1]);\n            if (p1 == p2) return false;\n            vec[p1] = p2;\n        }\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/261-270/Missing Number.cpp",
    "content": "class Solution {\npublic:\n    int missingNumber(vector<int>& nums) {\n        int s = accumulate(nums.begin(), nums.end(), 0);\n        int n = nums.size();\n        int v = (1+n)*n/2;\n        return v - s;\n    }\n};\n\nclass Solution {\npublic:\n    int missingNumber(vector<int>& nums) {\n        int ans = 0;\n        for (int i = 0; i < nums.size(); i++) {\n            ans ^= i;\n            ans ^= nums[i];\n        }\n        ans ^= nums.size();\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/261-270/Paint House II.cpp",
    "content": "class Solution {\npublic:\n    int minCostII(vector<vector<int>>& costs) {\n        if(costs.size() == 0) return 0;\n        vector<vector<int> > v(2, vector<int>(costs[0].size(), 0));\n        for(int i = 0;i < costs[0].size();i++) v[0][i] = costs[0][i];\n        int k = 0;\n        \n        for(int i = 1;i < costs.size();i++)\n        {\n            int minimum1 = min(v[k][0], v[k][1]);\n            int minimum2 = max(v[k][0], v[k][1]);\n            for(int j = 2;j < costs[0].size();j++)\n            {\n                if(v[k][j] < minimum1) {\n                    minimum2 = minimum1;\n                    minimum1 = v[k][j];\n                } else if(v[k][j] >= minimum1 && v[k][j] < minimum2) {\n                    minimum2 = v[k][j];\n                }\n            }\n            \n            k = (k+1)%2;\n            \n            for(int j = 0;j < costs[0].size();j++)\n            {\n                if(minimum1 != v[(k+1)%2][j]) v[k][j] = minimum1 + costs[i][j];\n                else v[k][j] = minimum2 + costs[i][j];\n            }\n            \n        }\n        \n        return *min_element(v[k].begin(), v[k].end());\n    }\n};"
  },
  {
    "path": "cpp/261-270/Palindrome Permutation II.cpp",
    "content": "class Solution {\n    \n    const static int M = 128;\n    \n    int chs[M] = {0};\n    \n    void help(vector<string>& result, string &temp, const string &s, int cur)\n    {\n        int mid = s.length() / 2;\n        if(s.length() % 2 == 0 && cur == mid) { result.push_back(temp); return;}\n        if(s.length() % 2 == 1 && cur == mid) {\n            for(int i = 0;i < M;i++){\n                if(chs[i] == 1) {\n                    temp[mid] = i;\n                    result.push_back(temp);\n                    return;\n                }\n            }\n        }\n        \n        for(int i = 0;i < M;i++)\n        {\n            if(chs[i] >= 2) {\n                temp[cur] = i;\n                temp[s.length() - 1 - cur] = i;\n                chs[i] -= 2;\n                help(result, temp, s, cur+1);\n                chs[i] += 2;\n            }\n        }\n    }\n    \npublic:\n    vector<string> generatePalindromes(string s) {\n        vector<string> result;\n        for (int i = 0;i < s.length();i++)\n            chs[s[i]]++;\n        \n        int odd(0),even(0);\n        for (int i = 0;i < M;i++) {\n            if(chs[i] == 0) continue;\n            if(chs[i] % 2 == 0) even++;\n            else odd++;\n        }\n        \n        if (odd >= 2) return result;\n        if (s.length() % 2 == 0 && odd > 0) return result;\n        \n        string tmp(s.length(), 0);\n        help(result, tmp, s, 0);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/261-270/Palindrome Permutation.cpp",
    "content": "class Solution {\n    \npublic:\n    bool canPermutePalindrome(string s) {\n        int MAGIC(128);\n        int ch[MAGIC] = {0};\n        for (int i = 0;i < s.length();i++) \n            ch[s[i]]++;\n        \n        int odd(0), even(0);\n        for (int i = 0;i < MAGIC;i++)\n            if (ch[i] > 0)\n                ch[i] % 2 == 1 ? odd++ : even++;\n        \n        if (odd >= 2) return false;\n        else if (odd == 1) {\n            if (s.length() % 2 == 1) return true;\n            return false;\n        }\n        else return true;\n    }\n};\n"
  },
  {
    "path": "cpp/261-270/Ugly Number II.cpp",
    "content": "class Solution {\npublic:\n    int nthUglyNumber(int n) {\n        vector<int> v = {1};     \n        int index2(0), index3(0), index5(0);\n        int val = 1;\n        \n        while (--n)      {\n            val = min(v[index2]*2, min(v[index3]*3, v[index5]*5));  \n            v.push_back(val);\n            if (val == v[index2]*2)    \n                ++index2;\n            if (val == v[index3]*3) \n                ++index3;\n            if (val == v[index5]*5)\n                ++index5;\n        }\n        return val;\n    }\n};\n"
  },
  {
    "path": "cpp/261-270/Ugly Number.cpp",
    "content": "class Solution {\npublic:\n    bool isUgly(int num) {\n        if (num <= 0) return false;\n        if (num == 1) return true;\n        while (num % 2 == 0) num /= 2;\n        while (num % 3 == 0) num /= 3;\n        while (num % 5 == 0) num /= 5;\n        return num == 1;\n    }\n};\n"
  },
  {
    "path": "cpp/271-280/Closest Binary Search Tree Value II.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    void dfs(TreeNode* root, priority_queue<pair<double, int>>& pq, double target, int k) {\n        if(!root) return;\n        \n        pq.push(make_pair(fabs(target - double(root->val)), root->val));\n        \n        if(pq.size() > k)\n            pq.pop();\n        \n        dfs(root->left, pq, target, k);\n        dfs(root->right, pq, target, k);\n    }\npublic:\n    \n    vector<int> closestKValues(TreeNode* root, double target, int k) {\n        priority_queue<pair<double, int>> pq;\n        vector<int> result;\n        \n        dfs(root, pq, target, k);\n        while(!pq.empty()) {\n            result.push_back(pq.top().second);\n            pq.pop();\n        }\n        \n        return result;\n    }\n};"
  },
  {
    "path": "cpp/271-280/Encode and Decode Strings.cpp",
    "content": "class Codec {\npublic:\n    \n    // Encodes a list of strings to a single string.\n    string encode(vector<string>& strs) {\n        string result(\"\");\n        for (const string& str : strs) {\n            string len = to_string(str.length());\n            result = result + len + \"#\" + str;\n        }\n        return result;\n    }\n    \n    // Decodes a single string to a list of strings.\n    vector<string> decode(string s) {\n        vector<string> result;\n        size_t i = 0;\n        while (i < s.length()) {\n            size_t index = s.find('#', i);\n            int len = stoi(s.substr(i, index-i));\n            result.push_back(s.substr(index+1, len));\n            i = index + len + 1;\n        }\n        return result;\n    }\n    \n};\n\n// Your Codec object will be instantiated and called as such:\n// Codec codec;\n// codec.decode(codec.encode(strs));\n"
  },
  {
    "path": "cpp/271-280/Find the Celebrity.cpp",
    "content": "// Forward declaration of the knows API.\nbool knows(int a, int b);\n\nclass Solution {\npublic:\n    int findCelebrity(int n) {\n        int i(0), j(n-1);\n        \n        while (i < j) {\n            if (knows(i, j)) i++;\n            else j--;\n        }\n        \n        for(int k = 0;k < n;k++) {\n            if (k == i) continue;\n            if (knows(i, k) || !knows(k, i)) return -1;\n        }\n        return i;\n    }\n};\n"
  },
  {
    "path": "cpp/271-280/First Bad Version.cpp",
    "content": "// Forward declaration of isBadVersion API.\nbool isBadVersion(int version);\n\nclass Solution {\npublic:\n    int firstBadVersion(int n) {\n        int lower = 1, upper = n, mid;\n        while(lower < upper) {\n            mid = lower + (upper - lower) / 2;\n            if(!isBadVersion(mid)) lower = mid + 1;\n            else upper = mid;\n        }\n        return lower;\n    }\n};"
  },
  {
    "path": "cpp/271-280/H-Index II.cpp",
    "content": "class Solution {\npublic:\n    int hIndex(vector<int>& citations) {\n        int i(0),j(citations.size()-1);\n        if(citations.size() == 0) return 0;\n        \n        while(i < j)\n        {\n            int mid = (i+j) >> 1;\n            int citation = citations[mid];\n            if(citation >= (citations.size() - mid)) j = mid - 1;\n            else i = mid + 1;\n        }\n        \n        if(citations[i] >= citations.size() - i) return citations.size() - i;\n        else return citations.size() - i - 1;\n    }\n    \n};"
  },
  {
    "path": "cpp/271-280/H-Index.cpp",
    "content": "class Solution {\npublic:\n    int hIndex(vector<int>& citations) {\n        if(citations.empty()) return 0;\n        int n = citations.size();\n        vector<int> hash(n + 1, 0);\n        \n        for (int i = 0; i < n; ++i) {\n            if(citations[i] >= n)\n                hash[n]++;\n            else\n                hash[citations[i]]++;\n        }\n        \n        int paper = 0;\n        for(int i = n; i >= 0; --i){\n            paper += hash[i];\n            if(paper >= i)\n                return i;\n        }\n        \n        return 0;\n    }\n};\n"
  },
  {
    "path": "cpp/271-280/Integer to English Words.cpp",
    "content": "class Solution {\npublic:\n    string hundredStr(int num){\n        vector<string> arr1={\"\",\"One\",\"Two\",\"Three\",\"Four\",\"Five\",\"Six\",\"Seven\",\"Eight\",\"Nine\",\"Ten\",\n            \"Eleven\",\"Twelve\",\"Thirteen\",\"Fourteen\",\"Fifteen\",\"Sixteen\",\"Seventeen\",\"Eighteen\",\"Nineteen\"};\n        vector<string> arr2={\"\",\"\",\"Twenty\",\"Thirty\",\"Forty\",\"Fifty\",\"Sixty\",\"Seventy\",\"Eighty\",\"Ninety\"};\n        string ret;\n        ret=num%100<20?arr1[num%100]:arr2[(num%100)/10]+(num%10?\" \"+arr1[num%10]:\"\");\n        if(num>99)ret=arr1[num/100]+\" Hundred\"+(num%100?\" \"+ret:\"\");\n        return ret;\n    }\n    string numberToWords(int num) {\n        string ret;\n        vector<string> strarr={\"Thousand\",\"Million\",\"Billion\"};\n        ret=hundredStr(num%1000);\n        for(int i=0;i<3;i++){\n            num/=1000;\n            ret=num%1000?hundredStr(num%1000)+\" \"+strarr[i]+\" \"+ ret:ret;\n        }\n        while(ret.back()==' ')ret.pop_back();\n        return ret.empty()?\"Zero\":ret;\n    }\n};"
  },
  {
    "path": "cpp/271-280/Paint Fence.cpp",
    "content": "class Solution {\npublic:\n    int numWays(int n, int k) {\n        vector<vector<int>> dp(2, vector<int>(n+2, 0));\n        dp[0][0] = 0;\n        dp[0][1] = k;\n        dp[1][0] = k;\n        dp[1][1] = k*(k-1);\n        \n        for (int i = 2; i < n; i++) {\n            dp[0][i] = dp[1][i-1];\n            dp[1][i] = (k-1) * (dp[0][i-1] + dp[1][i-1]);\n        }\n        \n        return dp[0][n-1] + dp[1][n-1];\n    }\n};\n"
  },
  {
    "path": "cpp/271-280/Perfect Squares.cpp",
    "content": "class Solution {\npublic:\n    int numSquares(int n) {\n        vector<int> p {0};\n        while (p.size() <= n) {\n            int res = INT_MAX;\n            for (int i = 1; i*i <= p.size(); i++)\n                res = min(res, p[p.size()-i*i]+1);\n            p.push_back(res);\n        }\n        return p[n];\n    }\n};\n"
  },
  {
    "path": "cpp/271-280/Wiggle Sort.cpp",
    "content": "class Solution {\npublic:\n    void wiggleSort(vector<int>& nums) {\n        \n        for (int i = 0;i < nums.size();i++) {\n            if (i % 2 == 0 && (i+1) < nums.size() && nums[i] > nums[i+1]) swap(nums[i], nums[i+1]);\n            if (i % 2 == 1 && (i+1) < nums.size() && nums[i] < nums[i+1]) swap(nums[i], nums[i+1]);\n        }\n        \n    }\n    \n};\n"
  },
  {
    "path": "cpp/281-290/Expression Add Operators.cpp",
    "content": "class Solution {\n    \n    void help(vector<string>& result, string& num, int& target, int index, char op, int pv, int nv, string res) {\n        if (index == num.size() && nv == target) {\n            result.push_back(res);\n            return;\n        }\n        \n        for (int i = 1; i <= num.size()-index; i++) {\n            string curnum = num.substr(index, i);\n            int v = stol(curnum);\n            if (curnum.length() != to_string(v).length()) continue;\n            help(result, num, target, index+i, '+', v, nv+v, res+'+'+curnum);\n            help(result, num, target, index+i, '-', v, nv-v, res+'-'+curnum);\n            help(result, num, target, index+i, op, pv*v, op == '+'? nv - pv + pv*v : (op == '-'? nv + pv - pv*v : pv*v), res+'*'+curnum);\n        }\n    }\n    \npublic:\n    vector<string> addOperators(string num, int target) {\n        \n        vector<string> result;\n        \n        for (int i = 1; i <= num.size(); i++) {\n            string curnum = num.substr(0, i);\n            int v = stol(curnum);\n            if (curnum.length() != to_string(v).length()) continue;\n            help(result, num, target, i, '!', v, v, curnum);\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/281-290/Find the Duplicate Number.cpp",
    "content": "class Solution {\npublic:\n    int findDuplicate(vector<int>& nums) {\n        int n = nums.size();\n        int left(1), right(n);\n        while (left < right) {\n            int mid = (left+right)/2;\n            int less(0), duplicate(0);\n            for (int i = 0;i < n;i++) {\n                if (nums[i] < mid) less++;\n                else if(nums[i] == mid) duplicate++;\n            }\n            if (duplicate > 1) return mid;\n            less > mid - 1 ? right = mid - 1 : left = mid + 1;\n        }\n        return left;\n    }\n};\n"
  },
  {
    "path": "cpp/281-290/Game of Life.cpp",
    "content": "class Solution {\npublic:\n    void gameOfLife(vector<vector<int>>& board) {\n        \n        int h = board.size();\n        int w = board[0].size();\n        \n        for (int i = 0;i < h;i++)\n        {\n            for (int j = 0;j < w;j++)\n            {\n                int old = board[i][j];\n                int lives(0);\n                int deads(0);\n                for (int m = -1;m <= 1;m++)\n                {\n                    for (int n = -1;n <= 1;n++)\n                    {\n                        if (m == 0 && n == 0) continue;\n                        int ix = j + n;\n                        int iy = i + m;\n                        if (ix < 0 || iy < 0 || ix >= w || iy >= h) continue;\n                        if ( (board[iy][ix] & 0x1) == 0) deads++;\n                        else if ( (board[iy][ix] & 0x1) == 1) lives++;\n                    }\n                }\n                \n                if (old == 1)\n                {\n                    if (lives < 2) continue;\n                    else if (lives == 2 || lives == 3) board[i][j] |= 0x2;\n                    else continue;\n                } else {\n                    if (lives == 3) board[i][j] |= 0x2;\n                }\n            }\n        }\n        \n        for (int i = 0;i < h;i++)\n        {\n            for (int j = 0;j < w;j++)\n            {\n                if ((board[i][j] & 0x2) > 0) board[i][j] = 1;\n                else board[i][j] = 0;\n            }\n        }\n        \n    }\n    \n};\n"
  },
  {
    "path": "cpp/281-290/Inorder Successor in BST.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {\n        if (root == nullptr)\n            return nullptr;\n\n        if (root->val <= p->val) {\n            return inorderSuccessor(root->right, p);\n        } else {\n            TreeNode* left = inorderSuccessor(root->left, p);\n            return (left != nullptr) ? left : root;\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/281-290/Move Zeroes.cpp",
    "content": "class Solution {\npublic:\n    void moveZeroes(vector<int>& nums) {\n        int first(0);\n        for (int i = 0;i < nums.size(); i++)\n            if (nums[i] != 0)\n                swap(nums[i],nums[first++]);\n    }\n};\n"
  },
  {
    "path": "cpp/281-290/Peeking Iterator.cpp",
    "content": "class PeekingIterator : public Iterator {\n    \n    int peekele;\n    bool peeked;\n    \npublic:\n    PeekingIterator(const vector<int>& num) : Iterator(num) {\n        // Initialize any member here.\n        peeked = false;\n    }\n    \n    // Returns the next element in the iteration without advancing the iterator.\n    int peek() {\n        if(!peeked) {\n            peekele = Iterator::next();\n            peeked = true;\n        }\n        return peekele;\n    }\n    \n    // hasNext() and next() should behave the same as in the Iterator interface.\n    // Override them if needed.\n    int next() {\n        if(!peeked) return Iterator::next();\n        peeked = false;\n        return peekele;\n    }\n    \n    bool hasNext() const {\n        if(peeked) return true;\n        if(Iterator::hasNext()) return true;\n        return false;\n    }\n};"
  },
  {
    "path": "cpp/281-290/Unique Word Abbreviation.cpp",
    "content": "class ValidWordAbbr {\n    \n    map<string, string> m;\n    \npublic:\n    ValidWordAbbr(vector<string> &dictionary) {\n        for(int i = 0;i < dictionary.size();i++) {\n            string abbr = dictionary[i].front() + to_string(dictionary[i].length()-2) + dictionary[i].back();\n            if(m.count(abbr) > 0 && m[abbr] != dictionary[i]) m[abbr] = \"0\";\n            else m[abbr] = dictionary[i];\n        }\n    }\n    \n    bool isUnique(string word) {\n        string abbr = word.front() + to_string(word.length()-2) + word.back();\n        if(m.count(abbr) > 0 && m[abbr] == \"0\") return false;\n        if(m.count(abbr) > 0 && m[abbr] != word) return false;\n        return true;\n    }\n};"
  },
  {
    "path": "cpp/281-290/Walls and Gates.cpp",
    "content": "struct point {\n    int i;\n    int j;\n    int v;\n    point(int _i, int _j, int _v):i(_i), j(_j), v(_v) { }\n};\n\nclass mycomparison {\npublic:\n    mycomparison() { }\n    bool operator() (const point& lhs, const point &rhs) const {\n        return lhs.v > rhs.v;\n    }\n};\n\nclass Solution {\n    \n    pair<int,int> cors[4] = {{1,0},{0,1},{-1,0},{0,-1}};\n    \npublic:\n    void wallsAndGates(vector<vector<int>>& rooms) {\n        priority_queue<point, vector<point>, mycomparison> myqueue;\n        \n        int height = rooms.size();\n        if (height == 0) return;\n        int width = rooms[0].size();\n        if (width == 0) return;\n        \n        for (int j = 0;j < height;j++)\n            for (int i = 0;i < width;i++)\n                if (rooms[j][i] == 0)\n                    myqueue.push(point(i, j, 0));\n        \n        while (!myqueue.empty()) {\n            point p = myqueue.top();\n            myqueue.pop();\n            for (int m = 0;m <= 3;m++) {\n                int ox = p.i + cors[m].first;\n                int oy = p.j + cors[m].second;\n                int ov = p.v;\n                if (ox >= 0 && ox < width && oy >= 0 && oy < height) {\n                    if(rooms[oy][ox] == INT_MAX) {\n                        rooms[oy][ox] = p.v + 1;\n                        myqueue.push(point(ox,oy,rooms[oy][ox]));\n                    }\n                }\n            }\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/281-290/Word Pattern.cpp",
    "content": "class Solution {\npublic:\n    bool wordPattern(string pattern, string str) {\n        stringstream ss(str);\n        // bijection, so need two maps\n        map<char, string>m;\n        map<string, bool>m2;\n        \n        for (int i = 0;i < pattern.length();i++)\n        {\n            char ch = pattern[i];\n            string temp;\n            ss >> temp;\n            \n            if (temp == \"\") return false;\n            \n            if (m.count(ch) == 0)\n            {\n                if (m2[temp] == true) return false;\n                m[ch] = temp;\n                m2[temp] = true;\n            } else {\n                if (m[ch] != temp)\n                    return false;\n            }\n        }\n        \n        string test;\n        ss >> test;\n        if (test.length() > 0) return false;\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/281-290/Zigzag Iterator.cpp",
    "content": "class ZigzagIterator {\n    \n    queue<vector<int>::iterator> myqueue;\n    set<vector<int>::iterator> dead;\n    \npublic:\n    ZigzagIterator(vector<int>& v1, vector<int>& v2) {\n        if(v1.begin() != v1.end())\n            myqueue.push(v1.begin());\n        if(v2.begin() != v2.end())\n            myqueue.push(v2.begin());\n        dead.insert(v1.end());\n        dead.insert(v2.end());\n    }\n    \n    int next() {\n        vector<int>::iterator it = myqueue.front();\n        myqueue.pop();\n        int v = *it;\n        it++;\n        if(dead.count(it) == 0) myqueue.push(it);\n        return v;\n    }\n    \n    bool hasNext() {\n        return !myqueue.empty();\n    }\n};\n\n/**\n * Your ZigzagIterator object will be instantiated and called as such:\n * ZigzagIterator i(v1, v2);\n * while (i.hasNext()) cout << i.next();\n */"
  },
  {
    "path": "cpp/291-300/Best Meeting Point.cpp",
    "content": "class Solution {\n    \npublic:\n    int minTotalDistance(vector<vector<int>>& grid) {\n        int result(0);\n        vector<int>vx, vy;\n        \n        for (int i = 0;i < grid.size();i++) {\n            for (int j = 0;j < grid[i].size();j++) {\n                if (grid[i][j] == 1) {\n                    vx.push_back(j);\n                    vy.push_back(i);\n                }\n            }\n        }\n        \n        int half_num = vx.size()/2;\n        std::nth_element (vx.begin(), vx.begin()+half_num, vx.end());\n        std::nth_element (vy.begin(), vy.begin()+half_num, vy.end());\n        int midx = vx[half_num];\n        int midy = vy[half_num];\n        \n        for (int i = 0;i < vx.size();i++)\n            result += abs(vx[i] - midx) + abs(vy[i] - midy);\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/291-300/Binary Tree Longest Consecutive Sequence.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    int result;\n    \n    void help(TreeNode* root, int h) {\n        result = max(result, h);\n        \n        if (root->left) {\n            if (root->val == root->left->val -1)\n                help(root->left, h+1);\n            else\n                help(root->left, 1);\n        }\n        if (root->right) {\n            if (root->val == root->right->val -1)\n                help(root->right, h+1);\n            else\n                help(root->right, 1);\n        }\n    }\n    \npublic:\n    int longestConsecutive(TreeNode* root) {\n        if(!root) return 0;\n        help(root, 1);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/291-300/Bulls and Cows.cpp",
    "content": "class Solution {\npublic:\n    string getHint(string secret, string guess) {\n        int A(0),B(0);\n        map<char, int> mymap1;\n        map<char, int> mymap2;\n        for(int i = 0;i < secret.length();i++) {\n            if(secret[i] == guess[i]) A++;\n            else {\n                mymap1[secret[i]]++;\n                mymap2[guess[i]]++;\n            }\n        }\n        \n        for(int i = 0;i <= 9;i++)\n            B += min(mymap1['0'+i],mymap2['0'+i]);\n        \n        return to_string(A)+\"A\"+to_string(B)+\"B\";\n    }\n};"
  },
  {
    "path": "cpp/291-300/Find Median from Data Stream.cpp",
    "content": "class MedianFinder {\n    priority_queue<int, vector<int>, std::less<int>> maximum_heap;\n    priority_queue<int, vector<int>, std::greater<int>> minimum_heap;\npublic:\n    /** initialize your data structure here. */\n    MedianFinder() {\n        \n    }\n    \n    void addNum(int num) {\n        minimum_heap.push(num);\n        \n        maximum_heap.push(minimum_heap.top());\n        minimum_heap.pop();\n        \n        if (minimum_heap.size() < maximum_heap.size()) {\n            minimum_heap.push(maximum_heap.top());\n            maximum_heap.pop();\n        }\n    }\n    \n    double findMedian() {\n        if (maximum_heap.size() == minimum_heap.size()) {\n            return (minimum_heap.top()+maximum_heap.top()) / 2.0;\n        }\n        return minimum_heap.top();\n    }\n};\n"
  },
  {
    "path": "cpp/291-300/Flip Game II.cpp",
    "content": "class Solution {\n    \n    int len;\n    string ss;\n    \n    bool help() {\n        for (int is = 0; is <= len-2; ++is) {\n            if (ss[is] == '+' && ss[is+1] == '+') {\n                ss[is] = ss[is+1] = '-';\n                bool wins = !help();\n                ss[is] = ss[is+1] = '+';\n                if (wins) return true;\n            }\n        }\n        return false;\n    }\n    \npublic:\n    \n    bool canWin(string s) {\n        len = s.size();\n        ss = s;\n        return help();\n    }\n    \n};"
  },
  {
    "path": "cpp/291-300/Flip Game.cpp",
    "content": "class Solution {\npublic:\n    vector<string> generatePossibleNextMoves(string s) {\n        vector<string> result;\n        for (int i = 1;i < s.length();i++) {\n            if (s[i-1] == '+' && s[i] == '+') {\n                s[i-1] = s[i] = '-';\n                result.push_back(s);\n                s[i-1] = s[i] = '+';\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/291-300/Longest Increasing Subsequence.cpp",
    "content": "class Solution {\n\npublic:\n    int lengthOfLIS(vector<int>& nums) {\n        vector<int> res;\n        for(int i=0; i<nums.size(); i++) {\n            auto it = std::lower_bound(res.begin(), res.end(), nums[i]);\n            if(it == res.end()) res.push_back(nums[i]);\n            else *it = nums[i];\n        }\n        return res.size();\n    }\n};\n"
  },
  {
    "path": "cpp/291-300/Nim Game.cpp",
    "content": "class Solution {\n    \npublic:\n    bool canWinNim(int n) {\n        if(n % 4 == 0) return false;\n        return true;\n    }\n};"
  },
  {
    "path": "cpp/291-300/Serialize and Deserialize Binary Tree.cpp",
    "content": "/*\n * Solution 1\n * Use to_string to convert integer to a string.\n * Use space to separate each node.\n * Write a '#' for nullptr node.\n */\nclass Codec {\n    \n    void readNext(stringstream& ss, int& val, bool &isnumber) {\n        string str;\n        ss >> str;\n        if(str[0] == '#') {\n            isnumber = false;\n        } else {\n            val = stoi(str);\n            isnumber = true;\n        }\n        return;\n    }\n    \n    TreeNode* help(stringstream& ss) {\n        bool isnumber;\n        int val;\n        TreeNode *root = nullptr;\n        readNext(ss, val, isnumber);\n        \n        if (isnumber) {\n            root = new TreeNode(val);\n            root->left = help(ss);\n            root->right = help(ss);\n        }\n        return root;\n    }\n    \n    // Encodes a tree to a single string.\n    string _serialize(TreeNode* root) {\n        if (root == nullptr) return \"# \";\n        else return to_string(root->val) + \" \" + _serialize(root->left) + _serialize(root->right);\n    }\n    \npublic:\n    \n    // Encodes a tree to a single string.\n    string serialize(TreeNode* root) {\n        string serialized_data = _serialize(root);\n        return serialized_data;\n    }\n    \n    // Decodes your encoded data to tree.\n    TreeNode* deserialize(string data) {\n        stringstream ss(data);\n        return help(ss);\n    }\n};\n\n\n/*\n * Solution 2\n * Write 4 bytes for each integer.\n * Write a 'Y' or 'N' for each node. No separator is need.\n */\nclass Codec {\n    \n    void preorderDFS(TreeNode* root, string& serialized_data) {\n        if (root == nullptr) {\n            serialized_data.push_back('Y');\n            return;\n        }\n        serialized_data.push_back('N');\n        char buf[4];\n        memcpy(buf, &(root->val), sizeof(int));\n        for (int i = 0; i < 4; i++) serialized_data.push_back(buf[i]);\n        preorderDFS(root->left, serialized_data);\n        preorderDFS(root->right, serialized_data);\n    }\n    \n    inline TreeNode* reconstruct(const string& buffer, int& pos) {\n        if (pos >= buffer.size()) return nullptr;\n        \n        char indicator = buffer[pos];\n        pos++;\n        \n        if (indicator == 'Y') {\n            return nullptr;\n        }\n        \n        int value;\n        memcpy(&value, &buffer[pos], sizeof(int));\n        \n        TreeNode* node = new TreeNode(value);\n        pos += sizeof(int);\n        node->left = reconstruct(buffer, pos);\n        node->right = reconstruct(buffer, pos);\n        return node;\n    }\n    \npublic:\n    \n    // Encodes a tree to a single string.\n    string serialize(TreeNode* root) {\n        string serialized_data;\n        preorderDFS(root, serialized_data);\n        return serialized_data;\n    }\n    \n    // Decodes your encoded data to tree.\n    TreeNode* deserialize(string data) {\n        int pos = 0;\n        return reconstruct(data, pos);\n    }\n};\n"
  },
  {
    "path": "cpp/291-300/Word Pattern II.cpp",
    "content": "class Solution {\n    \n    bool help(int pindex, int sindex, string &pattern, string &str, map<char,string>& m, map<string, bool>& check)\n    {\n        if(pindex == pattern.length() && sindex == str.length()) return true;\n        if(pindex == pattern.length() || sindex == str.length()) return false;\n        char cur = pattern[pindex];\n        if(m.count(cur) == 0)\n        {\n            int maxlength = str.length() - sindex;\n            for(int l = 1; l <= maxlength; l++)\n            {\n                string s = str.substr(sindex, l);\n                if(check[s] == true) continue;\n                m[cur] = s;\n                check[s] = true;\n                bool fff = help(pindex+1, sindex+l, pattern, str, m, check);\n                if(fff) return true;\n                m.erase(cur);\n                check[s] = false;\n            }\n            return false;\n        } else {\n            string temp = m[cur];\n            if(str.substr(sindex, temp.length()) == temp)\n            {\n                bool fff = help(pindex+1, sindex+temp.length(), pattern, str, m, check);\n                if(fff) return true;\n                else return false;\n            } else {\n                return false;\n            }\n        }\n    }\n    \npublic:\n    bool wordPatternMatch(string pattern, string str) {\n        \n        map<char, string> m;\n        map<string, bool> check;\n        \n        bool fff = help(0, 0, pattern, str, m, check);\n        return fff;\n    }\n};"
  },
  {
    "path": "cpp/301-310/Additive Number.cpp",
    "content": "class Solution {\n    \n    bool check(string add1, string add2, int index, string &num) {\n        while(1) {\n            if(add1.length() > 1 && add1[0] == '0') return false;\n            if(add2.length() > 1 && add2[0] == '0') return false;\n            long res = stol(add1) + stol(add2);\n            \n            string strres = to_string(res);\n            if(index + strres.length() > num.length()) return false;\n            string cmp = num.substr(index, strres.length());\n            \n            if(cmp != strres) return false;\n            index += strres.length();\n            if(index == num.length()) return true;\n            \n            add1 = add2;\n            add2 = strres;\n        }\n        \n        return false;\n    }\n    \npublic:\n    bool isAdditiveNumber(string num) {\n        \n        if(num.length() < 3) return false;\n        \n        for(int len1 = 1;len1 <= num.length() - 2; len1++) {\n            for(int len2 = 1; len1+len2 <= num.length() - 1;len2++) {\n                bool f = check(num.substr(0, len1), num.substr(len1, len2), len1+len2, num);\n                if(f) return true;\n            }\n        }\n        return false;\n    }\n};"
  },
  {
    "path": "cpp/301-310/Best Time to Buy and Sell Stock with Cooldown.cpp",
    "content": "class Solution {\npublic:\n    int maxProfit(vector<int>& prices) {\n        if (prices.empty()) return 0;\n        int buy = -prices[0];\n        int sell = 0;\n        int cooldown = 0;\n        \n        for (int i = 1; i < prices.size(); i++) {\n            int old_cooldown = cooldown;\n            cooldown = sell;\n            sell = max(sell, buy + prices[i]);\n            buy = max(buy, old_cooldown - prices[i]);\n        }\n        \n        return max(sell, cooldown);\n    }\n};\n"
  },
  {
    "path": "cpp/301-310/Minimum Height Trees.cpp",
    "content": "class Solution {\n    \npublic:\n    vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {\n        vector<int> res;\n        if(n <= 2) {\n            for(int i = 0;i < n;i++)\n                res.push_back(i);\n            return res;\n        }\n        int k = 0;\n        \n        vector<set<int>> myvec(n, set<int>());\n        queue<int> myqueue;\n        \n        for(auto e : edges) {\n            myvec[e.first].insert(e.second);\n            myvec[e.second].insert(e.first);\n        }\n        \n        for(int i = 0;i < n;i++) {\n            if(myvec[i].size() == 1) {\n                myqueue.push(i);\n                k++;\n            }\n        }\n        \n        while(1) {\n            int j = myqueue.size();\n            for(int i = 0;i < j;i++) {\n                int v = myqueue.front();\n                myqueue.pop();\n                for(auto e : myvec[v]) {\n                    myvec[e].erase(v);\n                    if(myvec[e].size() == 1) {\n                        myqueue.push(e);\n                        k++;\n                    }\n                }\n            }\n            if(n == k) break;\n        }\n        \n        while(!myqueue.empty()) {\n            res.push_back(myqueue.front());\n            myqueue.pop();\n        }\n        sort(res.begin(), res.end());\n        return res;\n    }\n};"
  },
  {
    "path": "cpp/301-310/Number of Islands II.cpp",
    "content": "class UF {\n    \nprivate:\n    vector<int> parent;\n    vector<int> rank;\n    int count;\n    int N;\n    \npublic:\n    \n    UF(int N) {\n        parent.resize(N);\n        rank.resize(N);\n        this->N = N;\n        count = N;\n        for(int i = 0;i < N;i++) {\n            parent[i] = i;\n            rank[i] = 0;\n        }\n    }\n    \n    int find(int p) {\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];    // path compression by halving\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    int getCount() {\n        return count;\n    }\n    \n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    void Union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rootP == rootQ) return;\n        \n        // make root of smaller rank point to root of larger rank\n        if      (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;\n        else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;\n        else {\n            parent[rootQ] = rootP;\n            rank[rootP]++;\n        }\n        count--;\n    }\n};\n\nclass Solution {\n\n    inline int convert(int m, int n, int col) {\n        return col*m + n;\n    }\n    \npublic:\n    vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {\n        vector<int> res;\n        UF uf(m*n);\n        int count = 0;\n        pair<int,int> pos[4] = {{0,1},{0,-1},{1,0},{-1,0}};\n        vector<bool> marked(m*n+10, false);\n        \n        for(auto& e : positions) {\n            count++;\n            int curisland = convert(e.first, e.second, n);\n            marked[curisland] = true;\n            for(int i = 0;i < 4;i++) {\n                int posi = e.first + pos[i].first;\n                int posj = e.second + pos[i].second;\n                int neighborisland = convert(posi, posj, n);\n                if(posi < 0 || posj < 0 || posi >= m || posj >= n || !marked[neighborisland]) continue;\n                if(!uf.connected(curisland, neighborisland)) {\n                    uf.Union(curisland, neighborisland);\n                    count--;\n                }\n            }\n            res.push_back(count);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/301-310/Range Sum Query - Immutable.cpp",
    "content": "class NumArray {\n    int *a;\npublic:\n    NumArray(vector<int> &nums) {\n        a = new int[nums.size()+1];\n        a[0] = 0;\n        for (int i = 0; i < nums.size(); i++) {\n            a[i+1] = nums[i] + a[i];\n        }\n    }\n\n    int sumRange(int i, int j) {\n        return a[j+1] - a[i];\n    }\n};\n\n\n\n// Your NumArray object will be instantiated and called as such:\n// NumArray numArray(nums);\n// numArray.sumRange(0, 1);\n// numArray.sumRange(1, 2);\n"
  },
  {
    "path": "cpp/301-310/Range Sum Query - Mutable.cpp",
    "content": "class SegmentTreeNode {\n    \npublic:\n    int start, end, sum;\n    SegmentTreeNode *left, *right;\n    SegmentTreeNode(int start, int end, int sum) {\n        this->start = start;\n        this->end = end;\n        this->sum = sum;\n        this->left = this->right = NULL;\n    }\n};\n\nclass NumArray {\n    \n    SegmentTreeNode *root;\n    \n    SegmentTreeNode * build(int start, int end, vector<int>& A) {\n        // write your code here\n        if(start > end) return nullptr;\n        if(start == end) {\n            SegmentTreeNode *tree = new SegmentTreeNode(start, end, A[start]);\n            return tree;\n        }\n        if(start < end) {\n            SegmentTreeNode *left = build(start, (start+end)/2, A);\n            SegmentTreeNode *right = build((start+end)/2+1, end, A);\n            SegmentTreeNode *tree = new SegmentTreeNode(start, end, left->sum + right->sum);\n            tree -> left = left;\n            tree -> right = right;\n            return tree;\n        }\n    }\n    \n    void modify(SegmentTreeNode *root, int i, int val) {\n        if(root->start == root->end) {\n            root->sum = val;\n            return;\n        }\n        if(i <= root->left->end) modify(root->left, i, val);\n        else modify(root->right, i, val);\n        root->sum = root->left->sum + root->right->sum;\n    }\n    \n    int query(SegmentTreeNode *root, int i, int j) {\n        if(root->start == root->end) return root->sum;\n        if(root->start == i && root->end == j) return root->sum;\n        \n        if(j <= root->left->end) {\n            return query(root->left, i, j);\n        } else if(i >= root->right->start) {\n            return query(root->right, i, j);\n        } else {\n            return query(root->left, i, root->left->end) + query(root->right, root->right->start, j);\n        }\n    }\n    \npublic:\n    NumArray(vector<int> &nums) {\n        root = build(0, nums.size()-1, nums);\n    }\n    \n    void update(int i, int val) {\n        modify(root, i, val);\n    }\n    \n    int sumRange(int i, int j) {\n        return query(root, i, j);\n    }\n};\n\n\n// Your NumArray object will be instantiated and called as such:\n// NumArray numArray(nums);\n// numArray.sumRange(0, 1);\n// numArray.update(1, 10);\n// numArray.sumRange(1, 2);"
  },
  {
    "path": "cpp/301-310/Range Sum Query 2D - Immutable.cpp",
    "content": "class NumMatrix {\n    vector<vector<int>> dp;\npublic:\n    NumMatrix(vector<vector<int>> &matrix) {\n        if(matrix.size() < 1) return;\n        vector<vector<int>> dp(matrix.size(), vector<int>(matrix[0].size(), 0));\n        dp[0][0] = matrix[0][0];\n        for(int i = 1;i < matrix.size();i++) dp[i][0] = dp[i-1][0] + matrix[i][0];\n        for(int i = 1;i < matrix[0].size();i++) dp[0][i] = dp[0][i-1] + matrix[0][i];\n        for(int i = 1;i < matrix.size();i++)\n            for(int j = 1;j < matrix[0].size();j++)\n                dp[i][j] = dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + matrix[i][j];\n        this->dp = dp;\n    }\n    \n    int sumRegion(int row1, int col1, int row2, int col2) {\n        return (dp[row2][col2] - (row1 == 0? 0 : dp[row1-1][col2]) - (col1 == 0? 0 :dp[row2][col1-1]) + (row1 == 0 || col1 == 0? 0 : dp[row1-1][col1-1]));\n    }\n};"
  },
  {
    "path": "cpp/301-310/Range Sum Query 2D - Mutable.cpp",
    "content": "class NumMatrix {\n    \n    vector<vector<int>> dp;\n    vector<vector<int>> matrix;\n    \npublic:\n    NumMatrix(vector<vector<int>> &matrix) {\n        if (matrix.empty() || matrix[0].empty()) return;\n        \n        for (int i = 0; i < matrix.size(); i++) {\n            vector<int> temp(matrix[0].size()+1,0);\n            for (int j = 0; j < matrix[0].size(); j++) {\n                temp[j+1] = temp[j] + matrix[i][j];\n            }\n            dp.emplace_back(temp);\n        }\n        \n        this->matrix = matrix;\n    }\n    \n    void update(int row, int col, int val) {\n        int diff = val - matrix[row][col];\n        for (int j = col; j < matrix[0].size(); j++) {\n            dp[row][j+1] = dp[row][j+1] + diff;\n        }\n        matrix[row][col] = val;\n    }\n    \n    int sumRegion(int row1, int col1, int row2, int col2) {\n        int res = 0;\n        for (int i = row1; i <= row2; i++) {\n            res += (dp[i][col2+1] - dp[i][col1]);\n        }\n        return res;\n    }\n};\n\n\n// Your NumMatrix object will be instantiated and called as such:\n// NumMatrix numMatrix(matrix);\n// numMatrix.sumRegion(0, 1, 2, 3);\n// numMatrix.update(1, 1, 10);\n// numMatrix.sumRegion(1, 2, 3, 4);\n"
  },
  {
    "path": "cpp/301-310/Remove Invalid Parentheses.cpp",
    "content": "// Solution 1: BFS\nclass Solution {\n    \n    int GetErrors(const string &s) {\n        stack<char> mystack;\n        int valid = 0;\n        for (char ch : s) {\n            if (ch == '(') {\n                mystack.push(ch);\n            } else if (ch == ')') {\n                if (!mystack.empty()) {\n                    valid += 2;\n                    mystack.pop();\n                }\n            } else {\n                valid++;\n            }\n        }\n        return s.length() - valid;\n    }\n    \npublic:\n    vector<string> removeInvalidParentheses(string s) {\n        queue<string> myqueue;\n        unordered_set<string> visited;\n        myqueue.push(s);\n        visited.insert(s);\n        \n        int errors = GetErrors(s);\n        while (!myqueue.empty() && errors > 0) {\n            int queue_size = myqueue.size();\n            for (int k = 0; k < queue_size; k++) {\n                string str = myqueue.front();\n                myqueue.pop();\n                int i = 0;\n                while (i < str.length()) {\n                    if (str[i] != '(' && str[i] != ')') {\n                        i++;\n                        continue;\n                    }\n                    string tmp = str.substr(0,i) + str.substr(i+1);\n                    if (visited.count(tmp) == 0) {\n                        int current_errors = GetErrors(tmp);\n                        if (current_errors < errors) {\n                            myqueue.push(tmp);\n                            visited.insert(tmp);\n                        }\n                    }\n    \n                    while (i+1 < str.length() && str[i] == str[i+1]) i++;\n                    i++;\n                }\n            }\n            \n            errors--;\n        }\n        \n        vector<string> result;\n        while (!myqueue.empty()) {\n            string tmp = myqueue.front();\n            myqueue.pop();\n            result.push_back(tmp);\n        }\n        \n        return result;\n    }\n};\n\n\n// Solution 2: DFS\nclass Solution {\n    \n    int GetErrors(const string &s) {\n        stack<char> mystack;\n        int valid = 0;\n        for (char ch : s) {\n            if (ch == '(') {\n                mystack.push(ch);\n            } else if (ch == ')') {\n                if (!mystack.empty()) {\n                    valid += 2;\n                    mystack.pop();\n                }\n            } else {\n                valid++;\n            }\n        }\n        return s.length() - valid;\n    }\n    \npublic:\n    \n    void dfs(const string& s, int ind, int validLen, int leftCnt, int rightCnt, string cur, unordered_set<string>& visited, unordered_set<string>& res_set) {\n        if (cur.size() == validLen) {\n            if (leftCnt == rightCnt) {\n                res_set.insert(cur);\n            }\n            return;\n        }\n        if (ind >= s.size()) {\n            return;\n        }\n        \n        string key = to_string(ind) + cur;\n        if (visited.count(key) > 0) return;\n        visited.insert(key);\n        \n        if (s[ind] == '(' || s[ind] == ')') {\n            if (cur.length() + (s.size() - ind) > validLen) {\n                dfs(s, ind+1, validLen, leftCnt, rightCnt, cur, visited, res_set);\n            }\n            if (s[ind] == '(') {\n                if (leftCnt < validLen / 2) {\n                    dfs(s, ind+1, validLen, leftCnt+1, rightCnt, cur + '(', visited, res_set);\n                }\n            } else if (leftCnt > rightCnt) {\n                dfs(s, ind+1, validLen, leftCnt, rightCnt+1, cur + ')', visited, res_set);\n            }\n        } else {\n            dfs(s, ind+1, validLen, leftCnt, rightCnt, cur + s[ind], visited, res_set);\n        }\n    }\n    \n    vector<string> removeInvalidParentheses(string s) {\n        int validLen = s.size() - GetErrors(s);\n        unordered_set<string> visited;\n        unordered_set<string> res_set;\n        dfs(s, 0, validLen, 0, 0, \"\", visited, res_set);\n        return vector<string>(res_set.begin(), res_set.end());\n    }\n};\n"
  },
  {
    "path": "cpp/301-310/Smallest Rectangle Enclosing Black Pixels.cpp",
    "content": "class Solution {\n    \n    int top;\n    int left;\n    int right;\n    int bottom;\n    \n    pair<int, int> pos[4] = {\n        {-1,0},{1,0},{0,-1},{0,1}\n    };\n    \n    void bfs(vector<vector<char>>& image, int x, int y) {\n        \n        image[x][y] = '0';\n        \n        left = min(left, y);\n        right = max(right, y);\n        top = min(top, x);\n        bottom = max(bottom, x);\n        \n        for(auto e : pos) {\n            int nx = x + e.first;\n            int ny = y + e.second;\n            if(nx >= 0 && nx < image.size() && ny >= 0 && ny < image[0].size() && image[nx][ny] == '1')\n                bfs(image, nx, ny);\n        }\n    }\n    \npublic:\n    int minArea(vector<vector<char>>& image, int x, int y) {\n        \n        top = bottom = x;\n        left = right = y;\n        \n        bfs(image, x, y);\n        \n        int res = (right - left + 1) * (bottom - top + 1);\n        return res;\n    }\n};"
  },
  {
    "path": "cpp/311-320/Binary Tree Vertical Order Traversal.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \npublic:\n    vector<vector<int>> verticalOrder(TreeNode* root) {\n        map<int, vector<int>> mymap;\n        vector<vector<int>> res;\n        if (root == nullptr) return res;\n        \n        queue<TreeNode*> nodequeue;\n        queue<int>idqueue;\n        nodequeue.push(root);\n        idqueue.push(0);\n        \n        while (!nodequeue.empty()) {\n            TreeNode* cur = nodequeue.front();\n            int id = idqueue.front();\n            nodequeue.pop();\n            idqueue.pop();\n            \n            if (mymap.count(id) == 0) {\n                vector<int> temp;\n                mymap[id] = temp;\n            }\n            mymap[id].push_back(cur->val);\n            \n            if (cur -> left != nullptr) {\n                nodequeue.push(cur->left);\n                idqueue.push(id-1);\n            }\n            if (cur -> right != nullptr) {\n                nodequeue.push(cur->right);\n                idqueue.push(id+1);\n            }\n        }\n        \n        for (const auto& e : mymap)\n            res.emplace_back(e.second);\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/311-320/Bulb Switcher.cpp",
    "content": "class Solution {\npublic:\n    int bulbSwitch(int n) {\n        return sqrt(n);\n    }\n};\n"
  },
  {
    "path": "cpp/311-320/Burst Balloons.cpp",
    "content": "class Solution {\n    \n    int getValue(vector<int>& nums, int i) {\n        if(i < 0 || i >= nums.size()) return 1;\n        return nums[i];\n    }\n    \npublic:\n    int maxCoins(vector<int>& nums) {\n        if(nums.size() == 0) return 0;\n        int n = nums.size();\n        vector<vector<int>> dp(n, vector<int>(n, 0));\n        for(int len = 1; len <= n; len++) {\n            for(int start = 0;start <= n-len;start++) {\n                int end = start + len - 1;\n                for(int i = start; i <= end; i++) {\n                    int coins = nums[i] * getValue(nums, start - 1) * getValue(nums, end + 1);\n                    coins += i != start ? dp[start][i - 1] : 0;\n                    coins += i != end ? dp[i + 1][end] : 0;\n                    dp[start][end] = max(dp[start][end], coins);\n                }\n            }\n        }\n        return dp[0][n - 1];\n    }\n};"
  },
  {
    "path": "cpp/311-320/Count of Smaller Numbers After Self.cpp",
    "content": "struct tree{\n    int val;\n    tree* left;\n    tree* right;\n    int count;\n    tree(int v):val(v),left(nullptr),right(nullptr),count(1){}\n};\n\nclass Solution {\npublic:\n    vector<int> countSmaller(vector<int>& nums) {\n        tree* root(nullptr);\n        vector<int> res(nums.size(), 0);\n        \n        for (int i = nums.size() - 1; i >= 0; i--) {\n            if (root == nullptr) {\n                root = new tree(nums[i]);\n            } else {\n                int temp(0);\n                tree* cur = root;\n                while (cur != nullptr) {\n                    if (nums[i] <= cur->val) {\n                        cur->count++;\n                        if(cur -> left == nullptr) {\n                            tree* node = new tree(nums[i]);\n                            cur->left = node;\n                            break;\n                        }\n                        cur = cur->left;\n                    } else {\n                        temp += cur->count;\n                        if (cur -> right == nullptr) {\n                            tree* node = new tree(nums[i]);\n                            cur->right = node;\n                            break;\n                        }\n                        cur = cur->right;\n                    }\n                }\n                res[i] = temp;\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/311-320/Generalized Abbreviation.cpp",
    "content": "class Solution {\n    \n    void help(int i, string &word, vector<string>& result, int previous, string temp) {\n        if(i >= word.length()) {\n            if(previous != 0) temp = temp + to_string(previous);\n            result.push_back(temp);\n            return;\n        }\n        string num(\"\");\n        if(previous != 0) num = to_string(previous);\n        string _temp = temp+num+word[i];\n        help(i+1, word, result, 0, _temp);\n        help(i+1, word, result, previous+1, temp);\n    }\n    \npublic:\n    vector<string> generateAbbreviations(string word) {\n        vector<string> result;\n        help(0, word, result, 0, \"\");\n        return result;\n    }\n};"
  },
  {
    "path": "cpp/311-320/Maximum Product of Word Lengths.cpp",
    "content": "class Solution {\npublic:\n    int maxProduct(vector<string>& words) {\n        vector<int> mask(words.size(), 0);\n        int res = 0;\n        for(int i = 0;i < words.size(); i++) {\n            for(auto ch : words[i]) mask[i] |= (1 << (ch - 'a'));\n            for(int j = 0;j < i;j++) {\n                if( (mask[i] & mask[j]) == 0)\n                    res = max(res, int(words[i].length() * words[j].length()));\n            }\n        }\n        return res;\n    }\n};"
  },
  {
    "path": "cpp/311-320/Remove Duplicate Letters.cpp",
    "content": "class Solution {\npublic:\n    string removeDuplicateLetters(string s) {\n        bool visited[26] = {false};\n        int count[26] = {0};\n        stack<char> temp_answers;\n        for (char ch : s) {\n            count[ch - 'a']++;\n        }\n        \n        // bcabc, b -> bc -> a -> ab -> abc\n        // cbacdcbc, c -> b -> a -> ac -> acd -> acd -> acdb \n        for (char ch : s) {\n            int index = ch - 'a';\n            count[index]--;\n\n            if (visited[index]) continue;\n            \n            while (!temp_answers.empty() && temp_answers.top() > ch && count[temp_answers.top() - 'a'] > 0) {\n                char c = temp_answers.top();\n                temp_answers.pop();\n                visited[c - 'a'] = false;\n            }\n            \n            if (visited[index] == false) {\n                temp_answers.push(ch);\n                visited[index] = true;\n            }\n            \n        }\n        \n        string res(\"\");\n        while (!temp_answers.empty()) {\n            res = temp_answers.top() + res;\n            temp_answers.pop();\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/311-320/Shortest Distance from All Buildings.cpp",
    "content": "struct point {\n    int i;\n    int j;\n    int v;\n    point(int _i, int _j, int _v){i = _i; j = _j; v = _v;}\n};\n\nclass Solution {\n    \n    void BFS(int i, int j, vector<vector<int>>& grid, vector<vector<int>>& records) {\n        int m = grid.size();\n        int n = grid[0].size();\n        \n        vector<vector<bool> > visited(m, vector<bool>(n, false));\n        \n        queue<struct point> myqueue;\n        point cur(i, j, 0);\n        myqueue.push(cur);\n        visited[i][j] = true;\n        \n        while (!myqueue.empty()) {\n            cur = myqueue.front();\n            myqueue.pop();\n            \n            if(records[cur.i][cur.j] >= 0)\n                records[cur.i][cur.j] += cur.v;\n            \n            pair<int,int> pos[4] = {{-1,0},{1,0},{0,1},{0,-1}};\n            \n            for (int k = 0;k < 4;k++) {\n                int curi = cur.i + pos[k].first;\n                int curj = cur.j + pos[k].second;\n                \n                if (curi >= 0 && curi < m && curj >= 0 && curj < n && !visited[curi][curj] &&\n                grid[curi][curj] == 0 && records[curi][curj] >= 0) {\n                    point p(curi, curj, cur.v+1);\n                    visited[curi][curj] = true;\n                    myqueue.push(p);\n                }\n            }\n        }\n    \n        for (int i = 0;i < m;i++)\n            for (int j = 0;j < n;j++)\n                if (!visited[i][j])\n                    records[i][j] = INT_MIN;\n    }\n    \npublic:\n    int shortestDistance(vector<vector<int>>& grid) {\n        int m = grid.size();\n        int n = grid[0].size();\n        \n        vector<vector<int> > records(m, vector<int>(n, 0));\n        \n        for(int i = 0;i < m;i++)\n            for(int j = 0;j < n;j++)\n                if(grid[i][j] == 1)\n                    BFS(i, j, grid, records);\n        \n        int result(INT_MAX);\n        \n        for(int i = 0;i < m;i++)\n            for(int j = 0;j < n;j++)\n                if(records[i][j] > 0)\n                    result = min(result, records[i][j]);\n        \n        if(result == INT_MAX) return -1;\n        return result;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/311-320/Sparse Matrix Multiplication.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> multiply(vector<vector<int>>& A, vector<vector<int>>& B) {\n        int row1 = A.size();\n        int col1 = A[0].size();\n        int row2 = B.size();\n        int col2 = B[0].size();\n        \n        vector<vector<int>> res(row1, vector<int>(col2, 0));\n        vector<unordered_map<int,int>> CacheB(col2);\n        \n        for (int i = 0;i < row2;i++)\n            for (int j = 0;j < col2;j++)\n                if (B[i][j] != 0)\n                    CacheB[j][i] = B[i][j];\n        \n        for (int i = 0;i < row1;i++) {\n            for (int j = 0;j < col2;j++) {\n                unordered_map<int, int> right = CacheB[j];\n                if (right.size() == 0) continue;\n                for (int k = 0;k < col1;k++) {\n                    if (A[i][k] != 0 && right.count(k) > 0) {\n                        res[i][j] += A[i][k] * right[k];\n                    }\n                }\n            }\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/311-320/Super Ugly Number.cpp",
    "content": "class Solution {\npublic:\n    int nthSuperUglyNumber(int n, vector<int>& primes) {\n        int k = primes.size();\n        vector<int>index(k, 0);\n        vector<int>v(n, INT_MAX);\n        v[0] = 1;\n        int val = 1;\n        \n        for (int i=1; i<n; i++){\n            for (int j = 0; j< k; j++) v[i] = min(v[i], v[index[j]]*primes[j]);\n            for (int j = 0; j< k; j++) index[j] += (v[i]==v[index[j]]*primes[j]);\n        }\n        return v[n-1];\n    }\n};\n"
  },
  {
    "path": "cpp/321-330/Coin Change.cpp",
    "content": "class Solution {\n    \npublic:\n    int coinChange(vector<int>& coins, int amount) {\n        if(amount == 0) return 0;\n        int *dp = new int[amount+1];\n        for(int i = 1;i <= amount;i++) dp[i] = -1;\n        dp[0] = 0;\n        \n        for(int i = 1;i <= amount;i++) {\n            for(int e : coins) {\n                if(i - e < 0 || dp[i-e] < 0) continue;\n                int v = dp[i-e] + 1;\n                if(dp[i] <= 0) dp[i] = v;\n                else dp[i] = min(v, dp[i]);\n            }\n        }\n        \n        return dp[amount] <= 0 ? -1 : dp[amount];\n    }\n};"
  },
  {
    "path": "cpp/321-330/Count of Range Sum.cpp",
    "content": "typedef long long LL;\nstruct SegmentTreeNode {\n    LL L, R;\n    int cnt;\n    SegmentTreeNode *left, *right;\n    SegmentTreeNode(LL L, LL R) :L(L), R(R), cnt(0), left(NULL), right(NULL) {}\n};\n\nclass SegmentTree {\n    SegmentTreeNode * root;\n    SegmentTreeNode * buildTree(vector<LL> &nums, int L, int R) {\n        if (L > R) return NULL;\n        SegmentTreeNode * root = new SegmentTreeNode(nums[L], nums[R]);\n        if (L == R) return root;\n        int mid = (L + R) >> 1;\n        root->left = buildTree(nums, L, mid);\n        root->right = buildTree(nums, mid + 1, R);\n        return root;\n    }\n    \n    void update(SegmentTreeNode * root, LL val) {\n        if (root && root->L <= val &&  val <= root->R) {\n            root->cnt++;\n            update(root->left, val);\n            update(root->right, val);\n        }\n    }\n    \n    int sum(SegmentTreeNode * root, LL L, LL R) {\n        if (!root || root->R < L ||  R < root->L ) return 0;\n        if (L <= root->L  && root->R <= R) return root->cnt;\n        return sum(root->left, L, R) + sum(root->right, L, R);\n    }\n    \npublic:\n    SegmentTree(vector<LL> &nums, int L, int R) { root = buildTree(nums, L, R); }\n    \n    int sum(LL L, LL R) {\n        return sum(root, L, R);\n    }\n    \n    void update(LL val) {\n        update(root, val);\n    }\n};\n\nclass Solution {\npublic:\n    int countRangeSum(vector<int>& nums, int lower, int upper) {\n        if (nums.size() == 0) return 0;\n        vector<LL> sum_array (nums.size(),0);\n        sum_array[0] = nums[0];\n        for (int i = 1; i < sum_array.size(); i++) {\n            sum_array[i] = nums[i] + sum_array[i - 1];\n        }\n        LL sum = sum_array[sum_array.size() - 1];\n        sort(sum_array.begin(), sum_array.end());\n        auto t = unique(sum_array.begin(), sum_array.end());\n        SegmentTree tree(sum_array, 0, t - sum_array.begin() - 1);\n        int ans = 0;\n        for (int i = nums.size() - 1; i >= 0; i--) {\n            tree.update(sum);\n            sum -= nums[i];\n            ans += tree.sum(lower + sum,upper + sum);\n        }\n        return ans;\n    }\n};"
  },
  {
    "path": "cpp/321-330/Create Maximum Number.cpp",
    "content": "class Solution {\n    \n    vector<int> merge(vector<int> nums1, vector<int> nums2) {\n        vector<int> ans;\n        int i = 0, j = 0;\n        while(i < nums1.size() && j < nums2.size()) {\n            if(greater(nums1, nums2, i, j)) {\n                ans.push_back(nums1[i]);\n                i++;\n            } else {\n                ans.push_back(nums2[j]);\n                j++;\n            }\n        }\n        if(i == nums1.size())\n            while(j < nums2.size())\n                ans.push_back(nums2[j++]);\n        else if(j == nums2.size())\n            while(i < nums1.size())\n                ans.push_back(nums1[i++]);\n        \n        return ans;\n    }\n    \n    vector<int> getMax(const vector<int>& nums, int t) {\n        stack<int> ans;\n        vector<int> res;\n        for(int i = 0;i < nums.size();i++) {\n            while(!ans.empty() && (ans.size() + nums.size() - i > t) && ans.top() < nums[i])\n            ans.pop();\n            if(ans.size() < t)\n            ans.push(nums[i]);\n        }\n        while(!ans.empty()) {\n            res.insert(res.begin(), ans.top());\n            ans.pop();\n        }\n        return res;\n    }\n    \n    bool greater(const vector<int> &nums1, const vector<int> &nums2, int i, int j) {\n        while (i < nums1.size() && j < nums2.size()) {\n            if (nums1[i] > nums2[j]) return true;\n            if (nums1[i] < nums2[j]) return false;\n            i++;\n            j++;\n        }\n        return (nums1.size()-i) >= (nums2.size()-j);\n    }\n    \npublic:\n    vector<int> maxNumber(vector<int>& nums1, vector<int>& nums2, int k) {\n        int len1 = nums1.size();\n        int len2 = nums2.size();\n        vector<int> res;\n        \n        int start = max(0, k - len2);\n        int end = min(k, len1) + 1;\n        \n        for (int i = start; i < end; i++) {\n            vector<int> tmp = merge(getMax(nums1, i), getMax(nums2, k - i));\n            if (greater(tmp, res, 0, 0)) res = tmp;\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/321-330/Longest Increasing Path in a Matrix.cpp",
    "content": "class Solution {\n    \n    int dfsvisit(int i, int j, vector<vector<bool>> &visited, vector<vector<int>>& lens, vector<vector<int>>& matrix) {\n        \n        pair<int, int> pos[4] = {{0,1}, {0,-1}, {1,0}, {-1,0}};\n        \n        for (int k = 0;k < 4;k++) {\n            int ni = i + pos[k].first;\n            int nj = j + pos[k].second;\n            if(ni < 0 || nj < 0 || ni >= matrix.size() || nj >= matrix[0].size()) continue;\n            if(matrix[i][j] >= matrix[ni][nj]) continue;\n            if(visited[ni][nj]) lens[i][j] = max(lens[i][j], lens[ni][nj]+1);\n            else lens[i][j] = max(lens[i][j], 1 + dfsvisit(ni, nj, visited, lens, matrix));\n        }\n        \n        visited[i][j] = true;\n        return lens[i][j];\n    }\n    \npublic:\n    int longestIncreasingPath(vector<vector<int>>& matrix) {\n        int m = matrix.size();\n        if (m == 0) return 0;\n        int n = matrix[0].size();\n        vector<vector<bool>> visited(m,vector<bool>(n, false));\n        vector<vector<int>> lens(m,vector<int>(n, 1));\n        \n        int _max(0);\n        for (int i = 0;i < m;i++) {\n            for (int j = 0;j < n;j++) {\n                if (!visited[i][j]) {\n                    _max = max(_max, dfsvisit(i, j, visited, lens, matrix));\n                }\n            }\n        }\n        \n        return _max;\n    }\n};\n"
  },
  {
    "path": "cpp/321-330/Maximum Size Subarray Sum Equals k.cpp",
    "content": "/*\n *  a[5] = 1  -1  5 -2  3\n *  sum    1   0  5  3  6\n *  if k = 2, when i = 3, mymap[1] = 0. the sum in the range is k.\n */\n\nclass Solution {\npublic:\n    int maxSubArrayLen(vector<int>& nums, int k) {\n        \n        map<int, int> mymap;\n        int sum(0), res(0);\n        \n        for (int i = 0;i < nums.size();i++) {\n            sum += nums[i];\n            if (sum == k) res = i+1;\n            else {\n                if (mymap.count(sum - k) > 0) res = max(res, i - mymap[sum-k]);\n            }\n            if (mymap.count(sum) == 0) mymap[sum] = i;\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/321-330/Number of Connected Components in an Undirected Graph.cpp",
    "content": "class Solution {\n    \n    int findroot(int c, vector<int> &u)\n    {\n        while (c != u[c]) c = u[c];\n        return c;\n    }\n    \npublic:\n    int countComponents(int n, vector<pair<int, int>>& edges) {\n        \n        vector<int> u(n, 0);\n        for (int i = 0;i < n;i++) {\n            u[i] = i;\n        }\n        \n        for (int i = 0;i < edges.size();i++)\n        {\n            int root1 = findroot(edges[i].first, u);\n            int root2 = findroot(edges[i].second, u);\n            if(root1 != root2) {\n                u[root2] = root1;\n                n--;\n            }\n        }\n        \n        return n;\n    }\n};\n"
  },
  {
    "path": "cpp/321-330/Odd Even Linked List.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* oddEvenList(ListNode* head) {\n        \n        ListNode* oddhead = new ListNode(0);\n        ListNode* res = oddhead;\n        \n        ListNode* evenhead = new ListNode(0);\n        ListNode* res2 = evenhead;\n        \n        int count(1);\n        \n        while(head) {\n            if(count % 2 == 1) {\n                oddhead -> next = head;\n                oddhead = oddhead->next;\n            } else {\n                evenhead -> next = head;\n                evenhead = evenhead->next;\n            }\n            head = head->next;\n            count++;\n        }\n        \n        evenhead->next = nullptr;\n        oddhead -> next = res2 -> next;\n        return res->next;\n    }\n};"
  },
  {
    "path": "cpp/321-330/Patching Array.cpp",
    "content": "class Solution {\npublic:\n    int minPatches(vector<int>& nums, int n) {\n        int i(0), res(0);\n        long miss(0);\n        \n        while (miss < n) {\n            if (i < nums.size() && miss >= (nums[i] - 1) ) {\n                miss += nums[i];\n                i++;\n            } else {\n                res++;\n                miss += (miss+1);\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/321-330/Power of Three.cpp",
    "content": "class Solution {\npublic:\n    bool isPowerOfThree(int n) {\n        return n > 0 && (1162261467 % n) == 0;\n    }\n};"
  },
  {
    "path": "cpp/321-330/Wiggle Sort II.cpp",
    "content": "class Solution {\npublic:\n    void wiggleSort(vector<int>& nums) {\n        int n = nums.size();\n        \n        // Find a median.\n        auto midptr = nums.begin() + n / 2;\n        nth_element(nums.begin(), midptr, nums.end());\n        int mid = *midptr;\n        \n        // Index-rewiring.\n#define A(i) nums[(1+2*(i)) % (n|1)]\n        \n        // 3-way-partition-to-wiggly in O(n) time with O(1) space.\n        int i = 0, j = 0, k = n - 1;\n        while (j <= k) {\n            if (A(j) > mid)\n                swap(A(i++), A(j++));\n            else if (A(j) < mid)\n                swap(A(j), A(k--));\n            else\n                j++;\n        }\n    }\n    \n};"
  },
  {
    "path": "cpp/331-340/Counting Bits.cpp",
    "content": "/*\n * 0000 0001 0010 0011 0100 0101 0110 0111 1000\n *  0     1    1   2     1    2    2    3    1\n */\n\nclass Solution {\npublic:\n    vector<int> countBits(int num) {\n        \n        vector<int> myvec(num+1, 0);\n        if(num == 0) return myvec;\n        \n        int loops = 1;\n        while(1) {\n            \n            int _size = loops;\n            for(int k = 0;k < loops;k++) {\n                int index = k+_size;\n                if(index > num)\n                    return myvec;\n                myvec[index] = myvec[k]+1;\n            }\n            loops *= 2;\n        }\n        \n    }\n};"
  },
  {
    "path": "cpp/331-340/House Robber III.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    void help(TreeNode* root, int &a, int &b) {\n        if (root == nullptr) {\n            a = b = 0;\n            return;\n        }\n        \n        // a is including current root, b is not\n        int a1, a2, b1, b2;\n        help(root->left, a1, b1);\n        help(root->right, a2, b2);\n        \n        a = root->val + b1 + b2;\n        b = max(a1 + a2, a1 + b2);\n        b = max(b, a2 + b1);\n        b = max(b, b1 + b2);\n        return;\n    }\n    \npublic:\n    int rob(TreeNode* root) {\n        int a, b;\n        help(root, a, b);\n        return max(a, b);\n    }\n};\n"
  },
  {
    "path": "cpp/331-340/Increasing Triplet Subsequence.cpp",
    "content": "class Solution {\npublic:\n    bool increasingTriplet(vector<int>& nums) {\n        \n        int min1(INT_MAX), min2(INT_MAX);\n        \n        for(int i = 0;i < nums.size();i++) {\n            if(nums[i] > min2) return true;\n            if(nums[i] > min1) min2 = min(min2, nums[i]);\n            else min1 = nums[i];\n        }\n        \n        return false;\n        \n    }\n};"
  },
  {
    "path": "cpp/331-340/Largest BST Subtree.cpp",
    "content": "class Solution {\n    \n    bool isBST(TreeNode* node, int& res, int& mini, int& maxi) {\n        \n        if (!node)\n            return true;\n        \n        int left_size=0, right_size=0;\n        int left_mini, left_maxi, right_mini, right_maxi;\n        \n        bool leftB = isBST(node->left, left_size, left_mini, left_maxi);\n        bool rightB = isBST(node->right, right_size, right_mini, right_maxi);\n        \n        if (leftB && rightB) {\n            if ( (!node->left || node->val >= left_maxi) && (!node->right || node->val <= right_mini) ) {\n                /* The tree rooted at this node is a binary search tree */\n                res = left_size+right_size+1;\n                \n                mini = node->left ? left_mini : node->val;\n                maxi = node->right ? right_maxi : node->val;\n                return true;\n            }\n        }\n        /* The tree rooted at this node is not a binary search tree, so take the maximum size of the BST in the left or right subtrees  */\n        res = max(left_size, right_size);\n        return false;\n    }\n    \npublic:\n    int largestBSTSubtree(TreeNode* root) {\n        \n        int res = 0;\n        int mini, maxi;\n        bool b = isBST(root, res, mini, maxi);\n        \n        return res;\n    }\n    \n};"
  },
  {
    "path": "cpp/331-340/Longest Substring with At Most K Distinct Characters.cpp",
    "content": "class Solution {\npublic:\n    int lengthOfLongestSubstringKDistinct(string s, int k) {\n        int longest = 0;\n        int previouspos = 0;\n        unordered_map<char, int>m;\n        \n        int cnt = 0;\n        for (int i = 0; i < s.length(); i++) {\n            m[s[i]]++;\n            if (m[s[i]] == 1) {\n                cnt++;\n            }\n\n            while (cnt > k) {\n                char ch = s[previouspos];\n                previouspos++;\n                m[ch]--;\n                if(m[ch] == 0) {\n                    cnt--;\n                }\n            }\n            \n            longest = max(longest, i-previouspos+1);\n        }\n        \n        return longest;\n    }\n};\n"
  },
  {
    "path": "cpp/331-340/Nested List Weight Sum.cpp",
    "content": "/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * class NestedInteger {\n *   public:\n *     // Return true if this NestedInteger holds a single integer, rather than a nested list.\n *     bool isInteger() const;\n *\n *     // Return the single integer that this NestedInteger holds, if it holds a single integer\n *     // The result is undefined if this NestedInteger holds a nested list\n *     int getInteger() const;\n *\n *     // Return the nested list that this NestedInteger holds, if it holds a nested list\n *     // The result is undefined if this NestedInteger holds a single integer\n *     const vector<NestedInteger> &getList() const;\n * };\n */\nclass Solution {\n    \n    int DFS(vector<NestedInteger>& nestedList, int depth){\n        int sum(0);\n        for (int i = 0;i < nestedList.size();i++){\n            if(nestedList[i].isInteger())\n                sum += nestedList[i].getInteger()*depth;\n            else\n                sum += DFS(nestedList[i].getList(),depth+1);\n        }\n        return sum;\n    }\n    \npublic:\n    int depthSum(vector<NestedInteger>& nestedList) {\n        return DFS(nestedList, 1);\n    }\n};\n"
  },
  {
    "path": "cpp/331-340/Palindrome Pairs.cpp",
    "content": "class Solution {\n    unordered_map<string, int> word_idx;\n    bool isPalindrome(const string& s) {\n        int left = 0;\n        int right = s.size() - 1;\n        while (left < right) {\n            if (s[left] == s[right]) {\n                left++;\n                right--;\n            } else {\n                return false;\n            }\n        }\n        return true;\n    }\npublic:\n    vector<vector<int>> palindromePairs(vector<string>& words) {\n        vector<vector<int>> res;\n        \n        for (int i = 0; i < words.size(); i++)\n            word_idx[words[i]] = i;\n        \n        for (int i = 0; i < words.size(); i++) {\n            const string& word = words[i];\n        \n            if (!word.empty() && word_idx.count(\"\") > 0 && isPalindrome(word)) {\n                int bidx = word_idx[\"\"];\n                res.push_back({i, bidx});\n                res.push_back({bidx, i});\n            }\n\n            string rword = string(word.rbegin(), word.rend());\n            \n            if (word_idx.count(rword) > 0) {\n                int ridx = word_idx[rword];\n                if (i != ridx) {\n                    res.push_back({i, ridx});\n                }\n            }\n\n            for (int j = 1; j < word.length(); j++) {\n                string left = word.substr(0, j);\n                string rleft = string(left.rbegin(), left.rend());\n                string right = word.substr(j);\n                string rright = string(right.rbegin(), right.rend());\n                if (isPalindrome(left) && word_idx.count(rright) > 0) {\n                    res.push_back({word_idx[rright], i});\n                }\n                if (isPalindrome(right) && word_idx.count(rleft) > 0) {\n                    res.push_back({i, word_idx[rleft]});\n                }\n                \n            }\n        }\n        \n        return res;\n    }\n};\n\n\n/*\n * Trie Solution\n*/\nclass Trie {\n    bool isPalindrome(const string& s) {\n        int left = 0;\n        int right = s.size() - 1;\n        while (left < right) {\n            if (s[left] == s[right]) {\n                left++;\n                right--;\n            } else {\n                return false;\n            }\n        }\n        return true;\n    }\n    \n    struct TrieNode {\n        TrieNode *nodes[26];\n        bool isWord;\n        vector<int> indices;\n        int ind;\n        TrieNode(): isWord(false) {\n            memset(nodes, 0, sizeof(nodes));\n        }\n    };\n    \n    TrieNode* root_;\npublic:\n    Trie() {\n        root_ = new TrieNode();\n    }\n    \n    void insert(string& s, int wordIndex) {\n        TrieNode* tmp = root_;\n        int n = s.size();\n        for (int i = 0; i < n; i++) {\n            int ind = s[i]-'a';\n            if (tmp->nodes[ind] == nullptr) {\n                tmp->nodes[ind] = new TrieNode();\n            }\n            if (isPalindrome(s.substr(i))) {\n                tmp->indices.push_back(wordIndex);\n            }\n            tmp = tmp->nodes[ind];\n        }\n        tmp->indices.push_back(wordIndex);\n        tmp->ind = wordIndex;\n        tmp->isWord = true;\n    }\n    \n    void findPalindrome(const vector<string>& words, int wordIndex, vector<vector<int>>& res) {\n        TrieNode* root = root_;\n        int m = words[wordIndex].size();\n        bool consume_whole_word = true;\n        for (int j = 0; j < m; j++) {\n            int ind = words[wordIndex][j] - 'a';\n            if (root->isWord && isPalindrome(words[wordIndex].substr(j))) {\n                if (root->ind != wordIndex) {\n                    res.push_back({wordIndex, root->ind});\n                }\n            }\n            root = root->nodes[ind];\n            if (root == nullptr) {\n                consume_whole_word = false;\n                break;\n            }\n        }\n        if (consume_whole_word) {\n            for (int index : root->indices) {\n                if (index != wordIndex) {\n                    res.push_back({wordIndex, index});\n                }\n            }\n        }\n    }\n};\n\nclass Solution {\npublic:\n    vector<vector<int>> palindromePairs(vector<string>& words) {\n        int n = words.size();\n        vector<vector<int>> res;\n        Trie trie;\n        for (int i = 0; i < n; i++) {\n            string current = words[i];\n            reverse(current.begin(), current.end());\n            trie.insert(current, i);\n        }\n       \n        for (int i = 0; i < n; i++) {\n            trie.findPalindrome(words, i, res);\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/331-340/Reconstruct Itinerary.cpp",
    "content": "class Solution {\npublic:\n    vector<string> findItinerary(vector<pair<string, string>> tickets) {\n        vector<string> ans;\n        unordered_map<string, multiset<string> > g;\n        for (int i = 0; i < tickets.size(); ++ i) {\n            g[tickets[i].first].insert(tickets[i].second);\n        }\n        dfs(\"JFK\", ans, g);\n        reverse(ans.begin(), ans.end());\n        return ans;\n    }\n    \nprivate:\n    void dfs(string u, vector<string> &ans, unordered_map<string, multiset<string> >& g){\n        while (!g[u].empty()) {\n            string v = *g[u].begin();\n            g[u].erase(g[u].begin());\n            dfs(v, ans, g);\n        }\n        ans.push_back(u);\n    }\n};\n"
  },
  {
    "path": "cpp/331-340/Self Crossing.cpp",
    "content": "class Solution {\npublic:\n    bool isSelfCrossing(vector<int>& x) {\n        for(int i=3, l=x.size(); i<l; i++) {\n            // Case 1: current line crosses the line 3 steps ahead of it\n            if(x[i]>=x[i-2] && x[i-1]<=x[i-3]) return true;  \n            // Case 2: current line crosses the line 4 steps ahead of it\n            else if(i>=4 && x[i-1]==x[i-3] && x[i]+x[i-4]>=x[i-2]) return true; \n            // Case 3: current line crosses the line 6 steps ahead of it\n            else if(i>=5 && x[i-2]>=x[i-4] && x[i]+x[i-4]>=x[i-2] && x[i-1]<=x[i-3] && x[i-1]+x[i-5]>=x[i-3]) return true;  \n        }\n        return false;\n    }\n\n/*               i-2\n    case 1 : i-1┌─┐\n                └─┼─>i\n                 i-3\n\n                    i-2\n    case 2 : i-1 ┌────┐\n                 └─══>┘i-3\n                 i  i-4      (i overlapped i-4)\n\n    case 3 :    i-4\n               ┌──┐ \n               │i<┼─┐\n            i-3│ i-5│i-1\n               └────┘\n                i-2\n\n*/\n};\n"
  },
  {
    "path": "cpp/331-340/Verify Preorder Serialization of a Binary Tree.cpp",
    "content": "class Solution {\n\npublic:\n    bool isValidSerialization(string preorder) {\n        if (preorder.empty()) return false;\n        preorder += ',';\n        int capacity = 1;\n        for (int idx = 0; idx < preorder.size(); idx++) {\n            if (preorder[idx]!=',') continue;\n            capacity--;\n            if (capacity < 0) return false;\n            if (preorder[idx-1] != '#') capacity += 2;\n        }\n        return capacity == 0;\n    }\n};\n"
  },
  {
    "path": "cpp/341-350/Design Tic-Tac-Toe.cpp",
    "content": "class TicTacToe {\nprivate:\n    //count parameter: player 1 + : player 2: -\n    vector<int> rowJudge;\n    vector<int> colJudge;\n    int diag, anti;\n    int total;\npublic:\n    /** Initialize your data structure here. */\n\n    TicTacToe(int n):total(n), rowJudge(n), colJudge(n),diag(0),anti(0){}\n\n    int move(int row, int col, int player) {\n        int add = player == 1 ? 1 : -1;\n        diag += row == col ? add : 0;\n        anti += row == total - col - 1 ? add : 0;\n        rowJudge[row] += add;\n        colJudge[col] += add;\n        if(abs(rowJudge[row]) == total || abs(colJudge[col]) == total || abs(diag) == total || abs(anti) == total) \n            return player;\n        return 0;\n    }\n};\n"
  },
  {
    "path": "cpp/341-350/Flatten Nested List Iterator.cpp",
    "content": "/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * class NestedInteger {\n *   public:\n *     // Return true if this NestedInteger holds a single integer, rather than a nested list.\n *     bool isInteger() const;\n *\n *     // Return the single integer that this NestedInteger holds, if it holds a single integer\n *     // The result is undefined if this NestedInteger holds a nested list\n *     int getInteger() const;\n *\n *     // Return the nested list that this NestedInteger holds, if it holds a nested list\n *     // The result is undefined if this NestedInteger holds a single integer\n *     const vector<NestedInteger> &getList() const;\n * };\n */\nclass NestedIterator {\n    \n    stack<NestedInteger> mystack;\n    bool cached;\n    int v;\n    \npublic:\n    NestedIterator(vector<NestedInteger> &nestedList) {\n        for (int i = nestedList.size()-1;i >= 0;i--)\n            mystack.push(nestedList[i]);\n        cached = false;\n    }\n\n    int next() {\n        hasNext();\n        cached = false;\n        return v;\n    }\n\n    bool hasNext() {\n        if (cached) return true;\n        while (!mystack.empty()) {\n            NestedInteger tmp = mystack.top();\n            mystack.pop();\n            if (tmp.isInteger()) {\n                v = tmp.getInteger();\n                cached = true;\n                return true;\n            }\n            vector<NestedInteger> nlist = tmp.getList();\n            for (int i = nlist.size()-1;i >= 0;i--) mystack.push(nlist[i]);\n        }\n        return false;\n    }\n};\n\n/**\n * Your NestedIterator object will be instantiated and called as such:\n * NestedIterator i(nestedList);\n * while (i.hasNext()) cout << i.next();\n */\n\n\n\n\n\n\n\n// pointer\n/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * class NestedInteger {\n *   public:\n *     // Return true if this NestedInteger holds a single integer, rather than a nested list.\n *     bool isInteger() const;\n *\n *     // Return the single integer that this NestedInteger holds, if it holds a single integer\n *     // The result is undefined if this NestedInteger holds a nested list\n *     int getInteger() const;\n *\n *     // Return the nested list that this NestedInteger holds, if it holds a nested list\n *     // The result is undefined if this NestedInteger holds a single integer\n *     const vector<NestedInteger> &getList() const;\n * };\n */\n\nclass NestedIterator {\n    stack<NestedInteger*> mystack;\n    int cache = 0;\n    bool cached = false;\npublic:\n    NestedIterator(vector<NestedInteger> &nestedList) {\n        for (int i = nestedList.size() - 1; i >= 0; i--) {\n            mystack.push(&nestedList[i]);\n        }\n    }\n    \n    int next() {\n        hasNext();\n        cached = false;\n        return cache;\n    }\n    \n    bool hasNext() {\n        if (cached == true) {\n            return true;\n        }\n        \n        while (!mystack.empty()) {\n            NestedInteger* ni = mystack.top();\n            mystack.pop();\n\n            if (ni->isInteger()) {\n                cached = true;\n                cache = ni->getInteger();\n                return true;\n            }\n            \n            for (int i = ni->getList().size() - 1; i >= 0; i--) {\n                mystack.push(&ni->getList()[i]);\n            }\n        }\n        \n        return false;\n    }\n};\n\n/**\n * Your NestedIterator object will be instantiated and called as such:\n * NestedIterator i(nestedList);\n * while (i.hasNext()) cout << i.next();\n */\n"
  },
  {
    "path": "cpp/341-350/Integer Break.cpp",
    "content": "class Solution {\npublic:\n    long long integerBreak(long long n) {\n        if(n == 2) return 1;\n        if(n == 3) return 2;\n        if(n == 4) return 4;\n        if(n == 5) return 6;\n        if(n == 6) return 9;\n        return 3 * integerBreak(n - 3);\n    }\n};\n"
  },
  {
    "path": "cpp/341-350/Intersection of Two Arrays II.cpp",
    "content": "class Solution {\npublic:\n    vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {\n        map<int, int> mymap;\n        vector<int> ans;\n        for(int ele : nums1) mymap[ele] += 1;\n        for(int ele : nums2) {\n            if(mymap.count(ele) > 0 && mymap[ele] > 0) {\n                ans.push_back(ele);\n                mymap[ele] -= 1;\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/341-350/Intersection of Two Arrays.cpp",
    "content": "class Solution {\npublic:\n    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {\n        set<int> myset, ans;\n        for (int ele : nums1) myset.insert(ele);\n        for (int ele : nums2) \n            if(myset.count(ele) > 0)\n                ans.insert(ele);\n        return vector<int>(ans.begin(), ans.end());\n    }\n};\n"
  },
  {
    "path": "cpp/341-350/Moving Average from Data Stream.cpp",
    "content": "class MovingAverage {\n    \n    queue<int> myqueue;\n    int size;\n    int sum;\n    \npublic:\n    /** Initialize your data structure here. */\n    MovingAverage(int size) {\n        this->size = size;\n        this->sum = 0;\n    }\n    \n    double next(int val) {\n        if(myqueue.size() < size) {\n            myqueue.push(val);\n            sum += val;\n        } else {\n            myqueue.push(val);\n            sum += val;\n            sum -= myqueue.front();\n            myqueue.pop();\n        }\n        return sum*1.0/myqueue.size();\n    }\n};\n\n/**\n * Your MovingAverage object will be instantiated and called as such:\n * MovingAverage obj = new MovingAverage(size);\n * double param_1 = obj.next(val);\n */\n"
  },
  {
    "path": "cpp/341-350/Power of Four.cpp",
    "content": "class Solution {\npublic:\n    bool isPowerOfFour(int num) {\n        return ((num-1)&num)==0 && (num-1)%3==0;\n    }\n};\n"
  },
  {
    "path": "cpp/341-350/Reverse String.cpp",
    "content": "class Solution {\npublic:\n    string reverseString(string s) {\n        for(int i = 0;i < s.length()/2;i++) {\n            swap(s[i], s[s.length()-1-i]);\n        }\n        return s;\n    }\n};"
  },
  {
    "path": "cpp/341-350/Reverse Vowels of a String.cpp",
    "content": "class Solution {\npublic:\n    string reverseVowels(string s) {\n        int dict[256] = {0};\n        dict['a'] = 1, dict['A'] = 1;\n        dict['e'] = 1, dict['E'] = 1;\n        dict['i'] = 1, dict['I'] = 1;\n        dict['o'] = 1, dict['O'] = 1;\n        dict['u'] = 1, dict['U'] = 1;\n        int start = 0, end = (int)s.size() - 1;\n        while(start < end){\n            while(start < end && dict[s[start]] == 0) start++;\n            while(start < end && dict[s[end]] == 0) end--;\n            swap(s[start++],s[end--]);\n        }\n        return s;\n    }\n};"
  },
  {
    "path": "cpp/341-350/Top K Frequent Elements.cpp",
    "content": "class Solution {\n    \n    struct greater_than\n    {\n        inline bool operator() (const pair<int, int>& left, const pair<int, int>& right)\n        {\n            return (left.second > right.second);\n        }\n    };\n    \npublic:\n    vector<int> topKFrequent(vector<int>& nums, int k) {\n        \n        map<int, int> mymap;\n        vector<pair<int, int> > myvec;\n        for(int ele : nums) mymap[ele] += 1;\n        for(auto ele : mymap) myvec.push_back(make_pair(ele.first, ele.second));\n        sort(myvec.begin(), myvec.end(), greater_than());\n        \n        vector<int> result;\n        for(int i = 0;i < k;i++)\n            result.push_back(myvec[i].first);\n        return result;\n    }\n};\n\n\nclass Solution {\n      struct greater_than{\n        bool operator() (const pair<int, int>&lhs, const pair<int, int>&rhs) {\n            return lhs.second > rhs.second;\n        }\n      };\npublic:\n   \n    vector<int> topKFrequent(vector<int>& nums, int k) {\n        unordered_map<int, int>dict;\n        priority_queue<pair<int, int>, vector<pair<int,int>>,greater_than> q;\n        vector<int> res(k);\n        for(int v : nums) dict[v]++;\n        for(const auto &m:dict) {\n            q.push({m.first,m.second});\n            if(q.size() > k) {\n                q.pop();\n            }\n        }\n        while (!q.empty()) {\n            res[--k] = q.top().first;\n            q.pop();\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/351-360/Android Unlock Patterns.cpp",
    "content": "class Solution {\n    \n    int DFS(vector<bool> &vis, vector<vector<int>> &skip, int cur, int remain) {\n        if(remain == 0) return 1;\n        vis[cur] = true;\n        int rst = 0;\n        for (int i = 1; i <= 9; ++i) {\n            if(!vis[i] && (skip[i][cur] == 0 || (vis[skip[i][cur]]))) {\n                rst += DFS(vis, skip, i, remain - 1);\n            }\n        }\n        vis[cur] = false;\n        return rst;\n    }\n\npublic:\n    int numberOfPatterns(int m, int n) {\n        vector<vector<int>> skip(10, vector<int>(10, 0));\n        skip[1][3] = skip[3][1] = 2;\n        skip[1][7] = skip[7][1] = 4;\n        skip[3][9] = skip[9][3] = 6;\n        skip[7][9] = skip[9][7] = 8;\n        skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = skip[3][7] = skip[7][3] = skip[4][6] = skip[6][4] = 5;\n        vector<bool> vis(10);\n        int rst = 0;\n        // DFS search each length from m to n\n        for(int i = m; i <= n; ++i) {\n            rst += DFS(vis, skip, 1, i - 1) * 4;    // 1, 3, 7, 9 are symmetric\n            rst += DFS(vis, skip, 2, i - 1) * 4;    // 2, 4, 6, 8 are symmetric\n            rst += DFS(vis, skip, 5, i - 1);        // 5\n        }\n        return rst;\n    }\n};\n"
  },
  {
    "path": "cpp/351-360/Count Numbers with Unique Digits.cpp",
    "content": "class Solution {\npublic:\n    int countNumbersWithUniqueDigits(int n) {\n        vector<int> p(n+1, 10);\n        p[0] = 1;\n        p[1] = 10;\n        int temp(9);\n        int base(9);\n        \n        for(int i = 2;i <= n;i++) {\n            temp *= base;\n            base --;\n            p[i] = p[i-1] + temp;\n        }\n        \n        return p[n];\n    }\n};\n"
  },
  {
    "path": "cpp/351-360/Data Stream as Disjoint Intervals.cpp",
    "content": "/**\n * Definition for an interval.\n * struct Interval {\n *     int start;\n *     int end;\n *     Interval() : start(0), end(0) {}\n *     Interval(int s, int e) : start(s), end(e) {}\n * };\n */\nclass SummaryRanges {\n    \n    vector<Interval> vec;\n    \npublic:\n    void addNum(int val) {\n        //anonymous function\n        auto Cmp = [](Interval a, Interval b) { return a.start < b.start; };\n        auto it = lower_bound(vec.begin(), vec.end(), Interval(val, val), Cmp);\n        int start = val, end = val;\n        if (it != vec.begin() && (it-1)->end + 1 >= val) it--;\n        while (it != vec.end() && val+1 >= it->start && val-1 <= it->end) {\n            start = min(start, it->start);\n            end = max(end, it->end);\n            it = vec.erase(it);\n        }\n        vec.insert(it,Interval(start, end));\n    }\n\n    vector<Interval> getIntervals() {\n        return vec;\n    }\n    \n};\n\n/**\n * Your SummaryRanges object will be instantiated and called as such:\n * SummaryRanges obj = new SummaryRanges();\n * obj.addNum(val);\n * vector<Interval> param_2 = obj.getIntervals();\n */\n"
  },
  {
    "path": "cpp/351-360/Design Snake Game.cpp",
    "content": "class SnakeGame {\n    \n    queue<pair<int, int>> myqueue;\n    set<pair<int, int>> myset;\n    vector<pair<int, int>> food;\n    \n    int width;\n    int height;\n    int idx;\n    \n    int curi,curj;\n    int score;\n    \n    \npublic:\n    /** Initialize your data structure here.\n        @param width - screen width\n        @param height - screen height \n        @param food - A list of food positions\n        E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */\n    SnakeGame(int width, int height, vector<pair<int, int>> food) {\n        myqueue.push(make_pair(0,0));\n        myset.insert(make_pair(0,0));\n        this->width = width;\n        this->height = height;\n        this->food = food;\n        this->idx = 0;\n        curi = curj = 0;\n        score = 0;\n    }\n    \n    /** Moves the snake.\n        @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down \n        @return The game's score after the move. Return -1 if game over. \n        Game over when snake crosses the screen boundary or bites its body. */\n    int move(string direction) {\n        int move_row = 0;\n        int move_col = 0;\n        if(direction == \"U\") {\n            move_row = -1;\n        } else if(direction == \"D\") {\n            move_row = 1;\n        } else if(direction == \"L\") {\n            move_col = -1;\n        } else if(direction == \"R\") {\n            move_col = 1;\n        }\n        \n        int nexti = curi + move_row;\n        int nextj = curj + move_col;\n        if (nexti < 0 || nexti >= height || nextj < 0 || nextj >= width) return -1;\n        pair<int, int> head = make_pair(nexti, nextj);\n        \n        myqueue.push(head);\n        if (food[idx] == head) {\n            myset.insert(head);\n            ++score;\n            ++idx;\n        } else {\n            pair<int, int> tail = myqueue.front();\n            myqueue.pop();\n            myset.erase(tail);\n            if (myset.count(head) > 0) return -1;\n            myset.insert(head);\n        }\n        \n        curi = nexti;\n        curj = nextj;\n        \n        return score;\n    }\n};\n\n/**\n * Your SnakeGame object will be instantiated and called as such:\n * SnakeGame obj = new SnakeGame(width, height, food);\n * int param_1 = obj.move(direction);\n */\n"
  },
  {
    "path": "cpp/351-360/Design Twitter.cpp",
    "content": "class Twitter {\n    \n    map<int, int> tweetTimeMap;\n    int time;\n    map<int, vector<int>> userTweetMap;\n    map<int, vector<int>> followMap;\n    \npublic:\n    /** Initialize your data structure here. */\n    Twitter() {\n        time = 0;\n    }\n    \n    /** Compose a new tweet. */\n    void postTweet(int userId, int tweetId) {\n        if(userTweetMap.count(userId) == 0) {\n            vector<int> myvec;\n            userTweetMap[userId] = myvec;\n        }\n        userTweetMap[userId].push_back(tweetId);\n        tweetTimeMap[tweetId] = ++time;\n    }\n    \n    /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */\n    vector<int> getNewsFeed(int userId) {\n        vector<int> res;\n        \n        vector<int> follows = followMap[userId];\n        follows.push_back(userId);\n        \n        vector<int> idxs(follows.size(), 0);\n        \n        for(int i = 0;i < follows.size(); i++) {\n            idxs[i] = userTweetMap[follows[i]].size() - 1;\n        }\n        \n        for(int k = 0; k < 10; k++) {\n            int tempidx;\n            int tweetId;\n            int latestTime(-1);\n            \n            for(int i = 0;i < idxs.size();i++) {\n                if(idxs[i] < 0) continue;\n                int tweetid = userTweetMap[follows[i]][idxs[i]];\n                int thisTime = tweetTimeMap[tweetid];\n                \n                if(thisTime > latestTime) {\n                    tempidx = i;\n                    tweetId = tweetid;\n                    latestTime = thisTime;\n                }\n            }\n            \n            if(latestTime < 0) break;\n            \n            idxs[tempidx]--;\n            \n            res.push_back(tweetId);\n        }\n        \n        return res;\n    }\n    \n    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */\n    void follow(int followerId, int followeeId) {\n        if(followerId == followeeId) return;\n        if(followMap.count(followerId) == 0) {\n            vector<int> myvec;\n            followMap[followerId] = myvec;\n        }\n        \n        vector<int> myvec = followMap[followerId];\n        for(int i = 0;i < myvec.size();i++)\n            if(myvec[i] == followeeId)\n                return;\n        \n        followMap[followerId].push_back(followeeId);\n    }\n    \n    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */\n    void unfollow(int followerId, int followeeId) {\n        if(followerId == followeeId) return;\n        int idx(-1);\n        vector<int> myvec = followMap[followerId];\n        for(int i = 0;i < myvec.size();i++) {\n            if(myvec[i] == followeeId) {\n                idx = i;\n                break;\n            }\n        }\n        if(idx < 0) return;\n        myvec.erase(myvec.begin() + idx);\n        followMap[followerId] = myvec;\n    }\n};\n\n/**\n * Your Twitter object will be instantiated and called as such:\n * Twitter obj = new Twitter();\n * obj.postTweet(userId,tweetId);\n * vector<int> param_2 = obj.getNewsFeed(userId);\n * obj.follow(followerId,followeeId);\n * obj.unfollow(followerId,followeeId);\n */\n"
  },
  {
    "path": "cpp/351-360/Line Reflection.cpp",
    "content": "class Solution {\n    \n    set<pair<int, int>> myset;\n    \npublic:\n    bool isReflected(vector<pair<int, int>>& points) {\n        \n        int small(INT_MAX);\n        int large(INT_MIN);\n        \n        for(auto e : points) {\n            small = min(small, e.first);\n            large = max(large, e.first);\n            myset.insert(e);\n        }\n        \n        int mid2 = small+large;\n        \n        for(auto e : points) {\n            pair<int, int> ref = make_pair(mid2 - e.first, e.second);\n            if(myset.count(ref) == 0) return false;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/351-360/Logger Rate Limiter.cpp",
    "content": "class Logger {\n    \n    map<string, int> mymap;\n    \npublic:\n    /** Initialize your data structure here. */\n    Logger() {\n        \n    }\n    \n    /** Returns true if the message should be printed in the given timestamp, otherwise returns false. The timestamp is in seconds granularity. */\n    bool shouldPrintMessage(int timestamp, string message) {\n        if(mymap.count(message) == 0) {\n            mymap[message] = timestamp;\n            return true;\n        }\n        int t = mymap[message];\n        if(timestamp - t < 10) return false;\n        mymap[message] = timestamp;\n        return true;\n    }\n};\n\n/**\n * Your Logger object will be instantiated and called as such:\n * Logger obj = new Logger();\n * bool param_1 = obj.shouldPrintMessage(timestamp,message);\n */\n"
  },
  {
    "path": "cpp/351-360/Rearrange String k Distance Apart.cpp",
    "content": "class Solution {\npublic:\n    string rearrangeString(string str, int k) {\n        if(k <= 1) return str;\n        string res;\n    \tint len = str.length();\n    \tmap<char, int> mymap;\n    \tpriority_queue< pair<int, char> > mypq;\n    \tfor(char c : str)\n    \t\tmymap[c]++;\n    \tfor(auto e : mymap) \n    \t\tmypq.push({e.second, e.first});\n    \n    \twhile(!mypq.empty()) {\n    \t\tint cnt = min(len, k);\n    \t\tvector<pair<int, char>> myvec;\n    \t\tfor(int i = 0;i < cnt;i++) {\n    \t\t    if(mypq.empty()) return \"\";\n    \t\t\tpair<int, char> mypair = mypq.top();\n    \t\t\tmypq.pop();\n    \t\t\tres.push_back(mypair.second);\n    \t\t\tif(mypair.first > 1) {\n    \t\t\t\tmyvec.push_back({mypair.first-1, mypair.second});\n    \t\t\t}\n    \t\t}\n    \t\tfor(auto e : myvec) mypq.push(e);\n    \t\tlen -= cnt;\n    \t}\n    \treturn res;\n    }\n};\n"
  },
  {
    "path": "cpp/351-360/Russian Doll Envelopes.cpp",
    "content": "class Solution {\npublic:\n    int maxEnvelopes(vector<pair<int, int>>& envelopes) {\n        auto Cmp = [&](const pair<int, int> a, const pair<int, int> b) { \n            if(a.first < b.first) return true;\n            if(a.first == b.first && a.second > b.second) return true;\n            return false;\n        };\n        auto Cmp2 = [&](const pair<int, int> a, const pair<int, int> b) { \n            return a.second < b.second;\n        };\n        sort(envelopes.begin(), envelopes.end(), Cmp);\n\n        vector<pair<int, int>> res;\n        for (int i=0; i<envelopes.size(); i++) {\n            auto it = std::lower_bound(res.begin(), res.end(), envelopes[i], Cmp2);\n            if (it == res.end()) res.push_back(envelopes[i]);\n            else *it = envelopes[i];\n        }\n        return res.size();\n    }\n};\n"
  },
  {
    "path": "cpp/351-360/Sort Transformed Array.cpp",
    "content": "class Solution {\n    \n    int transform(int num, int a, int b, int c) {\n        return a * num * num + b * num + c;\n    }\n    \n    public:\n        vector<int> sortTransformedArray(vector<int>& nums, int a, int b, int c) {\n            vector<int> res(nums.size());\n            if (nums.size() == 0) return res;\n            int i = 0, j = nums.size() - 1;\n            if (a >= 0) {\n                int index = nums.size() - 1;\n                while (i <= j) {\n                    if (transform(nums[i], a, b, c) > transform(nums[j], a, b, c)) {\n                        res[index--] = transform(nums[i], a, b, c);\n                        i++;\n                    } else {\n                        res[index--] = transform(nums[j], a, b, c);\n                        j--;\n                    }\n                }\n            } else {\n                int index = 0;\n                while (i <= j) {\n                    if (transform(nums[i], a, b, c) < transform(nums[j], a, b, c)) {\n                        res[index++] = transform(nums[i], a, b, c);\n                        i++;\n                    } else {\n                        res[index++] = transform(nums[j], a, b, c);\n                        j--;\n                    }\n                }\n            }\n            return res;\n        }\n};\n"
  },
  {
    "path": "cpp/361-370/Bomb Enemy.cpp",
    "content": "class Solution {\npublic:\n    int maxKilledEnemies(vector<vector<char>>& grid) {\n        int rows = grid.size();\n        if(rows == 0) return 0;\n        int cols = grid.back().size();\n        if(cols == 0) return 0;\n        vector<vector<int>> l2r(rows, vector<int>(cols, 0));\n        vector<vector<int>> r2l(rows, vector<int>(cols, 0));\n        vector<vector<int>> u2d(rows, vector<int>(cols, 0));\n        vector<vector<int>> d2u(rows, vector<int>(cols, 0));\n        \n        for(int i = 0;i < rows;i++) {\n            int cnt(0);\n            for(int j = 0;j < cols;j++) {\n                if(grid[i][j] == 'W') {\n                    cnt = 0;\n                } else if(grid[i][j] == 'E') {\n                    cnt++;\n                } else {\n                    l2r[i][j] = cnt;\n                }\n            }\n        }\n        \n        for(int i = 0;i < rows;i++) {\n            int cnt(0);\n            for(int j = cols-1;j >= 0;j--) {\n                if(grid[i][j] == 'W') {\n                    cnt = 0;\n                } else if(grid[i][j] == 'E') {\n                    cnt++;\n                } else {\n                    r2l[i][j] = cnt;\n                }\n            }\n        }\n        \n        for(int i = 0;i < cols;i++) {\n            int cnt(0);\n            for(int j = 0;j < rows;j++) {\n                if(grid[j][i] == 'W') {\n                    cnt = 0;\n                } else if(grid[j][i] == 'E') {\n                    cnt++;\n                } else {\n                    u2d[j][i] = cnt;\n                }\n            }\n        }\n        \n        for(int i = 0;i < cols;i++) {\n            int cnt(0);\n            for(int j = rows-1;j >= 0;j--) {\n                if(grid[j][i] == 'W') {\n                    cnt = 0;\n                } else if(grid[j][i] == 'E') {\n                    cnt++;\n                } else {\n                    d2u[j][i] = cnt;\n                }\n            }\n        }\n        \n        int res(0);\n        \n        for(int i = 0;i < rows;i++) {\n            for(int j = 0;j < cols;j++) {\n                res = max(res, l2r[i][j]+r2l[i][j]+u2d[i][j]+d2u[i][j]);\n            }\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/361-370/Design Hit Counter.cpp",
    "content": "class HitCounter {\n    \n    map<int, int> mymap;\n    int total;\n    \npublic:\n    /** Initialize your data structure here. */\n    HitCounter() {\n        total = 0;\n    }\n    \n    /** Record a hit.\n        @param timestamp - The current timestamp (in seconds granularity). */\n    void hit(int timestamp) {\n        mymap[timestamp]++;\n        total++;\n    }\n    \n    /** Return the number of hits in the past 5 minutes.\n        @param timestamp - The current timestamp (in seconds granularity). */\n    int getHits(int timestamp) {\n        \n        while(!mymap.empty()) {\n            auto it = mymap.begin();\n            if(timestamp - it->first >= 300) {\n                total -= it->second;\n                mymap.erase(it);\n            } else {\n                break;\n            }\n        }\n        \n        return total;\n    }\n};\n\n/**\n * Your HitCounter object will be instantiated and called as such:\n * HitCounter obj = new HitCounter();\n * obj.hit(timestamp);\n * int param_2 = obj.getHits(timestamp);\n */\n"
  },
  {
    "path": "cpp/361-370/Find Leaves of Binary Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    int dfs(TreeNode* root, vector<vector<int>> &myvec) {\n        if (root == nullptr) return 0;\n        int ldepth = dfs(root->left, myvec);\n        int rdepth = dfs(root->right, myvec);\n        int depth = 1 + max(ldepth, rdepth);\n        if (myvec.size() < depth) {\n            myvec.resize(myvec.size()+1);\n        }\n        myvec[depth-1].push_back(root->val);\n        return depth;\n    }\n    \npublic:\n    vector<vector<int>> findLeaves(TreeNode* root) {\n        vector<vector<int>> myvec;\n        dfs(root, myvec);\n        return myvec;\n    }\n};\n"
  },
  {
    "path": "cpp/361-370/Largest Divisible Subset.cpp",
    "content": "class Solution {\npublic:\n    vector<int> largestDivisibleSubset(vector<int>& nums) {\n        \n        vector<int> res;\n        if(nums.size() == 0) return res;\n        \n        sort(nums.begin(), nums.end());\n        \n        vector<int> previous(nums.size(), -1);\n        vector<int> size(nums.size(), 1);\n        \n        int result_idx(0);\n        int max_size(0);\n        \n        for(int i = 1;i < nums.size();i++) {\n            \n            int idx(-1);\n            int msize(1);\n            \n            for(int j = 0;j < i;j++) {\n                \n                if(nums[i] % nums[j] == 0) {\n                    if(size[j] + 1 > msize) {\n                        msize = size[j]+1;\n                        idx = j;\n                    }\n                }\n                \n            }\n            \n            previous[i] = idx;\n            size[i] = msize;\n            \n            if(msize > max_size) {\n                result_idx = i;\n                max_size = msize;\n            }\n        }\n        \n        while(result_idx >= 0) {\n            res.push_back(nums[result_idx]);\n            result_idx = previous[result_idx];\n        }\n        \n        reverse(res.begin(), res.end());\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/361-370/Max Sum of Rectangle No Larger Than K.cpp",
    "content": "class Solution {\n    \npublic:\n    int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {\n        if (matrix.empty()) return 0;\n        int rows = matrix.size();\n        int cols = matrix[0].size();\n        int res(INT_MIN);\n        \n        for(int col1 = 0; col1 < cols;col1++) {\n            \n            vector<int> vec(rows, 0);\n            \n            for(int col2 = col1;  col2 < cols;col2++) {\n                \n                for(int k = 0;k < rows;k++) {\n                    vec[k] += matrix[k][col2];\n                }\n                \n                set<int> cumset;\n                cumset.insert(0);\n                int best=INT_MIN, cum=0;\n                for(int i = 0;i < rows;i++)\n                {\n                    cum+=vec[i];\n                    set<int>::iterator sit=cumset.lower_bound(cum-k);\n                    if(sit!=cumset.end())best=max(best,cum-*sit);\n                    cumset.insert(cum);\n                }\n                res = max(res, best);\n            }\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/361-370/Nested List Weight Sum II.cpp",
    "content": "/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * class NestedInteger {\n *   public:\n *     // Return true if this NestedInteger holds a single integer, rather than a nested list.\n *     bool isInteger() const;\n *\n *     // Return the single integer that this NestedInteger holds, if it holds a single integer\n *     // The result is undefined if this NestedInteger holds a nested list\n *     int getInteger() const;\n *\n *     // Return the nested list that this NestedInteger holds, if it holds a nested list\n *     // The result is undefined if this NestedInteger holds a single integer\n *     const vector<NestedInteger> &getList() const;\n * };\n */\nclass Solution {\npublic:\n    int depthSumInverse(vector<NestedInteger>& nestedList) {\n        int unweighted = 0, weighted = 0;\n        while (nestedList.size() > 0) {\n            vector<NestedInteger> nextLevel;\n            for (NestedInteger ni : nestedList) {\n                if (ni.isInteger()) {\n                    unweighted += ni.getInteger();\n                } else {\n                    for(NestedInteger e : ni.getList())\n                        nextLevel.push_back(e);\n                }\n            }\n            weighted += unweighted;\n            nestedList = nextLevel;\n        }\n        return weighted;\n    }\n};\n"
  },
  {
    "path": "cpp/361-370/Plus One Linked List.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\n    \n    ListNode* reverseList(ListNode* head) {\n        ListNode *tmp(nullptr), *prev(nullptr);\n        while (head != nullptr) {\n            tmp = head->next;\n            head->next = prev;\n            prev = head;\n            head = tmp;\n        }\n        return prev;\n    }\n    \npublic:\n    ListNode* plusOne(ListNode* head) {\n        ListNode* tail = reverseList(head);\n        ListNode* tmptail = tail;\n        int carry(1);\n        while (tail || carry > 0) {\n            if (tail->val + carry < 10) {\n                tail->val ++;\n                break;\n            } else {\n                tail->val = 0;\n                if (tail->next != nullptr) {\n                    tail = tail->next;\n                } else {\n                    ListNode *newtail = new ListNode(1);\n                    tail->next = newtail;\n                    break;\n                }\n            }\n        }\n        return reverseList(tmptail);\n    }\n};\n"
  },
  {
    "path": "cpp/361-370/Range Addition.cpp",
    "content": "class Solution {\npublic:\n    vector<int> getModifiedArray(int length, vector<vector<int>>& updates) {\n        \n        //unordered_map<int, int> mymap;\n        \n        int mymap[150000] = {0};\n        \n        for(const vector<int> &vec : updates) {\n            mymap[vec[0]] += vec[2];\n            mymap[vec[1]+1] -= vec[2];\n        }\n        \n        vector<int> myvec(length, 0);\n        \n        int v(0);\n        \n        for(int i = 0;i < length;i++) {\n            v = v + mymap[i];\n            myvec[i] = v;\n        }\n        \n        return myvec;\n        \n    }\n};\n"
  },
  {
    "path": "cpp/361-370/Valid Perfect Square.cpp",
    "content": "class Solution {\npublic:\n    bool isPerfectSquare(int num) {\n        int i = 1;\n        int j = num;\n        \n        while (i <= j) {\n            int mid = i + (j - i) / 2;\n            \n            if ((long)mid * (long)mid == (long)num) return true;\n            \n            if ((long)mid * (long)mid > (long)num) {\n                j = mid - 1;\n            } else {\n                i = mid + 1;\n            }\n        }\n        \n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/361-370/Water and Jug Problem.cpp",
    "content": "class Solution {\npublic:\n    bool canMeasureWater(int x, int y, int z) {\n        if(x > y) return canMeasureWater(y, x, z);\n        if(z == 0) return true;\n        int g = gcd(x,y);\n        if(z <= (x+y) && z % g == 0) return true;\n        return false;\n    }\nprivate:\n    int gcd(int a, int b){\n        return b == 0?a:gcd(b, a%b);\n    }\n};\n"
  },
  {
    "path": "cpp/371-380/Combination Sum IV.cpp",
    "content": "class Solution {\npublic:\n    int combinationSum4(vector<int>& nums, int target) {\n        vector<int> dp(target+1, 0);\n        dp[0] = 1;\n        \n        for (int i = 1;i <= target;i++)\n            for (int k = 0;k < nums.size();k++)\n                if (i - nums[k] >= 0)\n                    dp[i] += dp[i - nums[k]];\n        \n        return dp[target];\n    }\n};\n"
  },
  {
    "path": "cpp/371-380/Design Phone Directory.cpp",
    "content": "class PhoneDirectory {\n    bool *used;\n    queue<int> avaliable;\npublic:\n    /** Initialize your data structure here\n        @param maxNumbers - The maximum numbers that can be stored in the phone directory. */\n    PhoneDirectory(int maxNumbers) {\n        for(int i = 0;i < maxNumbers;i++) {\n            avaliable.emplace(i);\n        }\n        used = new bool[maxNumbers];\n        memset(used, false, maxNumbers);\n    }\n    \n    /** Provide a number which is not assigned to anyone.\n        @return - Return an available number. Return -1 if none is available. */\n    int get() {\n        if (!avaliable.empty()) {\n            int value = avaliable.front();\n            avaliable.pop();\n            used[value] = true;\n            return value;\n        }\n        return -1;\n    }\n    \n    /** Check if a number is available or not. */\n    bool check(int number) {\n        return !used[number];\n    }\n    \n    /** Recycle or release a number. */\n    void release(int number) {\n        if (used[number]) {\n            used[number] = false;\n            avaliable.emplace(number);\n        }\n    }\n};\n\n/**\n * Your PhoneDirectory object will be instantiated and called as such:\n * PhoneDirectory obj = new PhoneDirectory(maxNumbers);\n * int param_1 = obj.get();\n * bool param_2 = obj.check(number);\n * obj.release(number);\n */\n"
  },
  {
    "path": "cpp/371-380/Find K Pairs with Smallest Sums.cpp",
    "content": "class Solution {\n    \n    typedef pair<int, vector<int>::iterator> mm;\n    \npublic:\n    vector<vector<int>> kSmallestPairs(vector<int>& nums1, vector<int>& nums2, int k) {\n        vector<vector<int>> res;\n        \n        auto cmp = [] (const mm& p1, const mm& p2) {\n            return p1.first + *(p1.second) > p2.first + *(p2.second);\n        };\n        priority_queue<mm, vector<mm>, decltype(cmp)> pq(cmp);\n        \n        // Given nums1 = [1,7,11], nums2 = [2,4,6],  k = 3\n        // {1, iter}  {7, iter}  {11, iter}\n        for (int v : nums1) {\n            pq.push({v, nums2.begin()});\n        }\n        \n        for (int i = 0; i < k && !pq.empty(); i++) {\n            auto ele = pq.top();\n            pq.pop();\n            res.push_back({ele.first, *(ele.second)});\n            ele.second++;\n            if (ele.second != nums2.end()) {\n                pq.push({ele.first, ele.second});\n            }\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/371-380/Guess Number Higher or Lower II.cpp",
    "content": "class Solution {\npublic:\n    int getMoneyAmount(int n) {\n        vector<vector<int>>table(n+1, vector<int>(n+1,0));\n        for (int j = 2;j <= n; j++) {\n            for (int i = j-1; i > 0; i--) {\n                int temp_min = INT_MAX;\n                for (int k = i; k < j; k++) {\n                    int localMax = k + max(table[i][k==i?k:k-1], table[k+1][j]);\n                    temp_min = min(temp_min, localMax);\n                }\n                table[i][j] = temp_min;\n            }\n        }\n        return table[1][n];\n    }\n};\n"
  },
  {
    "path": "cpp/371-380/Guess Number Higher or Lower.cpp",
    "content": "// Forward declaration of guess API.\n// @param num, your guess\n// @return -1 if my number is lower, 1 if my number is higher, otherwise return 0\nint guess(int num);\n\nclass Solution {\npublic:\n    int guessNumber(int n) {\n        int low = 1, high = n;\n        \n        while (low <= high) {\n            int mid = ((long)low+(long)high)/2;\n            int flag = guess(mid);\n            if(flag == 0) return mid;\n            else if(flag == 1) low = mid + 1;\n            else high = mid - 1;\n        }\n        \n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/371-380/Insert Delete GetRandom O(1).cpp",
    "content": "class RandomizedSet {\n    unordered_map<int, int> value_index_map;\n    vector<int> values;\npublic:\n    /** Initialize your data structure here. */\n    RandomizedSet() {\n        \n    }\n    \n    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */\n    bool insert(int val) {\n        if (value_index_map.count(val) > 0) {\n            return false;\n        }\n        value_index_map[val] = values.size();\n        values.push_back(val);\n        return true;\n    }\n    \n    /** Removes a value from the set. Returns true if the set contained the specified element. */\n    bool remove(int val) {\n        if (value_index_map.count(val) == 0) {\n            return false;\n        }\n        int index = value_index_map[val];\n        value_index_map[values.back()] = index;\n        value_index_map.erase(val);\n        swap(values[index], values.back());\n        values.erase(values.end() - 1);\n        return true;\n    }\n    \n    /** Get a random element from the set. */\n    int getRandom() {\n        return values[rand() % values.size()];\n    }\n};\n\n/**\n * Your RandomizedSet object will be instantiated and called as such:\n * RandomizedSet obj = new RandomizedSet();\n * bool param_1 = obj.insert(val);\n * bool param_2 = obj.remove(val);\n * int param_3 = obj.getRandom();\n */\n"
  },
  {
    "path": "cpp/371-380/Kth Smallest Element in a Sorted Matrix.cpp",
    "content": "class Solution {\npublic:\n\tint kthSmallest(vector<vector<int>>& matrix, int k) {\n\t\tint n = matrix.size();\n\t\tint L = matrix[0][0], R = matrix[n - 1][n - 1];\n\t\twhile (L < R) {\n\t\t\tint mid = L + ((R - L) >> 1);\n\t\t\tint temp = search_lower_than_mid(matrix, mid);\n\t\t\tif (temp < k) L = mid + 1;\n\t\t\telse R = mid;\n\t\t}\n\t\treturn L;\n\t}\n\tint search_lower_than_mid(const vector<vector<int>>& matrix, int x) {\n        int n = matrix.size();\n\t\tint i = n - 1, j = 0, cnt = 0;\n\t\twhile (i >= 0 && j < n) {\n\t\t\tif (matrix[i][j] <= x) {\n\t\t\t\tj++;\n\t\t\t\tcnt += i + 1;\n\t\t\t}\n\t\t\telse i--;\n\t\t}\n\t\treturn cnt;\n\t}\n};\n"
  },
  {
    "path": "cpp/371-380/Sum of Two Integers.cpp",
    "content": "class Solution {\n    \npublic:\n    int getSum(int a, int b) {\n        if(a == 0) return b;\n        return getSum( (a&b) << 1, a ^ b);\n    }\n};\n"
  },
  {
    "path": "cpp/371-380/Super Pow.cpp",
    "content": "class Solution {\n    \n    int help(int a, int b) {\n        int res(1);\n        a %= 1337;\n        for (int i = 0; i < b; i++) {\n            res = (res * a) % 1337;\n        }\n        return res;\n    }\n    \npublic:\n    int superPow(int a, vector<int>& b) {\n        if (b.empty()) return 1;\n        int last_digit = b.back();\n        b.pop_back();\n        return help(superPow(a, b), 10) * help(a, last_digit) % 1337;\n    }\n};\n"
  },
  {
    "path": "cpp/371-380/Wiggle Subsequence.cpp",
    "content": "class Solution {\npublic:\n    int wiggleMaxLength(vector<int>& nums) {\n        int flag(0), count(1);\n        for (int i = 1; i < nums.size(); ++i) {\n            if (nums[i] > nums[i-1] && (flag == -1 || count == 1)) {\n                ++count;\n                flag = 1;\n            }\n            else if (nums[i] < nums[i-1] && (flag == 1 || count == 1)) {\n                ++count;\n                flag = -1;\n            }\n        }\n        return nums.size() == 0 ? 0 : count;\n    }\n};\n"
  },
  {
    "path": "cpp/381-390/Elimination Game.cpp",
    "content": "/*\n1 2 3 4 5 6 7 8 9\n2 4 6 8(1 2 3 4)\n*/\n\nclass Solution {\npublic:\n    // https://discuss.leetcode.com/topic/58042/c-1-line-solution-with-explanation/2\n    // After first elimination, all the rest numbers are even numbers.\n    // Divide by 2, we get a continuous new sequence from 1 to n / 2.\n    // For this sequence we start from right to left as the first elimination.\n    // Then the original result should be two times the mirroring result of lastRemaining(n / 2).\n    int lastRemaining(int n) {\n        // Great answer. In fact, we can prove that \"ML(1...n) + MR(1...n) = 1 + n\" holds for any n >= 2, where ML(1...n) means removing elements from left to right first and MR(1...n) means removing elements from right to left first.\n        return n == 1 ? 1 : 2 * (1 + n / 2 - lastRemaining(n / 2));\n    }\n};\n"
  },
  {
    "path": "cpp/381-390/Find the Difference.cpp",
    "content": "class Solution {\npublic:\n    char findTheDifference(string s, string t) {\n        char onemore(0);\n        for (char ch : s) onemore ^= ch;\n        for (char ch : t) onemore ^= ch;\n        return onemore;\n    }\n};\n"
  },
  {
    "path": "cpp/381-390/First Unique Character in a String.cpp",
    "content": "class Solution {\npublic:\n    int firstUniqChar(string s) {\n        map<char, int> mymap;\n        for (char ch : s) {\n            mymap[ch]++;\n        }\n        for (int i = 0; i < s.length(); i++) {\n            if (mymap[s[i]] == 1) {\n                return i;\n            }\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/381-390/Insert Delete GetRandom O(1) - Duplicates allowed.cpp",
    "content": "class RandomizedCollection {\n    unordered_map<int, set<int>> value_index_map;\n    vector<int> values;\npublic:\n    /** Initialize your data structure here. */\n    RandomizedCollection() {\n        \n    }\n    \n    /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */\n    bool insert(int val) {\n        if (value_index_map.count(val) == 0) {\n            set<int> tmp;\n            value_index_map[val] = tmp;\n        }\n        value_index_map[val].insert(values.size());\n        values.push_back(val);\n        return value_index_map[val].size() == 1;\n    }\n    \n    /** Removes a value from the collection. Returns true if the collection contained the specified element. */\n    bool remove(int val) {\n        if (value_index_map.count(val) == 0 || value_index_map[val].empty()) {\n            return false;\n        }\n        int index = *value_index_map[val].begin();\n        value_index_map[values.back()].insert(index);\n        value_index_map[values.back()].erase(values.size()-1);\n        value_index_map[val].erase(index);\n        swap(values[index], values.back());\n        values.erase(values.end() - 1);\n        return true;\n    }\n    \n    /** Get a random element from the collection. */\n    int getRandom() {\n        return values[rand() % values.size()];\n    }\n};\n\n/**\n * Your RandomizedCollection object will be instantiated and called as such:\n * RandomizedCollection obj = new RandomizedCollection();\n * bool param_1 = obj.insert(val);\n * bool param_2 = obj.remove(val);\n * int param_3 = obj.getRandom();\n */\n"
  },
  {
    "path": "cpp/381-390/Lexicographical Numbers.cpp",
    "content": "class Solution {\n    \n    void dfs(int curr, int n, vector<int>& result, int& index) {\n        if (curr <= n) {\n            result[index++] = curr;\n        } else {\n            return;   \n        }\n        \n        for (int i = 0; i <= 9; i++) {\n            dfs(curr*10 + i, n, result, index);\n        }\n    }\n    \npublic:\n    vector<int> lexicalOrder(int n) {\n        vector<int> result(n);\n        int index = 0;\n        \n        for (int i = 1; i <= 9; i++)\n            dfs(i, n, result, index);\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/381-390/Linked List Random Node.cpp",
    "content": "class Solution {\n    vector<int> myvec;\npublic:\n    /** @param head The linked list's head. Note that the head is guanranteed to be not null, so it contains at least one node. */\n    Solution(ListNode* head) {\n        while (head != nullptr) {\n            myvec.push_back(head->val);\n            head = head->next;\n        }\n    }\n    \n    /** Returns a random node's value. */\n    int getRandom() {\n        return myvec[rand()%myvec.size()];\n    }\n};\n\n/**\n * Your Solution object will be instantiated and called as such:\n * Solution obj = new Solution(head);\n * int param_1 = obj.getRandom();\n */\n"
  },
  {
    "path": "cpp/381-390/Longest Absolute File Path.cpp",
    "content": "class Solution {\npublic:\n    int lengthLongestPath(string input) {\n        stack<string> myfiles;\n        \n        int index = 0;\n        int ans = 0;\n        int temp = 0;\n        \n        while (true) {\n            int nIndex = input.find(\"\\n\", index);\n            string str = nIndex >= 0 ? input.substr(index, nIndex - index) : input.substr(index);\n            \n            int level = 0;\n            while (str[level] == '\\t') {\n                level++;\n            }\n            \n            string filename = str.substr(level);\n            while (level < myfiles.size()) {\n                string topFile = myfiles.top();\n                myfiles.pop();\n                temp -= topFile.length() ;\n            }\n            \n            myfiles.push(filename);\n            temp += filename.length();\n                \n            if (filename.find('.') != -1) {\n                ans = max(ans, temp + (int)myfiles.size() - 1);\n            }\n            \n            if (nIndex < 0) break;\n            index = nIndex + 1;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/381-390/Mini Parser.cpp",
    "content": "/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * class NestedInteger {\n *   public:\n *     // Constructor initializes an empty nested list.\n *     NestedInteger();\n *\n *     // Constructor initializes a single integer.\n *     NestedInteger(int value);\n *\n *     // Return true if this NestedInteger holds a single integer, rather than a nested list.\n *     bool isInteger() const;\n *\n *     // Return the single integer that this NestedInteger holds, if it holds a single integer\n *     // The result is undefined if this NestedInteger holds a nested list\n *     int getInteger() const;\n *\n *     // Set this NestedInteger to hold a single integer.\n *     void setInteger(int value);\n *\n *     // Set this NestedInteger to hold a nested list and adds a nested integer to it.\n *     void add(const NestedInteger &ni);\n *\n *     // Return the nested list that this NestedInteger holds, if it holds a nested list\n *     // The result is undefined if this NestedInteger holds a single integer\n *     const vector<NestedInteger> &getList() const;\n * };\n */\nclass Solution {\npublic:\n    NestedInteger deserialize(string s) {\n        if (s.empty()) {\n            return NestedInteger();\n        }\n        if (isdigit(s[0]) || s[0] == '-') {\n            return NestedInteger(stoi(s));\n        }\n        s = s.substr(1, s.length()-2);\n        NestedInteger result;\n        int i(0);\n        while (i < s.length()) {\n            int j = i;\n            int counter(0);\n            while (j < s.length()) {\n                if (s[j] == '[') {\n                    counter++;\n                } else if (s[j] == ']') {\n                    counter--;\n                } else if (s[j] == ',') {\n                    if (counter == 0) {\n                        result.add(deserialize(s.substr(i, j-i)));\n                        break;\n                    }\n                }\n                j++;\n            }\n            if (j >= s.length()) {\n                result.add(deserialize(s.substr(i)));\n                break;\n            }\n            i = j+1;\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/381-390/Ransom Note.cpp",
    "content": "class Solution {\npublic:\n    bool canConstruct(string ransomNote, string magazine) {\n        int chs[128] = {0};\n        for (char ch : magazine) chs[ch]++;\n        for (char ch : ransomNote)\n            if (--chs[ch] < 0)\n                return false;\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/381-390/Shuffle an Array.cpp",
    "content": "class Solution {\n    vector<int> nums;\npublic:\n    Solution(vector<int> nums) {\n        this->nums = nums;\n    }\n    \n    /** Resets the array to its original configuration and return it. */\n    vector<int> reset() {\n        return nums;\n    }\n    \n    /** Returns a random shuffling of the array. */\n    vector<int> shuffle() {\n        vector<int> result(nums);\n        for (int i = 0;i < result.size();i++) {\n            int pos = rand()%(result.size()-i);\n            swap(result[i+pos], result[i]);\n        }\n        return result;\n    }\n};\n\n/**\n * Your Solution object will be instantiated and called as such:\n * Solution obj = new Solution(nums);\n * vector<int> param_1 = obj.reset();\n * vector<int> param_2 = obj.shuffle();\n */\n"
  },
  {
    "path": "cpp/391-400/Decode String.cpp",
    "content": "class Solution {\n    \n    string solve(const string& s, int& i) {\n        string result;\n        while (i < s.length() && s[i] != ']') {\n            int d = 0;\n            while (isdigit(s[i])) {\n                d = 10 * d + (s[i] - '0');\n                i++;\n            }\n            \n            if (s[i] == '[') {\n                i++;\n                string temp = solve(s, i);\n                while (d-- > 0) result += temp;\n            } else {\n                result += s[i];\n            }\n            i++;          \n        }\n        return result;\n    }\n    \npublic:\n    string decodeString(string s) {\n        int i = 0;\n        return solve(s, i);\n    }\n};\n"
  },
  {
    "path": "cpp/391-400/Evaluate Division.cpp",
    "content": "class Solution {\npublic:\n    vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> query) {\n        unordered_map<string, int> varID; // map var name to its ID \n        vector<int> par;                  // par[v2]==v1 ;  v1 is v2's parent\n        vector<double> parEq;             // parEq[v2]==t ; v1 is t times of v2 \n\n        for (int i=0; i<equations.size(); i++) { // process equations\n            const string& v1Name = equations[i].first;\n            const string& v2Name = equations[i].second;\n            double x = values[i]; // v1 is x times of v2\n            int v1, v2;\n            if (varID.count(v1Name)==0) { //new variable\n                v1 = par.size();\n                par.push_back(v1); //par[v1]==v1, v1 is itself's parent\n                parEq.push_back(1); \n                varID[v1Name] = v1;\n            } else v1 = varID[v1Name];\n            if (varID.count(v2Name)==0) {\n                v2 = par.size();\n                par.push_back(v2);  \n                parEq.push_back(1);\n                varID[v2Name] = v2; \n            } else  v2 = varID[v2Name];\n\n            double t1, t2;\n            int r1 = findRoot(par, parEq, v1, t1); //r1 is t1 times of v1\n            int r2 = findRoot(par, parEq, v2, t2); //r2 is t2 times of v2\n            par[r2] = r1;\n            parEq[r2] = t1 * x / t2;           //do simple math here\n        }\n\n        vector<double> res;\n        for (const auto& q : query) {\n            int v1, v2;\n            if (varID.count(q.first)==1 && varID.count(q.second)==1 ) {\n                v1 = varID[q.first];\n                v2 = varID[q.second];\n            } else {\n                res.push_back(-1);\n                continue;\n            }\n            double t1, t2;\n            int r1 = findRoot(par, parEq, v1, t1); //r1 is t1 times of v1\n            int r2 = findRoot(par, parEq, v2, t2); //r2 is t2 times of v2\n            if (r1 != r2) res.push_back(-1);\n            else res.push_back(t2/t1);\n        }\n        return res;\n    }\n    \n    int findRoot(vector<int>& par, vector<double>& parEq, int v, double& t) {\n        t = 1;\n        while (v != par[v]) {\n            // path compression\n            parEq[v] = parEq[v] * parEq[par[v]];\n            par[v] = par[par[v]];\n            // climb up\n            t *= parEq[v];\n            v = par[v];\n        }\n        return v;\n    }\n};\n"
  },
  {
    "path": "cpp/391-400/Integer Replacement.cpp",
    "content": "class Solution \n{\npublic:\n    int integerReplacement(int n) {\n        if (n == 1)\n            return 0;\n        if (n == 3)\n            return 2;\n        if (n == INT_MAX)\n            return 32;\n        \n        if (n & 1)\n            if ((n + 1) % 4 == 0)\n                return 1+integerReplacement(n + 1);\n            else\n                return 1+integerReplacement(n - 1);\n        else\n            return 1+integerReplacement(n / 2);\n    }\n};\n"
  },
  {
    "path": "cpp/391-400/Is Subsequence.cpp",
    "content": "class Solution {\npublic:\n    bool isSubsequence(string s, string t) {\n        if (s.empty()) return true;\n        int i = 0;\n        for (char ch : t) {\n            if (ch == s[i]) {\n                i++;\n            }\n            if (i >= s.length()) return true;\n        }\n        return i == s.length();\n    }\n};\n"
  },
  {
    "path": "cpp/391-400/Longest Substring with At Least K Repeating Characters.cpp",
    "content": "class Solution {\n    \n    int dfs(const string& s, int k, int start, int end) {\n        int size = end-start+1;\n        if(size == 0 || k > size)   return 0;\n        if(k == 0)  return size;\n        \n        int Map[26] = {0};\n        for(int i = start; i <= end; i++){\n            Map[s[i]-'a']++;\n        }\n        \n        int idx = start;\n        while(idx <= end && Map[s[idx]-'a'] >= k)    idx++;\n        if(idx == end+1) return size;\n        \n        int left = dfs(s, k, start, idx-1);\n        int right = dfs(s, k, idx+1, end);\n        \n        return max(left, right);\n    }\n    \npublic:\n    int longestSubstring(string s, int k) {\n        return dfs(s, k, 0, s.length()-1);\n    }\n};\n"
  },
  {
    "path": "cpp/391-400/Nth Digit.cpp",
    "content": "class Solution {\n    \n    int process(long long num, long long n) {\n        int digit = (n-1)/num;\n        int base = 1;\n        for (int i = 1;i < num;i++) base *= 10;\n        base += digit;\n        return to_string(base)[(n-1)%num] - '0';\n    }\n    \npublic:\n    int findNthDigit(int n) {\n        long long temp = 9, num = 1;\n        while (true) {\n            if (n - temp*num <= 0) break;\n            n = n - temp*num;\n            temp *= 10;\n            num++;\n        }\n        return process(num, n);\n    }\n};\n"
  },
  {
    "path": "cpp/391-400/Perfect Rectangle.cpp",
    "content": "class Solution {\npublic:\n    bool isRectangleCover(vector<vector<int>>& rectangles) {\n        set<string> points;\n        int area = 0;\n        int leftBottomX = INT_MAX, leftBottomY = INT_MAX, rightTopX = 0, rightTopY = 0;\n        \n        for (const auto& rectangle : rectangles) {\n            leftBottomX = min(leftBottomX, rectangle[0]);\n            leftBottomY = min(leftBottomY, rectangle[1]);\n            rightTopX = max(rightTopX, rectangle[2]);\n            rightTopY = max(rightTopY, rectangle[3]);\n            \n            string p1 = to_string(rectangle[0]) + \":\" + to_string(rectangle[1]);\n            string p2 = to_string(rectangle[2]) + \":\" + to_string(rectangle[3]);\n            string p3 = to_string(rectangle[0]) + \":\" + to_string(rectangle[3]);\n            string p4 = to_string(rectangle[2]) + \":\" + to_string(rectangle[1]);\n            \n            vector<string> four{p1, p2, p3, p4};\n            for (const string p : four) {\n                if (points.count(p) > 0) {\n                    points.erase(p);\n                } else {\n                    points.insert(p);\n                }\n            }\n            \n            area += (rectangle[2] - rectangle[0]) * (rectangle[3] - rectangle[1]);\n        }\n        \n        if (area != (rightTopX - leftBottomX) * (rightTopY - leftBottomY)) return false;\n        if (points.size() != 4) return false;\n        \n        // Verfify thet are corner points\n        if (points.count(to_string(leftBottomX) + \":\" + to_string(leftBottomY)) == 0) return false;\n        if (points.count(to_string(leftBottomX) + \":\" + to_string(rightTopY)) == 0) return false;\n        if (points.count(to_string(rightTopX) + \":\" + to_string(leftBottomY)) == 0) return false;\n        if (points.count(to_string(rightTopX) + \":\" + to_string(rightTopY)) == 0) return false;\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/391-400/Random Pick Index.cpp",
    "content": "class Solution {\npublic:\n    vector<int> n;\n    Solution(vector<int> nums)  {\n        n = nums;\n    }\n    \n    int pick(int target) {\n        int count = 0, res = -1;\n        for (int i = 0; i < n.size(); ++i) {\n            if (n[i] != target) continue;\n            if (++count == 1) res = i;\n            else if (!(rand()%count)) res = i;\n        }\n        return res;\n    }\n};\n\n/**\n * Your Solution object will be instantiated and called as such:\n * Solution obj = new Solution(nums);\n * int param_1 = obj.pick(target);\n */\n"
  },
  {
    "path": "cpp/391-400/Rotate Function.cpp",
    "content": "class Solution {\n    \npublic:\n    int maxRotateFunction(vector<int>& A) {\n        \n        int res(INT_MIN), sum(0), temp(0);\n        int n = A.size();\n        \n        int i(1), j(0);\n        \n        int times = 1;\n        for (int k = 1; k < n; k++) {\n            sum += A[k];\n            temp += times * A[k];\n            times++;\n        }\n        \n        res = temp;\n        \n        while (j < A.size()) {\n            temp -= sum;\n            temp += (n-1) * A[j];\n            sum = sum - A[i] + A[j];\n            i = (++i)%n;\n            j++;\n            res = max(res, temp);\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/391-400/UTF-8 Validation.cpp",
    "content": "class Solution {\npublic:\n    bool validUtf8(vector<int>& data) {\n        int count = 0;\n        for (auto c : data) {\n            if (count == 0) {\n                if ((c >> 5) == 0b110) count = 1;\n                else if ((c >> 4) == 0b1110) count = 2;\n                else if ((c >> 3) == 0b11110) count = 3;\n                else if ((c >> 7)) return false;\n            } else {\n                if ((c >> 6) != 0b10) return false;\n                count--;\n            }\n        }\n        return count == 0;\n    }\n};\n"
  },
  {
    "path": "cpp/401-410/Binary Watch.cpp",
    "content": "class Solution {\npublic:\n    vector<string> readBinaryWatch(int num) {\n        vector<string> rs;\n        for (int h = 0; h < 12; h++)\n            for (int m = 0; m < 60; m++)\n                if (bitset<10>((h << 6) + m).count() == num)\n                    rs.emplace_back(to_string(h) + (m < 10 ? \":0\" : \":\") + to_string(m));\n        return rs;\n    }\n};\n"
  },
  {
    "path": "cpp/401-410/Convert a Number to Hexadecimal.cpp",
    "content": "class Solution {\npublic:\n    string toHex(int num) {\n        if (num == 0) return \"0\";\n        vector<char> toHexChar = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};\n        string result;\n        while (num != 0 && result.size()<8){\n            result = toHexChar[num&15] + result;\n            num = num >> 4;\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/401-410/Frog Jump.cpp",
    "content": "class Solution {\n    \n    bool dfs(const vector<int>& stones, int stone_index, int speed, unordered_map<int, bool>& cache) {\n        if (stone_index == stones.size() - 1) return true;\n        \n        int key = (stone_index) | (speed << 12);\n        if (cache.count(key) > 0) {\n            return cache[key];\n        }\n        \n        for (int i = stone_index + 1; i < stones.size(); i++) {\n            int distance = stones[i] - stones[stone_index];\n            if (distance >= (speed - 1) && distance <= (speed + 1)) {\n                if (dfs(stones, i, distance, cache)) {\n                    return cache[key] = true;\n                }\n            }\n        }\n        return cache[key] = false;\n    }\n    \npublic:\n    bool canCross(vector<int>& stones) {\n        unordered_map<int, bool> cache;\n        return dfs(stones, 0, 0, cache);\n    }\n};\n"
  },
  {
    "path": "cpp/401-410/Longest Palindrome.cpp",
    "content": "class Solution {\npublic:\n    int longestPalindrome(string s) {\n        map<char, int> mymap;\n        for (char ch : s) {\n            mymap[ch]++;\n        }\n        \n        int res = 0;\n        bool odd = false;\n        for (const auto& ele : mymap) {\n            if (ele.second >= 2) {\n                res += ele.second % 2 == 0 ? ele.second : ele.second - 1;\n            } \n            \n            if (ele.second % 2 == 1) {\n                odd = true;\n            }\n        }\n        \n        return odd ? res + 1 : res;\n    }\n};\n"
  },
  {
    "path": "cpp/401-410/Queue Reconstruction by Height.cpp",
    "content": "class Solution {\npublic:\n    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {\n        auto comp = [](const pair<int, int>& p1, const pair<int, int>& p2) \n            { return p1.first > p2.first || (p1.first == p2.first && p1.second < p2.second); };\n        sort(people.begin(), people.end(), comp);\n        vector<pair<int, int>> res;\n        for (const auto& p : people) \n            res.insert(res.begin() + p.second, p);\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/401-410/Remove K Digits.cpp",
    "content": "class Solution {\npublic:\n    string removeKdigits(string num, int k) {\n        string res = \"\";\n        int n = num.size(), keep = n - k;\n        for (char c : num) {\n            while (k && res.size() && res.back() > c) {\n                res.pop_back();\n                --k;\n            }\n            res.push_back(c);\n        }\n        res.resize(keep);\n        while (!res.empty() && res[0] == '0') res.erase(res.begin());\n        return res.empty() ? \"0\" : res;\n    }\n};\n"
  },
  {
    "path": "cpp/401-410/Split Array Largest Sum.cpp",
    "content": "class Solution {\npublic:\n    typedef long long ll;\n\n    bool canSplit(vector<int>& nums, int m, ll sum) {\n        int c = 1;\n        ll s = 0;\n        for (int num : nums) {\n            s += num;\n            if (s > sum) {\n                s = num;\n                ++c;\n            }\n        }\n        return c <= m;\n    }\n\n    int splitArray(vector<int>& nums, int m) {\n        ll left = 0, right = 0;\n        for (int num : nums) {\n            left = max(left, (ll)num);\n            right += num;\n        }\n        while (left <= right) {\n            ll mid = left + (right-left)/2;\n            if (canSplit(nums, m, mid))\n                right = mid-1;\n            else\n                left = mid+1;\n        }\n        return left;\n    }\n};\n"
  },
  {
    "path": "cpp/401-410/Sum of Left Leaves.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int sumOfLeftLeaves(TreeNode* root) {\n        \n        if (!root) return 0;\n\n        if (root && root->left) {\n            if (!root->left->left && !root->left->right) return root->left->val + sumOfLeftLeaves(root->right);\n        }\n        \n        return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);\n    }\n};\n"
  },
  {
    "path": "cpp/401-410/Trapping Rain Water II.cpp",
    "content": "class Solution {\npublic:\n    int trapRainWater(vector<vector<int>>& heightMap) {\n        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> que;\n        int row = heightMap.size(), col = heightMap[0].size();\n        vector<vector<bool>> visited(row, vector<bool>(col, false));\n        int minimum = INT_MAX;\n        for (int i = 0; i < row; i++) {\n            for (int j = 0; j < col; j++) {\n                if (!(i==0 || i==row-1 || j==0 || j==col-1)) continue;\n                que.push({heightMap[i][j], i * col + j});\n                visited[i][j] = true;\n                minimum = min(minimum, heightMap[i][j]);\n            }\n        }\n        \n        pair<int, int> dir[4] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n        int ans = 0;\n        while (!que.empty()) {\n            pair<int, int> val = que.top();\n            que.pop();\n            int height = val.first;\n            int x = val.second / col;\n            int y = val.second % col;\n            minimum = max(minimum, height);\n            for (const pair<int, int>& d: dir) {\n                int nx = x + d.first;\n                int ny = y + d.second;\n                if (nx >= row || nx < 0 || ny < 0 || ny >= col || visited[nx][ny]) continue;\n                visited[nx][ny] = true;\n                if (heightMap[nx][ny] < minimum) {\n                    ans += minimum - heightMap[nx][ny];\n                }\n                que.push({heightMap[nx][ny], nx * col + ny});\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/401-410/Valid Word Abbreviation.cpp",
    "content": "class Solution {\npublic:\n    bool validWordAbbreviation(string word, string abbr) {\n        int p1 = 0, p2 = 0;\n        while (p1 < word.size() && p2 < abbr.size()) {\n            //If a digit starts with 0, abbr is invalid\n            if (abbr[p2] == '0')\n                return false;\n\n            //get the next digit\n            int num = 0;\n            while (p2 < abbr.size() && isdigit(abbr[p2])) {\n                num = num * 10 + abbr[p2] - '0';\n                p2++;\n            }\n            \n            //increment the pointer in words\n            p1 += num;\n          \n            //check current state is match or unmatch.\n            if (p1 == word.size() && p2 == abbr.size()) {\n                return true;\n            } else if (p1 >= word.size() || p2 >= abbr.size() || word[p1] != abbr[p2]) {\n                return false;\n            }\n            \n            p1++;\n            p2++;\n        }\n        \n        return p1 == word.size() && p2 == abbr.size();\n    }\n};\n"
  },
  {
    "path": "cpp/411-420/Add Strings.cpp",
    "content": "class Solution {\npublic:\n    string addStrings(string num1, string num2) {\n        string result;\n        int carry = 0;\n        int i1 = num1.length() - 1;\n        int i2 = num2.length() - 1;\n        while (i1 >= 0 || i2 >= 0 || carry > 0) {\n            int v1 = i1 >= 0 ? num1[i1] - '0' : 0;\n            int v2 = i2 >= 0 ? num2[i2] - '0' : 0;\n            int sum = v1 + v2 + carry;\n            result.push_back(sum % 10 + '0');\n            carry = sum / 10;\n            i1--;\n            i2--;\n        }\n        \n        reverse(begin(result), end(result));\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/411-420/Arithmetic Slices.cpp",
    "content": "class Solution {\npublic:\n    int numberOfArithmeticSlices(vector<int>& A) {\n        int n = A.size();\n        if (n < 3) return 0;\n        vector<int> dp(n, 0); // dp[i] means the number of arithmetic slices ending with A[i]\n        if (A[2]-A[1] == A[1]-A[0]) dp[2] = 1; // if the first three numbers are arithmetic or not\n        int result = dp[2];\n        for (int i = 3; i < n; ++i) {\n            // if A[i-2], A[i-1], A[i] are arithmetic, then the number of arithmetic slices ending with A[i] (dp[i])\n            // equals to:\n            //      the number of arithmetic slices ending with A[i-1] (dp[i-1], all these arithmetic slices appending A[i] are also arithmetic)\n            //      +\n            //      A[i-2], A[i-1], A[i] (a brand new arithmetic slice)\n            // it is how dp[i] = dp[i-1] + 1 comes\n            if (A[i]-A[i-1] == A[i-1]-A[i-2]) \n                dp[i] = dp[i-1] + 1;\n            result += dp[i]; // accumulate all valid slices\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/411-420/Battleships in a Board.cpp",
    "content": "class Solution {\npublic:\n    int countBattleships(vector<vector<char>>& board) {\n        if (board.empty() || board[0].empty()) { return 0; }\n        int m = board.size(), n = board[0].size(), cnt = 0;\n        \n        for (int r = 0; r < m; r++)\n            for (int c = 0; c < n; c++)\n                cnt += board[r][c] == 'X' && (r == 0 || board[r - 1][c] != 'X') && (c == 0 || board[r][c - 1] != 'X');\n        \n        return cnt;\n    }\n};\n"
  },
  {
    "path": "cpp/411-420/Fizz Buzz.cpp",
    "content": "class Solution {\npublic:\n    vector<string> fizzBuzz(int n) {\n        vector<string> ret_vec(n);\n        for (int i = 1; i <= n; ++i) {\n            if (i%3 == 0)\n                ret_vec[i-1] = \"Fizz\";\n            if (i%5 == 0)\n                ret_vec[i-1] += \"Buzz\";\n            if (ret_vec[i-1] == \"\")\n                ret_vec[i-1] += to_string(i);\n        }\n        return ret_vec;\n    }\n};\n"
  },
  {
    "path": "cpp/411-420/Minimum Unique Word Abbreviation.cpp",
    "content": "class Solution {\nstruct TrieNode {\n    TrieNode* childs[26];\n    TrieNode () {\n        memset(childs, 0, sizeof(childs));\n    }\n};\npublic:\n    string minAbbreviation(string target, vector<string>& dictionary) {\n        int n = target.size();\n        vector<string> dic;\n        // select word with the same length as target\n        for (const string& s:dictionary) {\n            if (s.size() == n) dic.emplace_back(s);\n        }\n        // build a trie; the depth of all leaves is the same\n        TrieNode* root = build(dic);\n        // generate abbreviation of target with length 1 until n-1; If it is valid, return\n        // For example, if the target is \"apple\", abbreviation has format of \"11p11\", whose length is 3\n        // This is to help function valid;\n        for (int i = 1; i <= n-1; i++) {\n            vector<string> abbrs;\n            generate_abb(abbrs, target, \"\", 0, i);\n            for (const string& s: abbrs) {\n                // encode(s) reformat \"11p11\" to \"2p2\"\n                if (valid(root, s, 0)) \n                    return encode(s);\n            }\n        }\n        return target;\n    }\nprivate:\n    void generate_abb(vector<string>& abbrs, string& s, string cur, int pos, int len) {\n        // backtracking, ending cases are len = 0 or len = 1;\n        if (pos == s.size()) {\n            if (len == 0) abbrs.push_back(cur);\n            return;\n        }\n        else if (len == 0)\n            return;\n        if (len == 1) {\n            if (pos != s.size()) {\n                for (int i = pos; i < s.size(); i++)\n                    cur += '1';\n                abbrs.push_back(cur);\n            }\n            return;\n        }\n        //next char can be at any index [pos s.size()]\n        // if next char at pos, len = len-1;\n        // else len = len-2 because we add both a number and a char\n        generate_abb(abbrs, s, cur+s[pos], pos+1, len-1);\n        for (int i = pos+1; i < s.size(); i++) {\n            cur += '1';\n            generate_abb(abbrs, s, cur+s[i],  i+1, len-2);\n        }\n    }\n    TrieNode* build(vector<string>& dic) {\n        TrieNode* root = new TrieNode();\n        for (string s:dic) {\n            TrieNode* p = root;\n            for (int i = 0; i < s.size(); i++) {\n                if (p->childs[s[i]-'a'] == nullptr)\n                    p->childs[s[i]-'a'] = new TrieNode();\n                p = p->childs[s[i]-'a'];\n            }\n        }\n        return root;\n    }\n    // if search continues to leaves, there is an conflict, return false;\n    bool valid(TrieNode* root, const string& s, int i) {\n        if (i == s.size()) return false;\n        if (s[i] == '1') {\n            for (int j = 0; j < 26; j++) {\n                // if any path results in conflict, return false\n                if (root->childs[j] && !valid(root->childs[j], s, i+1))\n                    return false;\n            }\n            return true;\n        }\n        else {\n            if (root->childs[s[i]-'a'] == nullptr) \n                return true;;\n            return valid(root->childs[s[i]-'a'], s, i+1);\n        }\n    }\n    string encode(const string& s) {\n        string ans;\n        int cnt = 0;\n        for (int i = 0; i < s.size(); i++) {\n            if (s[i] == '1')\n                cnt++;\n            else if (cnt == 0)\n                ans += s[i];\n            else {\n                ans += to_string(cnt)+s[i];\n                cnt = 0;\n            }\n        }\n        if (cnt) ans += to_string(cnt);\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/411-420/Pacific Atlantic Water Flow.cpp",
    "content": "class Solution {\n    vector<pair<int, int>> res;\n    vector<vector<int>> visited;\npublic:\n    void dfs(vector<vector<int>>& matrix, int x, int y, int pre, int preval){\n        if (x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size()  \n                || matrix[x][y] < pre || (visited[x][y] & preval) == preval) \n            return;\n        visited[x][y] |= preval;\n        if (visited[x][y] == 3) res.push_back({x, y});\n        dfs(matrix, x + 1, y, matrix[x][y], visited[x][y]);\n        dfs(matrix, x - 1, y, matrix[x][y], visited[x][y]);\n        dfs(matrix, x, y + 1, matrix[x][y], visited[x][y]);\n        dfs(matrix, x, y - 1, matrix[x][y], visited[x][y]);\n    }\n\n    vector<pair<int, int>> pacificAtlantic(vector<vector<int>>& matrix) {\n        if (matrix.empty()) return res;\n        int m = matrix.size(), n = matrix[0].size();\n        visited.resize(m, vector<int>(n, 0));\n        for (int i = 0; i < m; i++) {\n            dfs(matrix, i, 0, INT_MIN, 1);\n            dfs(matrix, i, n - 1, INT_MIN, 2);\n        }\n        for (int i = 0; i < n; i++) {\n            dfs(matrix, 0, i, INT_MIN, 1);\n            dfs(matrix, m - 1, i, INT_MIN, 2);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/411-420/Partition Equal Subset Sum.cpp",
    "content": "class Solution {\n    \npublic:\n    bool canPartition(vector<int>& nums) {\n        if (nums.size() <= 1) return false;\n        int sum = 0;\n        for (int num : nums) sum += num;\n        if (sum % 2 == 1) return false;\n        sum /= 2;\n        \n        vector<bool> dp(sum+1, false);\n        dp[0] = true;\n        sort(nums.begin(), nums.end());\n        \n        for (int num : nums)\n            for (int i = 0;i <= sum-num;i++)\n                if (dp[i] == true) dp[i + num] = true;\n                \n        return dp[sum];\n    }\n};\n"
  },
  {
    "path": "cpp/411-420/Sentence Screen Fitting.cpp",
    "content": "class Solution {\npublic:\n    int wordsTyping(vector<string>& sentence, int rows, int cols) {\n        unordered_map<int, int> umap;\n        int num = 0, n = sentence.size();\n        for (int i = 0; i < rows; i++){\n            int start = num % n;\n            if (umap.count(start) == 0){\n                int cnt = 0, len = 0;\n                for (int i = start; len < cols; i = (i+1) % n, cnt++) {\n                    if (len + sentence[i].size() > cols)\n                        break;\n                    len += sentence[i].size() + 1;\n                }\n                umap[start] = cnt;\n            }\n            num += umap[start];\n        }\n        return num / n;\n    }\n};\n"
  },
  {
    "path": "cpp/411-420/Third Maximum Number.cpp",
    "content": "class Solution {\npublic:\n    int thirdMax(vector<int>& nums) {\n        set<int> top3;\n        for (int num : nums) {\n            top3.insert(num);\n            if (top3.size() > 3)\n                top3.erase(top3.begin());\n        }\n        return top3.size() == 3 ? *top3.begin() : *top3.rbegin();\n    }\n};\n"
  },
  {
    "path": "cpp/421-430/Convert Binary Search Tree to Sorted Doubly Linked List.cpp",
    "content": "class Solution {\n\n  void inorder(Node* cur, Node*& prev, Node*& head) {\n        if (head == nullptr && cur->left == nullptr) {\n            head = cur;\n        }\n        Node* left = cur->left;\n        Node* right = cur->right;\n\n        if (left != nullptr) {\n            inorder(left, prev, head);\n        }\n\n        if (prev != nullptr) {\n            prev->right = cur;\n        }\n        cur->left = prev;\n\n        prev = cur;\n        if (right != nullptr) {\n            inorder(right, prev, head);\n        }\n    }\n\npublic:\n    \n    Node* treeToDoublyList(Node* root) {\n        if (root == nullptr) {\n            return nullptr;\n        }\n        Node* prev = nullptr;\n        Node* head = nullptr;\n        inorder(root, prev, head);\n        \n        prev->right = head;\n        head->left = prev;\n        \n        return head;\n    }\n};\n"
  },
  {
    "path": "cpp/421-430/Maximum XOR of Two Numbers in an Array.cpp",
    "content": "class Solution {\npublic:\n    class TreeNode {\n    public:\n        TreeNode* next[2];\n        TreeNode () {next[0] = NULL; next[1] = NULL;};\n    };\n    TreeNode* buildTree(vector<int>& nums) {\n        TreeNode* root = new TreeNode(), *cur;\n        int n = nums.size();\n        for (int i = 0; i < n; i++) {\n            int num = nums[i];\n            cur = root;\n            for (int j = 31; j >= 0; j--) {\n                int index = ((num >> j) & 1);\n                if (cur->next[index] ==  NULL)\n                    cur->next[index] = new TreeNode();\n                cur = cur->next[index];\n            }\n        }\n        return root;\n    }\n    \n    int helper(TreeNode* cur, int num) {\n        int res = 0;\n        for (int i = 31; i >= 0; i--) {\n            int index = ((num >> i) & 1) ? 0 : 1;\n            if (cur->next[index]) {\n                res <<= 1;\n                res |= 1;\n                cur = cur->next[index];\n            } else {\n                res <<= 1;\n                res |= 0;\n                cur = cur->next[index ? 0 : 1];\n            }\n        }\n        return res;\n    }\n    \n    int findMaximumXOR(vector<int>& nums) {\n        int res = 0;\n        TreeNode* root = buildTree(nums);\n        \n        for (int i : nums) {\n            res = max(res, helper(root, i));\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/421-430/Serialize and Deserialize N-ary Tree.cpp",
    "content": "/*\n// Definition for a Node.\nclass Node {\npublic:\n    int val;\n    vector<Node*> children;\n\n    Node() {}\n\n    Node(int _val) {\n        val = _val;\n    }\n\n    Node(int _val, vector<Node*> _children) {\n        val = _val;\n        children = _children;\n    }\n};\n*/\n\nclass Codec {\npublic:\n    // rule:  root, number of child, each child\n    \n    // Encodes a tree to a single string.\n    string serialize(Node* root) {\n        string data;\n        encode_dfs(root, data);\n        return data;\n    }\n\n    void encode_dfs(Node* root, string& data){\n        if (root == nullptr) return;\n        data += to_string(root->val) + \" \" + to_string(root->children.size()) + \" \";\n        for (Node* child : root->children) {\n            encode_dfs(child, data);\n        }\n    }\n    \n    // Decodes your encoded data to tree.\n    Node* deserialize(string data) {\n        stringstream ss(data);\n        return decode(ss);\n    }\n    \n    Node* decode(stringstream& ss) {\n        int val, child_size;\n        if (ss >> val >> child_size) {\n            Node* root = new Node(val);\n            for (int i = 0; i < child_size; i++) {\n                root->children.push_back(decode(ss));\n            }\n            return root;\n        }\n        return nullptr;\n    }\n};\n\n// Your Codec object will be instantiated and called as such:\n// Codec codec;\n// codec.deserialize(codec.serialize(root));\n"
  },
  {
    "path": "cpp/421-430/Valid Word Square.cpp",
    "content": "class Solution {\npublic:\n    bool validWordSquare(vector<string>& words) {\n        for(int i = 0; i < words.size(); ++i) {\n            for(int j = 0; j < words[i].size(); ++j)             {\n                if(j >= words.size() || words[j].size() <= i || words[j][i] != words[i][j])\n                   return false;\n            }\n        }\n        return true;\n   }\n};\n"
  },
  {
    "path": "cpp/421-430/Word Squares.cpp",
    "content": "class Solution {\npublic:\n    struct TrieNode {\n        vector<int> indexs;\n        vector<TrieNode*> children;\n        TrieNode(): children(26, nullptr) { }\n    };\n\n    TrieNode* buildTrie(const vector<string>& words) {\n        TrieNode* root = new TrieNode();\n        for (int j = 0; j < words.size(); j++) {\n            TrieNode* t = root;\n            for (int i = 0; i < words[j].size(); i++) {\n                if (!t->children[words[j][i] - 'a'])\n                    t->children[words[j][i] - 'a'] = new TrieNode();\n                t = t->children[words[j][i] - 'a'];\n                t->indexs.push_back(j);\n            }\n        }\n        return root;\n    }\n    \n    vector<vector<string>> res;\n    vector<string> vec;\n    void backtrack(const vector<string>& words, int level, TrieNode* root) {\n        if (level >= words[0].size()) {\n            res.emplace_back(vec);\n            return;\n        }\n        string str;\n        for (int i = 0; i < level; i++) \n            str += vec[i][level];\n        TrieNode* t = root;     \n        for (int i = 0; i < str.size(); i++) \n            if (!(t = t->children[str[i] - 'a'])) return;\n        for (int index : t->indexs) {\n            vec[level] = words[index];\n            backtrack(words, level + 1, root);\n        }\n    }\n    \n    vector<vector<string>> wordSquares(vector<string>& words) {\n        if (words.empty()) return res;\n        TrieNode* root = buildTrie(words);\n        vec.resize((int)words[0].size());\n        for (const string& word : words) {\n            vec[0] = word;\n            backtrack(words, 1, root);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/431-440/All O`one Data Structure.cpp",
    "content": "class AllOne {\npublic:\n\n    void inc(string key) {\n        \n        // If the key doesn't exist, insert it with value 0.\n        if (!bucketOfKey.count(key))\n            bucketOfKey[key] = buckets.insert(buckets.begin(), {0, {key}});\n            \n        // Insert the key in next bucket and update the lookup.\n        auto next = bucketOfKey[key], bucket = next++;\n        if (next == buckets.end() || next->value > bucket->value + 1)\n            next = buckets.insert(next, {bucket->value + 1, {}});\n        next->keys.insert(key);\n        bucketOfKey[key] = next;\n        \n        // Remove the key from its old bucket.\n        bucket->keys.erase(key);\n        if (bucket->keys.empty())\n            buckets.erase(bucket);\n    }\n\n    void dec(string key) {\n\n        // If the key doesn't exist, just leave.\n        if (!bucketOfKey.count(key))\n            return;\n\n        // Maybe insert the key in previous bucket and update the lookup.\n        list<Bucket>::iterator prev = bucketOfKey[key], bucket = buckets.begin();\n        if (prev != buckets.begin()) bucket = prev--;\n        bucketOfKey.erase(key);\n        if (bucket->value > 1) {\n            if (bucket == buckets.begin() || prev->value < bucket->value - 1)\n                prev = buckets.insert(bucket, {bucket->value - 1, {}});\n            prev->keys.insert(key);\n            bucketOfKey[key] = prev;\n        }\n        \n        // Remove the key from its old bucket.\n        bucket->keys.erase(key);\n        if (bucket->keys.empty())\n            buckets.erase(bucket);\n    }\n\n    string getMaxKey() {\n        return buckets.empty() ? \"\" : *(buckets.rbegin()->keys.begin());\n    }\n    \n    string getMinKey() {\n        return buckets.empty() ? \"\" : *(buckets.begin()->keys.begin());\n    }\n\nprivate:\n    struct Bucket { int value; unordered_set<string> keys; };\n    list<Bucket> buckets;\n    unordered_map<string, list<Bucket>::iterator> bucketOfKey;\n};\n"
  },
  {
    "path": "cpp/431-440/Find All Anagrams in a String.cpp",
    "content": "class Solution {\npublic:\n    vector<int> findAnagrams(string s, string p) {\n        unordered_map<char, int> mymap;\n        int psize = p.size();\n        vector<int> ans;\n        \n        for (char ch : p) mymap[ch]++;\n        int cnt = 0;\n        \n        for (int i = 0; i < s.size(); i++) {\n            char ch = s[i];\n            mymap[ch]--;\n            \n            if (mymap[ch] >= 0) cnt++;\n            \n            if (i >= psize) {\n                char poped_ch = s[i - psize];\n                int times = ++mymap[poped_ch];\n                if (times > 0) cnt--;\n            }\n            \n            if (cnt == psize) ans.push_back(i - psize + 1);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/431-440/Find Right Interval.cpp",
    "content": "/**\n * Definition for an interval.\n * struct Interval {\n *     int start;\n *     int end;\n *     Interval() : start(0), end(0) {}\n *     Interval(int s, int e) : start(s), end(e) {}\n * };\n */\nclass Solution {\npublic:\n    vector<int> findRightInterval(vector<Interval>& intervals) {\n        map<int, int> hash;\n        vector<int> res;\n        int n = intervals.size();\n        for (int i = 0; i < n; ++i)\n            hash[intervals[i].start] = i;\n        for (auto in : intervals) {\n            auto itr = hash.lower_bound(in.end);\n            if (itr == hash.end()) res.push_back(-1);\n            else res.push_back(itr->second);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/431-440/K-th Smallest in Lexicographical Order.cpp",
    "content": "class Solution {\n    \n    int dfs(string prefix, int n) {\n        string n_string = to_string(n);\n        string ptrfix_of_n = n_string.substr(0, prefix.length());\n        if (prefix.length() == n_string.length()) {\n            return prefix <= n_string ? 1 : 0;\n        }\n        if (prefix > ptrfix_of_n) {\n            int temp = 1;\n            for (int k = 0; k < (n_string.length() - prefix.length() - 1); k++) {\n                temp = temp * 10 + 1;\n            }\n            return temp;\n        }\n        if (prefix < ptrfix_of_n) {\n            int temp = 1;\n            for (int k = 0; k < (n_string.length() - prefix.length()); k++) {\n                temp = temp * 10 + 1;\n            }\n            return temp;\n        }\n        \n        int ans = 1;\n        for (int i = 0; i <= 9; i++) {\n            ans += dfs(prefix+to_string(i), n);\n        }\n        return ans;\n    }\n    \npublic:\n    int findKthNumber(int n, int k) {\n        string prefix = \"\";\n        \n        while (k > 0) {\n            for (int i = 0; i <= 9; i++) {\n                if (prefix.empty() && i == 0) continue;\n                \n                string new_prefix = prefix + to_string(i);\n                int tmp = dfs(new_prefix, n);\n                \n                if (tmp >= k) {\n                    prefix = new_prefix;\n                    k -= 1;\n                    break;\n                } else {\n                    k -= tmp;\n                }\n            }\n            \n        }\n        \n        return stoi(prefix);\n    }\n};\n"
  },
  {
    "path": "cpp/431-440/Minimum Genetic Mutation.cpp",
    "content": "class Solution {\npublic:\n    int minMutation(string start, string end, vector<string>& bank) {\n        queue<string> toVisit;\n        unordered_set<string> dict(bank.begin(), bank.end());\n        int dist = 0;\n        \n        if(!dict.count(end)) return -1;\n        \n        toVisit.push(start);\n        dict.insert(start); dict.insert(end);\n        while(!toVisit.empty()) {\n            int n = toVisit.size();\n            for(int i=0; i<n; i++) {\n                string str = toVisit.front();\n                toVisit.pop();\n                if(str==end) return dist;\n                addWord(str, dict, toVisit);\n            }\n            dist++;\n        }\n        return -1;\n    }\n    \n    void addWord(string word, unordered_set<string>& dict, queue<string>& toVisit) {\n        for(int i=0; i<word.size(); i++) {\n            char tmp = word[i];\n            for(char c:string(\"ACGT\")) {\n                word[i] = c;\n                if(dict.count(word)) {\n                    toVisit.push(word);\n                    dict.erase(word);\n                }\n            }\n            word[i] = tmp;\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/431-440/Number of Segments in a String.cpp",
    "content": "class Solution {\npublic:\n    int countSegments(string s) {\n        int segmentCount = 0;\n\n        for (int i = 0; i < s.length(); i++) {\n            if ((i == 0 || s[i-1] == ' ') && s[i] != ' ') {\n                segmentCount++;\n            }\n        }\n\n        return segmentCount;\n    }\n};\n"
  },
  {
    "path": "cpp/431-440/Path Sum III.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    int res;\n    \n    void dfs(TreeNode* root, map<int, int>& mymap, int currentSum, int target) {\n        if (!root) return;\n        currentSum += root->val;\n        res += mymap[currentSum - target];\n        mymap[currentSum]++;\n        dfs(root->left, mymap, currentSum, target);\n        dfs(root->right, mymap, currentSum, target);\n        mymap[currentSum]--;\n    }\n    \npublic:\n    int pathSum(TreeNode* root, int sum) {\n        res = 0;\n        map<int, int> mymap;\n        mymap[0] = 1;\n        dfs(root, mymap, 0, sum);\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/431-440/Ternary Expression Parser.cpp",
    "content": "class Solution {\npublic:\n    string parseTernary(string expression) {\n        stack<char> s;\n        for (int i = expression.size() - 1; i >= 0; --i) {\n            char c = expression[i];\n            if (!s.empty() && s.top() == '?') {\n                s.pop();\n                char first = s.top(); s.pop();\n                s.pop();\n                char second = s.top(); s.pop();\n                s.push(c == 'T' ? first : second);\n            } else {\n                s.push(c);\n            }\n        }\n        return string(1, s.top());\n    }\n};\n"
  },
  {
    "path": "cpp/441-450/Add Two Numbers II.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\n    \n    ListNode* addToFront(int val, ListNode* head){\n        ListNode* temp = new ListNode(val);\n        temp->next = head;\n        return temp;\n    }\n    \n    int length(ListNode* head) {\n        int len = 0;\n        while (head) {\n            len++;\n            head = head->next;\n        }\n        return len;\n    }\n    \npublic:\n    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {\n        int n1 = length(l1);\n        int n2 = length(l2);\n        int carry = 0;\n        ListNode *curr1 = l1, *curr2 = l2, *res = nullptr;\n        \n        while (n1 > 0 || n2 > 0){\n            int sum = 0;\n            if( n1 >= n2 ){ sum += curr1->val; curr1=curr1->next; n1--;}\n            if( n2 > n1 ){ sum += curr2->val; curr2=curr2->next; n2--;}\n            res = addToFront( sum, res );\n        }\n        \n        curr1 = res;\n        res = nullptr;\n        while( curr1 || carry) {\n            int tmp = curr1 ? curr1->val : 0;\n            tmp += carry;\n            carry = tmp/10;\n            res = addToFront(tmp%10, res);\n            if (!curr1) break;\n            curr2 = curr1; \n            curr1 = curr1->next;\n            delete curr2;\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/441-450/Arithmetic Slices II - Subsequence.cpp",
    "content": "class Solution {\npublic:\n    int numberOfArithmeticSlices(vector<int>& A) {\n        int n = A.size();\n        vector<map<int, int>> dp(n);\n        int ans = 0;\n        \n        for (int i = 0; i < n; i++) {\n            // dp[x][delta] += dp[y][delta] + 1（y∈[0, x - 1]）\n            for (int j = 0; j < i; j++) {\n                long delta = (long)A[i] - (long)A[j];\n                if (delta > INT_MAX || delta < INT_MIN) continue;\n                dp[i][delta]++;\n                if (dp[j].find(delta) != dp[j].end()) {\n                    dp[i][delta] += dp[j][delta];\n                    ans += dp[j][delta];\n                }\n            }\n            \n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/441-450/Arranging Coins.cpp",
    "content": "class Solution {\npublic:\n    int arrangeCoins(int n) {\n        long ans = 0;\n        long level = 1;\n        while (ans + level <= n) {\n            ans += level;\n            level++;\n        }\n        return level - 1;\n    }\n};\n"
  },
  {
    "path": "cpp/441-450/Delete Node in a BST.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\n\nclass Solution {\npublic:\n    TreeNode* deleteNode(TreeNode* root, int key) {\n        if (!root) return nullptr;\n        if (root->val == key) {\n            if (root->right == nullptr) {\n                TreeNode* left = root->left;\n                delete root;\n                return left;\n            } else {\n                TreeNode* right = root->right;\n                while (right->left)\n                    right = right->left;\n                swap(root->val, right->val);\n                root->right = deleteNode(root->right, key);\n                return root;\n            }\n        }\n        \n        if (key < root->val) {\n            root->left = deleteNode(root->left, key);\n        } else {\n            root->right = deleteNode(root->right, key);\n        }\n        \n        return root;\n    }\n};\n"
  },
  {
    "path": "cpp/441-450/Find All Duplicates in an Array.cpp",
    "content": "class Solution {\npublic:\n    vector<int> findDuplicates(vector<int>& nums) {\n        vector<int> res;\n        int i = 0;\n        while (i < nums.size()) {\n            if (nums[i] != nums[nums[i]-1]) swap(nums[i], nums[nums[i]-1]);\n            else i++;\n        }\n        for (i = 0; i < nums.size(); i++) {\n            if (nums[i] != i + 1) res.push_back(nums[i]);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/441-450/Number of Boomerangs.cpp",
    "content": "class Solution {\npublic:\n    int numberOfBoomerangs(vector<pair<int, int>>& points) {\n        int res = 0;\n    \n        // iterate over all the points\n        for (int i = 0; i < points.size(); ++i) {\n\n            unordered_map<long, int> group;\n\n            // iterate over all points other than points[i]\n            for (int j = 0; j < points.size(); ++j) {\n\n                if (j == i) continue;\n\n                int dy = points[i].second - points[j].second;\n                int dx = points[i].first - points[j].first;\n\n                // compute squared euclidean distance from points[i]\n                int key = dy * dy + dx * dx;\n\n                // accumulate # of such \"j\"s that are \"key\" distance from \"i\"\n                ++group[key];\n            }\n\n            for (auto& p : group) {\n                if (p.second > 1) {\n                    /*\n                     * for all the groups of points, \n                     * number of ways to select 2 from n = \n                     * nP2 = n!/(n - 2)! = n * (n - 1)\n                     */\n                    res += p.second * (p.second - 1);\n                }\n            }\n        }\n\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/441-450/Sequence Reconstruction.cpp",
    "content": "class Solution {\npublic:\n    bool sequenceReconstruction(vector<int>& org, vector<vector<int>>& seqs) {\n        map<int, set<int>> graph;\n        map<int, int> idxs;\n\n        for (int i = 0; i < org.size(); i++)\n            idxs[org[i]] = i;\n\n        for (int j = 0; j < seqs.size(); j++) {\n            vector<int> seq = seqs[j];\n            for (int i = 0; i < seq.size(); i++) {\n                if (idxs.count(seq[i]) == 0)\n                    return false;\n                if (i > 0 && idxs[seq[i - 1]] >= idxs[seq[i]])\n                    return false;\n                graph[seq[i-1]].insert(seq[i]);\n            }\n        }\n        \n        if (graph.empty()) return false;\n\n        for (int i = 0; i < org.size() - 1; i++)\n            if (graph[org[i]].count(org[i+1]) == 0)\n                return false;\n\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/441-450/Serialize and Deserialize BST.cpp",
    "content": "class Codec {\npublic:\n\n    // Encodes a tree to a single string.\n    string serialize(TreeNode* root) {\n        string order;\n        preorderDFS(root, order);\n        return order;\n    }\n    \n    void preorderDFS(TreeNode* root, string& order) {\n        if (!root) return;\n        char buf[4];\n        memcpy(buf, &(root->val), sizeof(int)); //burn the int into 4 chars\n        for (int i = 0; i < 4; i++) order.push_back(buf[i]);\n        preorderDFS(root->left, order);\n        preorderDFS(root->right, order);\n    }\n\n    // Decodes your encoded data to tree.\n    TreeNode* deserialize(string data) {\n        int pos = 0;\n        return reconstruct(data, pos, INT_MIN, INT_MAX);\n    }\n    \n    inline TreeNode* reconstruct(const string& buffer, int& pos, int minValue, int maxValue) {\n        if (pos >= buffer.size()) return nullptr;\n        \n        int value;\n        memcpy(&value, &buffer[pos], sizeof(int));\n        if (value < minValue || value > maxValue) return nullptr;\n        \n        TreeNode* node = new TreeNode(value);\n        pos += sizeof(int);\n        node->left = reconstruct(buffer, pos, minValue, value);\n        node->right = reconstruct(buffer, pos, value, maxValue);\n        return node;\n    }\n};\n"
  },
  {
    "path": "cpp/441-450/String Compression.cpp",
    "content": "class Solution {\npublic:\n    int compress(vector<char>& chars) {\n        int cnt = 1;\n        char cur = chars[0];\n        int writePos = 0;\n        for (int i = 0; i < chars.size(); i++) {\n            bool shouldWrite = i == chars.size() - 1 || cur != chars[i+1];\n\n            if (shouldWrite) {\n                chars[writePos++] = cur;\n                if (cnt > 1) {\n                    string tmp = to_string(cnt);\n                    for (char t : tmp) {\n                        chars[writePos++] = t;\n                    }\n                }\n                cur = chars[i+1];\n                cnt = 1;\n            } else {\n                cnt++;\n            }\n        }\n        return writePos;\n    }\n};\n"
  },
  {
    "path": "cpp/451-460/132 Pattern.cpp",
    "content": "class Solution {\npublic:\n    bool find132pattern(vector<int>& nums) {\n        int third = INT_MIN;\n        stack<int> mystack;\n        \n        for (int i = nums.size()-1; i >= 0; i--) {\n            \n            if (nums[i] < third) return true;\n            \n            while (!mystack.empty() && nums[i] > mystack.top()) {\n                third = mystack.top();\n                mystack.pop();\n            }\n            \n            mystack.push(nums[i]);\n        }\n        \n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/451-460/4Sum II.cpp",
    "content": "class Solution {\npublic:\n    void fillMap(const vector<int>& A, const vector<int>& B, unordered_map<int,int> &m) {\n        int n = A.size();\n        for(int i = 0; i < n; ++i)\n            for(int j = 0; j < n; ++j)\n                m[A[i] + B[j]]++;\n    }\n    \n    int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {\n        unordered_map<int,int> m1, m2;\n        fillMap(A, B, m1);\n        fillMap(C, D, m2);\n        int res = 0;\n        for(auto it = m1.begin(); it != m1.end(); ++it) {\n           auto it2 = m2.find(-it->first);\n           if(it2 != m2.end())\n             res += it->second*it2->second;\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/451-460/Assign Cookies.cpp",
    "content": "class Solution {\npublic:\n    int findContentChildren(vector<int>& g, vector<int>& s) {\n        sort(g.begin(),g.end());\n        sort(s.begin(),s.end());\n        int i = g.size()-1, j = s.size()-1, res = 0;\n        while(i>=0 && j>=0) {\n            if (g[i] > s[j]) i--;\n            else if (g[i--] <= s[j--]) res++;\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/451-460/LFU Cache.cpp",
    "content": "class LFUCache {\n    \n    int capacity;\n    int size;\n    int minFreq;\n    \n    unordered_map<int, pair<int, int>> m; //key to {value,freq};\n    unordered_map<int, list<int>::iterator> mIter; //key to list iterator;\n    unordered_map<int, list<int>>  fm;  //freq to key list;\n    \npublic:\n    LFUCache(int capacity) {\n        this->capacity = capacity;\n        size = 0;\n    }\n    \n    int get(int key) {\n        if (m.count(key) == 0) return -1;\n        \n        fm[m[key].second].erase(mIter[key]);\n        m[key].second++;\n        fm[m[key].second].push_back(key);\n        mIter[key] = --fm[m[key].second].end();\n        \n        if (fm[minFreq].empty())\n            minFreq++;\n        \n        return m[key].first;\n    }\n    \n   void put(int key, int value) {\n        if (capacity <= 0) return;\n        int oldValue = get(key);\n        \n        // only update the value\n        if(oldValue != -1) {\n            m[key].first=value;\n            return;\n        }\n        \n        // evict the least frequent item\n        if (size >= capacity ) {\n            int badKey = fm[minFreq].front();\n            m.erase(badKey);\n            mIter.erase(badKey);\n            fm[minFreq].pop_front();\n            size--;\n        }\n        \n        m[key] = {value, 1};\n        fm[1].push_back(key);\n        mIter[key] = --fm[1].end();\n        minFreq = 1;\n        size++;\n    }\n};\n"
  },
  {
    "path": "cpp/451-460/Minimum Moves to Equal Array Elements.cpp",
    "content": "class Solution {\npublic:\n    int minMoves(vector<int>& nums) {\n        return accumulate(begin(nums), end(nums), 0) - nums.size() * *min_element(begin(nums), end(nums));\n    }\n};\n"
  },
  {
    "path": "cpp/451-460/Minimum Number of Arrows to Burst Balloons.cpp",
    "content": "class Solution {\npublic:\n    int findMinArrowShots(vector<pair<int, int>>& points) {\n        int count = 0, arrow = INT_MIN;\n        auto cmp = [&] (const pair<int, int>& a, const pair<int, int>& b) {\n            return a.second == b.second ? a.first < b.first : a.second < b.second;\n        };\n        sort(points.begin(), points.end(), cmp);\n        for (int i = 0; i < points.size(); i++)  {\n            if (arrow != INT_MIN && points[i].first <= arrow) { continue; } //former arrow shot points[i] \n            arrow = points[i].second; // new arrow shot the end of points[i]\n            count++;\n        }\n        return count;\n    }\n};\n"
  },
  {
    "path": "cpp/451-460/Repeated Substring Pattern.cpp",
    "content": "class Solution {\npublic:\n    bool repeatedSubstringPattern(string str) {\n        int len = str.length();\n        for (int i = 1; i <= len/2; i++) {\n            if (len % i != 0) continue;\n            string part = str.substr(0, i);\n            int dups = len / i;\n            bool ff = true;\n            for (int k = 0; k < dups; k++) {\n                int idx = k * i;\n                bool f = true;\n                for (int j = 0; j < i; j++) {\n                    if (str[idx + j] != str[j]) {\n                        f = false;\n                        break;\n                    }\n                }\n                if (f == false) { ff = false; break; }\n            }\n            if (ff == false) continue;\n            return true;\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/451-460/Sort Characters By Frequency.cpp",
    "content": "class Solution {\npublic:\n    string frequencySort(string s) {\n        map<char,int> freq;\n        vector<string> bucket(s.size()+1, \"\");\n        string res;\n        \n        //count frequency of each character\n        for (char c : s) freq[c]++;\n        //put character into frequency bucket\n        for (const auto& it : freq) {\n            int n = it.second;\n            char c = it.first;\n            bucket[n].append(n, c);\n        }\n        //form descending sorted string\n        for (int i = s.size(); i>0; i--) {\n            if (!bucket[i].empty())\n                res.append(bucket[i]);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/461-470/Can I Win.cpp",
    "content": "class Solution {\n    \n    int buildkey (bool *nums, int N) {\n        int key = 0;\n        for (int i = 1; i <= N;i++) if (nums[i] == true) key |= (1 << i);\n        return key;\n    }\n    \n    bool caniwin (bool *nums, int N, int desiredTotal, map<int, bool> &cache) {\n        \n        int key = buildkey(nums, N);\n        \n        if (cache.count(key) > 0) return cache[key];\n        \n        for (int i = 1; i <= N; i++) {\n            \n            if (nums[i] == false) {\n                \n                if (i >= desiredTotal) return true;\n                \n                nums[i] = true;\n                bool win = !caniwin(nums, N, desiredTotal - i, cache);\n                nums[i] = false;\n                \n                if (win) return cache[key] = true;\n            }\n        }\n        \n        return cache[key] = false;\n    }\n    \npublic:\n    bool canIWin(int maxChoosableInteger, int desiredTotal) {\n        \n        if (desiredTotal == 0) return true;\n        \n        if ( (1 + maxChoosableInteger) * maxChoosableInteger / 2  < desiredTotal) return false;\n        \n        bool nums[maxChoosableInteger+1] = {false};\n        \n        map<int, bool>cache;\n        \n        return caniwin(nums, maxChoosableInteger, desiredTotal, cache);\n        \n    }\n};\n"
  },
  {
    "path": "cpp/461-470/Convex Polygon.cpp",
    "content": "class Solution {\npublic:\n    bool isConvex(vector<vector<int>>& points) {\n        if (points.size() < 3) return false;\n        int last = 0;\n        for (int i = 0; i < points.size(); i++) {\n            auto pre = i == 0 ? points.back() : points[i - 1];\n            auto after = i == points.size() - 1 ? points[0] : points[i + 1];\n            int x1 = points[i][0] - pre[0], y1 = points[i][1] - pre[1];\n            int x2 = after[0] - points[i][0], y2 = after[1] - points[i][1];\n            long flag = x1 * y2 - x2 * y1;\n            if (last * flag < 0) return false;\n            if (flag != 0) {\n                last = flag;\n            }\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/461-470/Count The Repetitions.cpp",
    "content": "/*\n                    0  1   2 3 0      1    2 3 0      1    2 3 0  \nS1 --------------> abacb | abacb | abacb | abacb | abacb | abacb \nrepeatCount ----->    0  |   1   |   1   |   2   |   2   |   3\nIncrement of \nrepeatCount     ->    0  |   1   |   0   |   1   |   0   |   1\nnextIndex ------->    2  |   1   |   2   |   1   |   2   |   1\n\n\n\"nlhqgllunmelayl\"\n10000\n\"lnl\"\n10\n\n1       2\n10000     20000\n\n0   1     2\n\n1   3     5\n\n1   1     1\n\n\n\"niconiconi\"\n99981\n\"nico\"\n81\n\n0   1   2   3\n\n2   4 \n\n2   2\n\n\n\n\"nlhqgllunmelayl\"\n2\n\"lnl\"\n1\n\n0     1\n\n1     3\n\n1\n\n\n*/\n\nclass Solution {\npublic:\n    int getMaxRepetitions(string s1, int n1, string s2, int n2) {\n        map<int, int> mymap1, mymap2; // mymap1 : index -> count, mymap2 : nextindex -> s1_pattern_count\n        \n        int index = 0;\n        int repeatCount = 0;\n        \n        for (int i = 1; i <= n1; i++) {\n            \n            for (int j = 0; j < s1.size(); j++) {\n                \n                if (s1[j] == s2[index]) {\n                    index++;\n                    if (index == s2.size()) {\n                        repeatCount++;\n                        index = 0;\n                    }\n                }\n            }\n            \n            mymap1[i] = repeatCount;\n            \n            if (mymap2.count(index) > 0) {\n                int start = mymap2[index];\n                int cycle = i - start;\n                int diff = repeatCount - mymap1[start];\n                int pattern_repeat = diff * ( (n1 - start) / cycle);\n                int remain = mymap1[start + (n1 - start) % cycle];\n                return (pattern_repeat + remain) / n2;\n            }\n            mymap2[index] = i;\n        }\n        \n        return mymap1[n1-1]/n2;\n    }\n};\n\n// mymap2[index]\n"
  },
  {
    "path": "cpp/461-470/Hamming Distance.cpp",
    "content": "class Solution {\npublic:\n    int hammingDistance(int x, int y) {\n        return __builtin_popcount(x^y);\n    }\n};\n"
  },
  {
    "path": "cpp/461-470/Island Perimeter.cpp",
    "content": "class Solution {\npublic:\n    int islandPerimeter(vector<vector<int>>& grid) {\n        int count=0, repeat=0;\n        for (int i = 0; i < grid.size(); i++) {\n            for (int j = 0; j < grid[i].size(); j++) {\n                    if (grid[i][j] == 1) {\n                        count ++;\n                        if (i != 0 && grid[i-1][j] == 1) repeat++;\n                        if (j != 0 && grid[i][j-1] == 1) repeat++;\n                    }\n                }\n        }\n        return 4*count-repeat*2;\n    }\n};\n"
  },
  {
    "path": "cpp/461-470/Minimum Moves to Equal Array Elements II.cpp",
    "content": "class Solution {\npublic:\n    int minMoves2(vector<int>& nums) {\n        std::nth_element(nums.begin(), nums.begin() + nums.size()/2, nums.end());\n        int median = nums[nums.size()/2];\n        int res = 0;\n        for (int v : nums) res += abs(median - v);\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/461-470/Optimal Account Balancing.cpp",
    "content": "class Solution {\n    \n    int helper(vector<int>& a, int start, int n) {\n        int ans = INT_MAX;\n        while(start < n && a[start] == 0) start++;\n        for (int i = start + 1; i < n; ++i) {\n            if ( (a[i] * a[start] < 0) ) {\n                a[i] += a[start];\n                ans = min(ans, 1 + helper(a, start + 1, n));\n                a[i] -= a[start];\n            }\n        }\n        return ans == INT_MAX ? 0 : ans;\n    }\n    \npublic:\n    int minTransfers(vector<vector<int>>& transactions) {\n        map<int, int> net;\n        for (const auto& t : transactions) {\n            net[t[0]] -= t[2];\n            net[t[1]] += t[2];\n        }\n        vector<int> a;\n        for (const auto& ele : net) {\n            if (ele.second != 0) {\n                a.push_back(ele.second);\n            }\n        }\n        \n        return helper(a, 0, a.size());\n    }\n};\n"
  },
  {
    "path": "cpp/461-470/Unique Substrings in Wraparound String.cpp",
    "content": "class Solution {\npublic:\n    int findSubstringInWraproundString(string p) {\n        vector<int> cnt(26, 0);\n        int len = 0;\n        for (int i = 0; i < p.size(); ++i) {\n            if (i > 0 && (p[i] - p[i-1] + 26) % 26 == 1) {\n                ++len;\n            } else {\n                len = 1;\n            }\n            cnt[p[i] - 'a'] = max(cnt[p[i] - 'a'], len);\n        }\n        return accumulate(cnt.begin(), cnt.end(), 0);\n    }\n};\n"
  },
  {
    "path": "cpp/461-470/Validate IP Address.cpp",
    "content": "class Solution {\n    \n    void split(const std::string &s, char delim, std::vector<std::string> &elems) {\n        std::stringstream ss;\n        ss.str(s);\n        std::string item;\n        while (std::getline(ss, item, delim)) {\n            elems.push_back(item);\n        }\n    }\n\n    std::vector<std::string> split(const std::string &s, char delim) {\n        std::vector<std::string> elems;\n        split(s, delim, elems);\n        return elems;\n    }\n    \n    static bool validateV4num(const string& num) {\n        if (num.empty() || num.length() > 3) return false;\n        for (char c : num)\n            if (!isdigit(c))\n                return false;\n        int v = stoi(num);\n        if (v >= 0 && v <= 255 && to_string(v).length() == num.length()) return true;\n        return false;\n    }\n    \n    static bool validateV6num(const string& num) {\n        if (num.empty() || num.length() > 4) return false;\n        for (char c : num) {\n            if (isdigit(c)) continue;\n            if (c >= 'a' && c <= 'f') continue;\n            if (c >= 'A' && c <= 'F') continue;\n            return false;\n        }\n        return true;\n    }\n    \n    string checkV4(const string& IP) {\n        vector<string> nums = split(IP, '.');\n        if (nums.size() != 4) return \"Neither\";\n        if ( std::all_of(nums.begin(), nums.end(), validateV4num) ) return \"IPv4\";\n        return \"Neither\";\n    }\n    \n    string checkV6(const string& IP) {\n        vector<string> nums = split(IP, ':');\n        if (nums.size() != 8) return \"Neither\";\n        if ( std::all_of(nums.begin(), nums.end(), validateV6num) ) return \"IPv6\";\n        return \"Neither\";\n    }\n    \npublic:\n    string validIPAddress(string IP) {\n        if (!isalnum(IP.back())) return \"Neither\";\n        if (IP.find('.') != std::string::npos) return checkV4(IP);\n        else if (IP.find(':') != std::string::npos) return checkV6(IP);\n        else return \"Neither\";\n    }\n};\n"
  },
  {
    "path": "cpp/471-480/Concatenated Words.cpp",
    "content": "class Solution {\npublic:\n    vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {\n        vector<string> result;\n        if(words.empty()) return result; \n        auto mycomp = [&](const string& str1, const string& str2){return str1.size() < str2.size();};\n        sort(words.begin(), words.end(), mycomp);\n        unordered_set<string> mp;\n        for(string& word: words) {\n            if(wordBreak(word, mp)) result.push_back(word); // We don't need to insert this word, because it can be concatenated from other words.\n            else mp.insert(word); \n        }\n        return result;\n    }\n    \nprivate:\n    bool wordBreak(const string& s, const unordered_set<string>& wordDict) {\n        if(s.empty() || wordDict.empty()) return false;\n        vector<bool> dp(s.size()+1, false);\n        dp[0] = true;\n        for(int i = 1; i <= s.size(); i++) {\n            for(int k = i-1; k >= 0; k--) {\n                if(dp[k] && wordDict.find(s.substr(k, i-k)) != wordDict.end()) {\n                    dp[i] = true;\n                    break;\n                }\n            }\n        }\n        return dp.back();\n    }\n};\n"
  },
  {
    "path": "cpp/471-480/Encode String with Shortest Length.cpp",
    "content": "class Solution {\n    int numRepetition(const string &s, const string &t) {\n        int cnt = 0,i = 0;\n        while (i < s.length()) {\n            if (s.substr(i, t.length()) != t) break;\n            cnt++;\n            i += t.length();\n        }\n        return cnt;\n    }\n    \n    string dfs(const string& s, unordered_map<string, string> &m) {\n        if (s.length() < 5) return s;\n        if (m.count(s) > 0) return m[s];\n        string res(s);\n        for (int i = 0; i < s.length(); i++) {\n            string s1 = s.substr(0, i+1);\n            int cnt = numRepetition(s, s1);\n            string t;\n            for (int k = 1; k <= cnt; k++) {\n                if (k == 1) t = s1 + dfs(s.substr(i+1), m);\n                else t = to_string(k) + \"[\" + dfs(s1, m) + \"]\" + dfs(s.substr(k*s1.length()), m);\n                if (t.length() < res.length()) res=t;            \n            }\n        }\n        return m[s] = res;\n    }\n    \npublic:\n    string encode(string s) {\n        unordered_map<string,string> m;\n        return dfs(s,m);\n    }\n};\n"
  },
  {
    "path": "cpp/471-480/Heaters.cpp",
    "content": "class Solution {\npublic:\n    int findRadius(vector<int>& houses, vector<int>& heaters) {\n        \n        sort(heaters.begin(), heaters.end());\n        \n        int res = -1;\n        \n        for (int i = 0; i < houses.size(); i++) {\n            \n            auto it = lower_bound(heaters.begin(), heaters.end(), houses[i]);\n            \n            int tmp = INT_MAX;\n            \n            if (it != heaters.end()) tmp = *it - houses[i];\n            \n            if (it != heaters.begin()) tmp = min(tmp, houses[i] - *(it-1));\n            \n            res = max(res, tmp);\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/471-480/Largest Palindrome Product.cpp",
    "content": "class Solution {\npublic:\n    int largestPalindrome(int n) {\n        if (n == 1) return 9;\n        int upper = pow(10, n) - 1;\n        int lower = pow(10, n-1);\n        for (int i = upper; i >= lower; i--) {\n            long cand = buildPalindrome(i);\n            for (long j = upper; j*j >= cand; j--) {\n                if (cand % j == 0 && cand / j <= upper) {\n                    return cand % 1337;\n                }\n            }\n        }\n        return -1;\n    }\n    \n    long buildPalindrome(int n) {\n        string s = to_string(n);\n        reverse(s.begin(), s.end());\n        return stol(to_string(n) + s);\n    }\n};\n"
  },
  {
    "path": "cpp/471-480/Matchsticks to Square.cpp",
    "content": "class Solution {\n    \n    map<int, bool> cache;\n    \n    int genKey(const vector<int>& nums) {\n        int key = 0;\n        for (int v : nums) {\n            key *= 2;\n            if (v > 0) key += 1;\n        }\n        return key;\n    }\n    \n    bool dfs(vector<int>& nums, int sidelength, int remain, int sideidx, int currentlength) {\n        int key = genKey(nums);\n        if (cache.count(key) > 0) return cache[key];\n        if (sideidx >= 4) return cache[key] = true;\n        if (currentlength > sidelength) return cache[key]=false;\n        if (remain <= 0) return cache[key]=false;\n        \n        for (int i = 0; i < nums.size(); i++) {\n            if (nums[i] <= 0) continue;\n            int temp = currentlength + nums[i];\n            if (temp > sidelength) continue;\n            int v = nums[i];\n            nums[i] = -1;\n            if (temp == sidelength) {\n                bool fff = dfs(nums, sidelength, remain-1, sideidx+1, 0);\n                if (fff) return true;\n            } \n            else if (temp < sidelength) {\n                bool fff = dfs(nums, sidelength, remain-1, sideidx, temp);\n                if (fff) return true;\n            }\n            nums[i] = v;\n        }\n        \n        return cache[key]=false;\n    }\n    \npublic:\n    bool makesquare(vector<int>& nums) {\n        int sum = accumulate(nums.begin(), nums.end(), 0);\n        if (sum % 4 != 0) return false;\n        int sidelength = sum/4;\n        return dfs(nums, sidelength, nums.size(), 0, 0);\n    }\n};\n"
  },
  {
    "path": "cpp/471-480/Number Complement.cpp",
    "content": "class Solution {\npublic:\n    int findComplement(int num) {\n        int mask = 0xffffffff;\n        while (num & mask) mask <<= 1;\n        return ~mask & ~num;\n    }\n};\n"
  },
  {
    "path": "cpp/471-480/Ones and Zeroes.cpp",
    "content": "class Solution {\n    \n    pair<int, int> count(const string& str) {\n        int x = 0, y = 0;\n        for (char ch : str) {\n            if (ch == '0') x++;\n            else y++;\n        }\n        return {x, y};\n    }\n    \npublic:\n    int findMaxForm(vector<string>& strs, int m, int n) {\n        \n        vector<vector<int>> dp(m+1, vector<int>(n+1, 0));\n        \n        for (const auto& str : strs) {\n            auto pairs = count(str);\n            for (int i = m; i >= pairs.first; i--) \n                for (int j = n; j >= pairs.second; j--) \n                    dp[i][j] = max(1 + dp[i-pairs.first][j-pairs.second], dp[i][j]);\n        }\n        \n        return dp[m][n];\n    }\n};\n"
  },
  {
    "path": "cpp/471-480/Sliding Window Median.cpp",
    "content": "class Solution {\npublic:\n    vector<double> medianSlidingWindow(vector<int>& nums, int k) {\n        multiset<int> window(nums.begin(), nums.begin() + k);\n        auto mid = next(window.begin(), k / 2);\n        vector<double> medians;\n        for (int i=k; ; i++) {\n    \n            // Push the current median.\n            medians.push_back((double(*mid) + *next(mid, k%2 - 1)) / 2);\n    \n            // If all done, return.\n            if (i == nums.size())\n                return medians;\n                \n            // Insert nums[i].\n            window.insert(nums[i]);\n            if (nums[i] < *mid)\n                mid--;\n    \n            // Erase nums[i-k].\n            if (nums[i-k] <= *mid)\n                mid++;\n            window.erase(window.lower_bound(nums[i-k]));\n        }\n    }\n\n};\n\nI prefer this solution.\nhttps://leetcode.com/problems/sliding-window-median/discuss/96347/O(n*log(n))-Time-C%2B%2B-Solution-Using-Two-Heaps-and-a-Hash-Table\n"
  },
  {
    "path": "cpp/471-480/Total Hamming Distance.cpp",
    "content": "class Solution {\npublic:\n    int totalHammingDistance(vector<int>& nums) {\n        vector<vector<int>> stats(2, vector<int>(32, 0));\n        int totalhammingdistance = 0;\n        for (int v : nums) {\n            for (int i = 0; i < 32; i++, v/=2) {\n                int key = v & 0x1;\n                totalhammingdistance += stats[1-key][i];\n                stats[key][i] ++;\n            }\n        }\n        return totalhammingdistance;\n    }\n};\n"
  },
  {
    "path": "cpp/481-490/Find Permutation.cpp",
    "content": "class Solution {\npublic:\n    vector<int> findPermutation(string s) {\n        vector<int> result;\n        for (int i = 0; i <= s.size(); i++) {\n            if (s[i] == 'I' || i == s.size()) {\n                int curL = result.size();\n                for (int j = i+1; j > curL; j--) {\n                    result.push_back(j);\n                }\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/481-490/License Key Formatting.cpp",
    "content": "class Solution {\npublic:\n    string licenseKeyFormatting(string S, int K) {\n        string ans;\n        int cnt = 0;\n        \n        for(int i = S.size() - 1; i >= 0; i--) {\n            if(S[i] != '-') {\n                if(cnt == 0 && !ans.empty()) ans.push_back('-');\n                ans.push_back(toupper(S[i]));\n                cnt = (cnt + 1) % K;\n            }\n        }\n        \n        reverse(ans.begin(), ans.end());\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/481-490/Magical String.cpp",
    "content": "class Solution {\npublic:\n    int magicalString(int n) {\n        if (n <= 3)\n            return n > 0;\n        queue<int> q;\n        int res = 1;\n        bool one = true;\n        q.push(2);\n        n -= 3; //122, start from second 2\n        while (n) {\n            int cnt = q.front();\n            q.pop();\n            while (n && cnt--) {\n                q.push(one ? 1 : 2);\n                n--;\n                res += one;\n            }\n            one = !one;\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/481-490/Max Consecutive Ones II.cpp",
    "content": "class Solution {\npublic:\n    int findMaxConsecutiveOnes(vector<int>& nums) {\n        int i = 0, j = 0, zeros = 0, res = 0;\n        for (; j < nums.size(); j++) {\n            if (nums[j] == 0) zeros++;\n            if (zeros > 1) {\n                while (nums[i] == 1) i++;\n                i++;\n                zeros--;\n            }\n            res = max(res, j-i+1);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/481-490/Max Consecutive Ones.cpp",
    "content": "class Solution {\npublic:\n    int findMaxConsecutiveOnes(vector<int>& nums) {\n        bool flag = false;\n        int res = 0, tmp = 0;\n        for (int v : nums) {\n            if (v == 1) {\n                tmp++;\n                flag = true;\n            } else {\n                res = max(res, tmp);\n                flag = false;\n                tmp = 0;\n            }\n        }\n        res = max(res, tmp);\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/481-490/Predict the Winner.cpp",
    "content": "class Solution {\n    \npublic:\n    bool PredictTheWinner(vector<int>& nums) {\n        int sum = accumulate(begin(nums), end(nums), 0);\n        int n = nums.size();\n        vector<vector<int>> dp(n, vector<int>(n));\n        for (int i = 0; i < n; i++) dp[i][i] = nums[i];\n        for (int i = 0; i < n-1; i++) dp[i][i+1] = max(nums[i], nums[i+1]);\n        for (int k = 2; k < n; k++) {\n            for (int i = 0; i+k < n; i++) {\n                int v1 = nums[i] + dp[i+2][i+k];\n                int v2 = nums[i] + dp[i+1][i+k-1];\n                int v3 = nums[i+k] + dp[i][i+k-2];\n                int v4 = nums[i+k] + dp[i+1][i+k-1];\n                dp[i][i+k] = max(min(v1,v2), min(v3,v4));\n            }\n        }\n        return dp[0][n-1] >= sum - dp[0][n-1];\n    }\n};\n"
  },
  {
    "path": "cpp/481-490/Robot Room Cleaner.cpp",
    "content": "/**\n * // This is the robot's control interface.\n * // You should not implement it, or speculate about its implementation\n * class Robot {\n *   public:\n *     // Returns true if the cell in front is open and robot moves into the cell.\n *     // Returns false if the cell in front is blocked and robot stays in the current cell.\n *     bool move();\n *\n *     // Robot will stay in the same cell after calling turnLeft/turnRight.\n *     // Each turn will be 90 degrees.\n *     void turnLeft();\n *     void turnRight();\n *\n *     // Clean the current cell.\n *     void clean();\n * };\n */\n\nclass Solution {\n    \n    void dfs(Robot &robot, set<pair<int, int>>& visited, int i, int j, int dir) {\n        robot.clean();\n        visited.insert({i, j});\n        pair<int, int> directions[4] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};\n        for (int k = 0; k < 4; k++) {\n            int new_i = i + directions[dir].first;\n            int new_j = j + directions[dir].second;\n            if (visited.count({new_i, new_j}) == 0 && robot.move()) {\n                dfs(robot, visited, new_i, new_j, dir);\n                robot.turnRight();\n                robot.turnRight();\n                robot.move();\n                robot.turnRight();\n                robot.turnRight();\n            }\n            dir = (dir + 1) % 4;\n            robot.turnRight();\n        }\n    }\n    \npublic:\n    void cleanRoom(Robot& robot) {\n        set<pair<int, int>> visited;\n        dfs(robot, visited, /*i=*/0, /*j=*/0, /*dir=*/0);\n    }\n};\n"
  },
  {
    "path": "cpp/481-490/Smallest Good Base.cpp",
    "content": "class Solution {\npublic:\n    string smallestGoodBase(string n) {\n        long long num = stol(n);\n        for (int i = log(num + 1) / log(2); i >= 2; --i) {\n            long long left = 2, right = pow(num, 1.0 / (i - 1)) + 1;\n            while (left < right) {\n                long long mid = left + (right - left) / 2, sum = 0;\n                for (int j = 0; j < i; ++j) {\n                    sum = sum * mid + 1;\n                }\n                if (sum == num) return to_string(mid);\n                else if (sum < num) left = mid + 1;\n                else right = mid;\n            }\n        }\n        return to_string(num - 1);\n    }\n};\n"
  },
  {
    "path": "cpp/481-490/The Maze.cpp",
    "content": "class Solution {\n    \n    int isStone(vector<vector<int>>& maze, int i, int j) {\n        int N1 = maze.size();\n        int N2 = maze[0].size();\n        if (i < 0 || j < 0 || i >= N1 || j >= N2) return 1;\n        return maze[i][j];\n    }\n    \npublic:\n    bool hasPath(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {\n        \n        queue<pair<int,int>> myqueue;\n        set<pair<int,int>> visited;\n        myqueue.push({start[0], start[1]});\n        visited.insert({start[0], start[1]});\n        pair<int, int> directions[4] = {{0,1},{0,-1},{1,0},{-1,0}};\n        \n        while (!myqueue.empty()) {\n            pair<int, int> pos = myqueue.front();\n            myqueue.pop();\n            if (pos.first == destination[0] && pos.second == destination[1])\n                return true;\n\n            for (int i = 0;i < 4;i++) {\n                int nx = pos.first;\n                int ny = pos.second;\n                while (!isStone(maze, nx, ny)) {\n                    nx += directions[i].first;\n                    ny += directions[i].second;\n                }\n                nx -= directions[i].first;\n                ny -= directions[i].second;\n                pair<int, int> n_pos{nx, ny};\n                if (visited.count(n_pos) == 0) {\n                    myqueue.push(n_pos);\n                    visited.insert(n_pos);\n                }\n            }\n            \n        }\n        \n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/481-490/Zuma Game.cpp",
    "content": "class Solution {\n    \n    int dfs(string board, string hand, unordered_map<string, int>& cache) {\n        if (board.empty()) return 0;\n        if (hand.empty()) return 999;\n        string key = board + \":\" + hand;\n        if (cache.count(key) > 0) return cache[key];\n        int step = 10;\n                \n        for (int i = 0;i <= board.size();i++) {\n            \n            int res = 0;\n            int idx = hand.find(board[i]);\n            if (idx < 0) continue;\n            \n            if (i+1 < board.size() && board[i] == board[i+1]) {\n                string nhand = hand.substr(0, idx) + hand.substr(idx+1);\n                string after_board = board.substr(0,i) + board.substr(i+2);\n                simplify(after_board);\n                if (after_board.empty()) return 1;\n                res = 1 + dfs(after_board, nhand, cache);\n            } else if (idx + 1 < hand.size() && hand[idx] == hand[idx+1]) {\n                string nhand = hand.substr(0, idx) + hand.substr(idx+2);\n                string after_board = board.substr(0,i) + board.substr(i+1);\n                simplify(after_board);\n                if (after_board.empty()) return 2;\n                res = 2 + dfs(after_board, nhand, cache);\n            } else {\n                continue;\n            }\n            \n            step = min(step, res);\n            while (i+1 < board.size() && board[i] == board[i+1]) i++;\n        }\n\n        \n        return cache[key] = step;\n    }\n    \npublic:\n    int findMinStep(string board, string hand) {\n        \n        sort(hand.begin(), hand.end());\n        \n        unordered_map<string, int> cache;\n        \n        int step = dfs(board, hand, cache);\n        \n        return step > 5 ? -1 : step;\n    }\n    \n    void simplify(string& str) {\n        while(str.size() > 0) {\n            int start = 0;\n            bool done = true;\n            for (int i = 0; i <= str.size(); i++) {\n                if (i == str.size() || str[i] != str[start]) {\n                    if (i - start >= 3) {\n                        str = str.substr(0, start) + str.substr(i);\n                        done = false;\n                        break;\n                    }\n                    start = i;\n                }\n            }\n            if (done) break;\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/491-500/Construct the Rectangle.cpp",
    "content": "class Solution {\npublic:\n    vector<int> constructRectangle(int area) {\n        vector<int> output(2);\n\t\n\t    output[0] = 1;\n\t    output[1] = area;\n\t    int length = 0;\n\t\n        for (int width = 1; width <= (int)sqrt(area); width++) {\n        \n            length = area/width;\n        \n            if ((length * width) == area && abs(length - width) <= abs(output[0] - output[1])) {\n        \t    output[0] = length;\n        \t    output[1] = width;\n            }\n        }\n        \n        return output;\n    }\n};\n"
  },
  {
    "path": "cpp/491-500/Diagonal Traverse.cpp",
    "content": "class Solution {\npublic:\n    vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {\n        if (matrix.empty() || matrix.front().empty()) return vector<int>();\n        int m = matrix.size();\n        int n = matrix.front().size();\n        int total = m * n;\n        vector<int> ans(total);\n        bool up = true;\n        int i = 0, j = 0;\n        \n        for (int k = 0; k < total; k++) {\n            ans[k] = matrix[i][j];\n            \n            if (up && (i == 0 || j == n - 1)) {\n                if (j == n - 1) i++;\n                else j++;\n                up = !up;\n            }\n            else if (!up && (j == 0 || i == m - 1)) {\n                if (i == m - 1) j++;\n                else i++;\n                up = !up;\n            } else {\n                if (up) { i--; j++; }\n                else { i++; j--; }\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/491-500/Increasing Subsequences.cpp",
    "content": "class Solution {\nprivate:\n    void findSubsequences(const vector<int> &nums, vector<int> &subsequence, set<vector<int> > &result, int index) {\n        if (subsequence.size() >= 2)\n            result.insert(subsequence);\n        \n        for (int i = index; i < nums.size(); ++i) {\n            if (subsequence.size() == 0 || nums[i] >= subsequence.back()) {\n                subsequence.push_back(nums[i]);\n                findSubsequences(nums, subsequence, result, i + 1);\n                subsequence.pop_back();\n            }\n        }\n}\n\npublic:\n    vector<vector<int>> findSubsequences(vector<int>& nums) {\n        set<vector<int>> resultSet;\n        vector<int> subsequence;\n        findSubsequences(nums, subsequence, resultSet, 0);\n\n        return vector<vector<int>>(begin(resultSet), end(resultSet));\n    }\n};\n"
  },
  {
    "path": "cpp/491-500/Keyboard Row.cpp",
    "content": "class Solution {\npublic:\n    vector<string> findWords(vector<string>& words) {\n        string a[3] = {\n            \"QWERTYUIOPqwertyuiop\",\n            \"ASDFGHJKLasdfghjkl\",\n            \"ZXCVBNMzxcvbnm\",\n        };\n        vector<string> ans;\n        for (int index = 0; index < 3; ++ index) {\n            for (auto& word: words) {\n                int cnt = 0;\n                for (auto ch: word) {\n                    if (a[index].find(ch) != string::npos) {\n                        cnt ++;\n                    }\n                }\n                if (cnt == word.size()) {\n                    ans.push_back(word);\n                }\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/491-500/Next Greater Element I.cpp",
    "content": "class Solution {\npublic:\n    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {\n        map<int, int> mymap;\n        stack<int> mystack;\n        \n        for (int i = nums.size()-1; i >= 0; i--) {\n            \n            while (!mystack.empty() && mystack.top() < nums[i]) {\n                mystack.pop();\n            }\n            \n            mymap[nums[i]] = mystack.empty() ? -1 : mystack.top();\n            \n            mystack.push(nums[i]);\n            \n        }\n        \n        vector<int> result;\n        for (int v : findNums) {\n            result.push_back(mymap[v]);\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/491-500/Reverse Pairs.cpp",
    "content": "class Solution {\n    \nprivate:\n    int count;\n   \n    void merge(vector<int>& nums, int start, int mid, int end){\n        int l = start, r = mid + 1;\n        while(l <= mid && r <= end){\n            if((long)nums[l] > (long) 2 * nums[r]){\n                count += (mid - l + 1);\n                r++;\n            } else{\n                l++;\n            }\n        }\n        sort(nums.begin() + start, nums.begin() + end + 1);\n    }\n    \n    void mergeSort(vector<int>& nums, int start, int end){\n        if(start == end) return;\n        \n        int mid = (start + end)/2;\n        mergeSort(nums, start, mid);\n        mergeSort(nums, mid+1, end);\n        merge(nums, start, mid, end);\n    }\n    \npublic:\n    int reversePairs(vector<int>& nums) {\n        if (nums.empty()) return 0;\n        count = 0;\n        mergeSort(nums, 0, nums.size()-1);\n        return count;\n    }\n};\n"
  },
  {
    "path": "cpp/491-500/Target Sum.cpp",
    "content": "class Solution {\n    \n    int dfs(const vector<int>& nums, int i, int S, map<pair<int, int>, int>& cache) {\n        pair<int, int> key = {i, S};\n        if (cache.count(key) > 0) return cache[key];\n        \n        if (i == nums.size())\n            return S == 0 ? 1 : 0;\n            \n        int curNum = nums[i];\n        int v1 = dfs(nums, i + 1, S - curNum, cache);\n        int v2 = dfs(nums, i + 1, S + curNum, cache);\n        return cache[key] = v1+v2;\n    }\n    \npublic:\n    int findTargetSumWays(vector<int>& nums, int S) {\n        map<pair<int, int>, int> cache;\n        return dfs(nums, 0, S, cache);\n    }\n};\n"
  },
  {
    "path": "cpp/491-500/Teemo Attacking.cpp",
    "content": "class Solution {\npublic:\n    int findPoisonedDuration(vector<int>& timeSeries, int duration) {\n        if (timeSeries.empty()) return 0;\n        int begin = timeSeries[0], result = 0;\n        for (int v : timeSeries) {\n            result += begin + duration >= v ? v - begin : duration;\n            begin = v;\n        }\n        return result + duration;\n    }\n};\n"
  },
  {
    "path": "cpp/491-500/The Maze III.cpp",
    "content": "class Solution {\n    \n    int isStone(vector<vector<int>>& maze, int i, int j) {\n        int N1 = maze.size();\n        int N2 = maze[0].size();\n        if (i < 0 || j < 0 || i >= N1 || j >= N2) return 1;\n        return maze[i][j];\n    }\n    \n    \npublic:\n    string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) {\n        queue<pair<int,int>> myqueue;\n        map<pair<int,int>, pair<int,string>> distance;\n        myqueue.push({ball[0], ball[1]});\n        distance[{ball[0], ball[1]}] = {0, \"\"};\n        pair<int, int> directions[4] = {{1,0},{0,-1},{0,1},{-1,0}};\n        string dis = \"dlru\";\n        \n        string res = \"impossible\";\n        int minimum_distance = INT_MAX;\n        \n        while (!myqueue.empty()) {\n            pair<int, int> pos = myqueue.front();\n            myqueue.pop();\n\n            for (int i = 0;i < 4;i++) {\n                int nx = pos.first;\n                int ny = pos.second;\n                int step = 0;\n                while (!isStone(maze, nx, ny)) {\n                    if (nx == hole[0] && ny == hole[1]) {\n                        if (minimum_distance > distance[pos].first + step) {\n                            minimum_distance = distance[pos].first + step;\n                            res = distance[pos].second + dis[i];\n                        } else if (minimum_distance == distance[pos].first + step) {\n                            res = min(res, distance[pos].second + dis[i]);\n                        }\n                    }\n                    nx += directions[i].first;\n                    ny += directions[i].second;\n                    step++;\n                }\n                nx -= directions[i].first;\n                ny -= directions[i].second;\n                step--;\n                pair<int, int> n_pos{nx, ny};\n                if (distance.count(n_pos) == 0 || distance[pos].first + step < distance[n_pos].first) {\n                    myqueue.push(n_pos);\n                    distance[n_pos].first = distance[pos].first + step;\n                    distance[n_pos].second = distance[pos].second + dis[i];\n                } else if (distance[pos].first + step == distance[n_pos].first) {\n                    if (distance[pos].second + dis[i] < distance[n_pos].second) {\n                        distance[n_pos].second = distance[pos].second + dis[i];\n                        myqueue.push(n_pos);\n                    }\n                }\n            }\n            \n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/501-510/Base 7.cpp",
    "content": "class Solution {\npublic:\n    string convertToBase7(int num) {\n        bool negative = false;\n        if (num < 0) {\n            negative = true;\n            num = -num;\n        }\n        \n        int result = 0;\n        \n        int base = 1;\n        \n        while (num > 0) {\n            int temp = num % 7;\n            num = (num - temp)/7;\n            result += base * temp;\n            base *= 10;\n        }\n        \n        string resultStr = to_string(result);\n        if (negative) resultStr = \"-\" + resultStr;\n        \n        return resultStr;\n    }\n};\n"
  },
  {
    "path": "cpp/501-510/Find Mode in Binary Search Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    void dfs(TreeNode* root, int& maximum_count, map<int, int>& mymap) {\n        if (!root) return;\n        int v = root->val;\n        mymap[v]++;\n        maximum_count = max(maximum_count, mymap[v]);\n        dfs(root->left, maximum_count, mymap);\n        dfs(root->right, maximum_count, mymap);\n    }\n    \npublic:\n    vector<int> findMode(TreeNode* root) {\n        map<int, int> mymap;\n        vector<int> result;\n        int maximum_count(0);\n        dfs(root, maximum_count, mymap);\n        for (auto it : mymap)\n            if (it.second == maximum_count)\n                result.push_back(it.first);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/501-510/IPO.cpp",
    "content": "class Compare1 {\npublic:\n    bool operator() (const pair<int,int>& p1, const pair<int,int>& p2) {\n        return p1.second - p2.second >= 0;\n    }\n};\n\nclass Compare2 {\npublic:\n    bool operator() (const pair<int,int>& p1, const pair<int,int>& p2) {\n        return p2.first - p1.first >= 0;\n    }\n};\n\nclass Solution {\npublic:\n    int findMaximizedCapital(int k, int W, vector<int>& Profits, vector<int>& Capital) {\n        priority_queue<pair<int, int>, vector<pair<int,int>>, Compare1> stocks;\n        priority_queue<pair<int, int>, vector<pair<int,int>>, Compare2> avaliable;\n        \n        for (int i = 0; i < Profits.size(); i++) {\n            stocks.push({Profits[i], Capital[i]});\n        }\n        \n        for (int i = 0; i < k; i++) {\n            \n            while (!stocks.empty() && stocks.top().second <= W) {\n                avaliable.push(stocks.top());\n                stocks.pop();\n            }\n            \n            if (!avaliable.empty()) {\n                W += avaliable.top().first;\n                avaliable.pop();\n            }\n        }\n        \n        return W;\n    }\n};\n"
  },
  {
    "path": "cpp/501-510/Most Frequent Subtree Sum.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<int> findFrequentTreeSum(TreeNode* root) {\n        unordered_map<int,int> counts;\n        int maxCount = 0;\n        countSubtreeSums(root, counts, maxCount);\n        \n        vector<int> maxSums;\n        for(const auto& x :  counts){\n            if(x.second == maxCount) maxSums.push_back(x.first);\n        }\n        return maxSums;\n    }\n    \n    int countSubtreeSums(TreeNode *r, unordered_map<int,int> &counts, int& maxCount){\n        if(r == nullptr) return 0;\n        \n        int sum = r->val;\n        sum += countSubtreeSums(r->left, counts, maxCount);\n        sum += countSubtreeSums(r->right, counts, maxCount);\n        ++counts[sum];\n        maxCount = max(maxCount, counts[sum]);\n        return sum;\n    }\n};\n"
  },
  {
    "path": "cpp/501-510/Next Greater Element II.cpp",
    "content": "class Solution {\npublic:\n    vector<int> nextGreaterElements(vector<int>& nums) {\n        stack<int> mystack;\n        int n = nums.size();\n        nums.resize(2*nums.size());\n        copy(nums.begin(), nums.begin()+n, nums.begin()+n);\n        vector<int> result(n, 0);\n        \n        for (int i = nums.size()-1; i >= 0; i--) {\n            \n            while (!mystack.empty() && mystack.top() <= nums[i]) {\n                mystack.pop();\n            }\n            \n            if (i < n) {\n                result[i] = mystack.empty() ? -1 : mystack.top();\n            }\n            \n            mystack.push(nums[i]);\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/501-510/Perfect Number.cpp",
    "content": "class Solution {\npublic:\n    bool checkPerfectNumber(int num) {\n        if (num <= 1) {\n            return false;\n        }\n        int sum = 1;\n        for (int i = 2; i * i <= num; i++) {\n            if (num % i == 0) {\n                sum += i;\n                if (i * i != num) {\n                    sum += num / i;\n                }\n\n            }\n        }\n        return sum == num;\n    }\n};\n"
  },
  {
    "path": "cpp/501-510/Relative Ranks.cpp",
    "content": "class Solution {\npublic:\n    vector<string> findRelativeRanks(vector<int>& nums) {\n        priority_queue<pair<int,int> > pq;\n        for(int i=0;i<nums.size();i++)\n        {\n            pq.push(make_pair(nums[i],i));\n        }\n        vector<string> res(nums.size(),\"\");\n        int count = 1;\n        for(int i=0; i<nums.size();i++)\n        {\n            if(count==1) {res[pq.top().second] = \"Gold Medal\"; count++;}\n            else if(count==2) {res[pq.top().second] = \"Silver Medal\"; count++;}\n            else if(count==3) {res[pq.top().second] = \"Bronze Medal\"; count++;}\n            else {res[pq.top().second] = to_string(count); count++;}\n            pq.pop();\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/501-510/The Maze II.cpp",
    "content": "class Solution {\n    \n    int isStone(vector<vector<int>>& maze, int i, int j) {\n        int N1 = maze.size();\n        int N2 = maze[0].size();\n        if (i < 0 || j < 0 || i >= N1 || j >= N2) return 1;\n        return maze[i][j];\n    }\n    \npublic:\n    int shortestDistance(vector<vector<int>>& maze, vector<int>& start, vector<int>& destination) {\n        \n        queue<pair<int,int>> myqueue;\n        map<pair<int,int>, int> distance;\n        myqueue.push({start[0], start[1]});\n        distance[{start[0], start[1]}] = 0;\n        pair<int, int> directions[4] = {{0,1},{0,-1},{1,0},{-1,0}};\n        \n        while (!myqueue.empty()) {\n            pair<int, int> pos = myqueue.front();\n            myqueue.pop();\n\n            for (int i = 0;i < 4;i++) {\n                int nx = pos.first;\n                int ny = pos.second;\n                int step = 0;\n                while (!isStone(maze, nx, ny)) {\n                    nx += directions[i].first;\n                    ny += directions[i].second;\n                    step++;\n                }\n                nx -= directions[i].first;\n                ny -= directions[i].second;\n                step--;\n                pair<int, int> n_pos{nx, ny};\n                if (distance.count(n_pos) == 0 || distance[pos] + step < distance[n_pos]) {\n                    myqueue.push(n_pos);\n                    distance[n_pos] = distance[pos] + step;\n                }\n            }\n            \n        }\n        \n        return distance[{destination[0], destination[1]}] == 0 ? -1 : distance[{destination[0], destination[1]}];\n        \n    }\n};\n"
  },
  {
    "path": "cpp/511-520/Coin Change 2.cpp",
    "content": "class Solution {\npublic:\n    int change(int amount, vector<int>& coins) {\n        if (amount == 0) return 1;\n        if (coins.empty()) return 0;\n        \n        vector<int> dp(amount + 1 , 0);\n        dp[0] = 1;\n        for (int val : coins) {\n            for (int i = val; i <= amount; i++) {\n                dp[i] += (dp[i - val]);\n            }\n        }\n        \n        return dp[amount];\n    }\n};\n"
  },
  {
    "path": "cpp/511-520/Detect Capital.cpp",
    "content": "class Solution {\npublic:\n    bool detectCapitalUse(string word) {\n        bool isUpper = isupper(word[0]);\n        \n        if (isUpper) {\n            isUpper = isupper(word[1]);\n            for (int i = 2; i < word.length(); i++) {\n                if (islower(word[i])) {\n                    if (isUpper) return false;\n                } else {\n                    if (!isUpper) return false;\n                }\n            }\n        } else {\n            for (int i = 1; i < word.length(); i++) {\n                if (!islower(word[i])) {\n                    return false;\n                }\n            }\n        }\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/511-520/Find Bottom Left Tree Value.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int findBottomLeftValue(TreeNode* root) {\n        queue<TreeNode*> q;\n        q.push(root);\n        q.push(nullptr);\n        int ans = root->val;\n        while (!q.empty()) {\n            TreeNode* t = q.front();\n            q.pop();\n            if (t == nullptr) {\n                if (!q.empty()) { ans = q.front()->val; q.push(nullptr); }\n            } else {\n                if (t->left) q.push(t->left);\n                if (t->right) q.push(t->right);\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/511-520/Find Largest Value in Each Tree Row.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<int> largestValues(TreeNode* root) {\n        queue<TreeNode*> q;\n        q.push(root);\n        q.push(nullptr);\n        vector<int> ans;\n        if (!root) return ans;\n        int current = INT_MIN;\n        while (!q.empty()) {\n            TreeNode* t = q.front();\n            q.pop();\n            if (t == nullptr) {\n                ans.push_back(current);\n                current = INT_MIN;\n                if (!q.empty()) {\n                    q.push(nullptr);\n                }\n            } else {\n                current = max(current, t->val);\n                if (t->left) q.push(t->left);\n                if (t->right) q.push(t->right);\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/511-520/Freedom Trail.cpp",
    "content": "class Solution {\n    \n    int dfs(const string& ring, const string& key, int index, map<string, int>& mymap){\n        if (index == key.length()) {\n            return 0;\n        }\n        string hashKey = ring + to_string(index);\n        if (mymap.find(hashKey) != mymap.end()) return mymap[hashKey];\n        \n        int minSteps = INT_MAX;\n        for (int i = 0; i < ring.length(); i ++) {\n            if (ring[i] == key[index]){\n                string s = ring.substr(i, ring.length()) + ring.substr(0, i);\n                int steps = 1 + min(i, (int)ring.length() - i);\n                steps += dfs(s, key, index + 1, mymap);\n                minSteps = min(minSteps, steps);\n            }\n        }\n        \n        return mymap[hashKey] = minSteps;\n    }\n    \npublic:\n    int findRotateSteps(string ring, string key) {\n        map<string, int> mymap;\n        return dfs(ring, key, 0, mymap);\n    }\n};\n"
  },
  {
    "path": "cpp/511-520/Longest Palindromic Subsequence.cpp",
    "content": "class Solution {\npublic:\n    int longestPalindromeSubseq(string s) {\n        int n = s.length();\n        vector<vector<int>> dp(n, vector<int>(n, 0));\n        \n        for (int step = 0; step < n; step++) {\n            for (int i = 0; i + step < n; i++) {\n                int j = i + step;\n                if (i == j) dp[i][j] = 1;\n                else if (i+1 == j) dp[i][j] = ( s[i] == s[j] ? 2 : 1);\n                else {\n                    if (s[i] == s[j]) {\n                        dp[i][j] = 2 + dp[i+1][j-1];\n                    } else {\n                        dp[i][j] = max(dp[i+1][j], dp[i][j-1]);\n                    }\n                }\n            }\n        }\n        \n        return dp[0][n-1];\n    }\n};\n"
  },
  {
    "path": "cpp/511-520/Super Washing Machines.cpp",
    "content": "class Solution {\npublic:\n    int findMinMoves(vector<int>& machines) {\n        int n = machines.size();\n        int sum = accumulate(machines.begin(), machines.end(), 0);\n        \n        if (sum % n != 0) return -1;\n        int avg = sum / n;\n        int ans = 0;\n        int peak = 0;\n        \n        for (int machine : machines) {\n            peak = peak + machine - avg;\n            ans = max(ans, abs(peak));\n            ans = max(ans, machine - avg);\n                      \n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/521-530/Beautiful Arrangement.cpp",
    "content": "class Solution {\npublic:\n    int countArrangement(int N) {\n        vector<int> vs;\n        for (int i=0; i<N; ++i) vs.push_back(i+1);\n        return counts(N, vs);\n    }\n    int counts(int n, vector<int>& vs) {\n        if (n <= 0) return 1;\n        int ans = 0;\n        for (int i=0; i<n; ++i) {\n            if (vs[i]%n==0 || n%vs[i]==0) {\n                swap(vs[i], vs[n-1]);\n                ans += counts(n-1, vs);\n                swap(vs[i], vs[n-1]);\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/521-530/Contiguous Array.cpp",
    "content": "class Solution {\n    \n    int get(int v) {\n        return v == 1 ? 1 : -1;\n    }\n    \npublic:\n    int findMaxLength(vector<int>& nums) {\n        if (nums.empty()) return 0;\n        int n = nums.size();\n        vector<int> dp(n, 0);\n        map<int, int> mymap;\n        mymap[0] = -1;\n        int result = 0;\n        for (int i = 0; i < nums.size(); i++) {\n            if (i == 0) dp[0] = get(nums[i]);\n            else dp[i] = dp[i - 1] + get(nums[i]);\n            auto itt = mymap.find(dp[i]);\n            if (itt != mymap.end()) {\n                result = max(result, i - itt->second);\n            } else {\n                mymap[dp[i]] = i;\n            }\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/521-530/Continuous Subarray Sum.cpp",
    "content": "class Solution {\npublic:\n    bool checkSubarraySum(vector<int>& nums, int k) {\n        if (nums.size() < 2) return false;\n        long K = abs(long(k));\n        map<int, int> record;\n        record[0] = -1;\n        \n        for (int i = 1; i < nums.size(); i++) {\n            if (nums[i-1] + nums[i] == 0) {\n                return true;\n            }\n        }\n        \n        int sum = 0;\n        for (int i = 0; i < nums.size(); i++) {\n            int e = nums[i];\n            sum += e;\n            if (sum == 0 && e != 0) return true;\n            if (k == 0) continue;\n            // Make it a positive number to avoid bad mod.\n            if (sum < 0) sum += (-1*sum / K) * K + K;\n            int target = sum % K;\n            // You can also remove following line.\n            sum = target;\n            if (record.count(target) > 0) {\n                if (i - record[target] > 1) return true;\n            } else {\n                record[target] = i;\n            }\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/521-530/Longest Uncommon Subsequence I.cpp",
    "content": "class Solution {\npublic:\n    int findLUSlength(string a, string b) {\n        if (a.length() > b.length()) return a.length();\n        if (b.length() > a.length()) return b.length();\n        if (a == b) return -1;\n        return a.length();\n    }\n};\n"
  },
  {
    "path": "cpp/521-530/Longest Uncommon Subsequence II.cpp",
    "content": "class Solution {\n    \n    bool isS1subsOfS2(const string &s1, const string &s2){\n        if (s1.length() >= s2.length()) return false;\n        int j = 0, i = 0;\n        for(; i < s1.size(); ++i){\n            while(j < s2.size() && s1[i] != s2[j]) ++j;\n            if(j == s2.size())\n               return false;\n            ++j;\n        }\n        return true;\n    }\n    \npublic:\n    int findLUSlength(vector<string>& strs) {\n        unordered_map<string, int> m;\n        for(const string& str : strs) ++m[str];\n        vector<pair<string, int>> v;\n        for(const auto &e : m) v.push_back(e);\n        \n        auto cmp = [](const pair<string,int> &a, const pair<string,int> &b) {\n            return a.first.size() > b.first.size();\n        };\n        sort(v.begin(), v.end(), cmp);\n        \n        for (int i = 0; i < v.size(); ++i) {\n           if(v[i].second == 1) {\n               int j = 0;\n               for(; j < i; ++j)\n                 if(isS1subsOfS2(v[i].first, v[j].first))\n                     break;\n               if(j == i) return v[i].first.size();\n           }\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/521-530/Longest Word in Dictionary through Deleting.cpp",
    "content": "class Solution {\npublic:\n    string findLongestWord(string s, vector<string>& d) {\n        string ans;\n        for (int i = 0; i < d.size(); i++) {\n            int pi = 0, pj = 0;\n            for (; pi < s.size() && pj < d[i].size(); pi++) {\n                pj += s[pi] == d[i][pj];\n            }\n            if (pj == d[i].size() && (ans.size() < d[i].size() || (ans.size() == d[i].size() && ans > d[i])))\n                ans = d[i];\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/521-530/Minimum Distance Between BST Nodes.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    void dfs(TreeNode* root, int &pv, int& result) {\n        if (!root) return;\n        dfs(root->left, pv, result);\n        if (pv != INT_MIN) result = min(result, abs(pv - root->val));\n        pv = root->val;\n        dfs(root->right, pv, result);\n    }\n    \npublic:\n    int getMinimumDifference(TreeNode* root) {\n        int pv = INT_MIN;\n        int result = INT_MAX;\n        dfs(root, pv, result);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/521-530/Word Abbreviation.cpp",
    "content": "class Solution {\npublic:\n    vector<string> wordsAbbreviation(vector<string>& dict) {\n        int n = dict.size();\n        vector<string> abbres;\n        vector<int> lens(n, 1);\n        for (const string& word : dict) {\n            abbres.push_back(abbreviate(word, 1));\n        }\n        \n        for (int i = 0; i < n; i++) {\n            bool unique = false;\n            while (!unique) {\n                string abbre = abbres[i];\n                unique = true;\n                for(int j = i + 1; j < n; j++) {\n                    if(abbre == abbres[j]) {\n                        abbres[j] = abbreviate(dict[j], lens[j]+1);\n                        lens[j]++;\n                        unique = false;\n                    }\n                }\n                if(unique == false) {\n                    abbres[i] = abbreviate(dict[i], lens[i]+1);\n                    lens[i]++;\n                }\n            }\n        }\n        return abbres;\n    }\n    \n    string abbreviate(const string& s, int len) {\n        int num = s.length() - len - 1;\n        if (num <= 1) return s;\n        return s.substr(0, len) + to_string(num) + s.back();\n    }\n};\n"
  },
  {
    "path": "cpp/531-540/Complex Number Multiplication.cpp",
    "content": "class Solution {\npublic:\n    string complexNumberMultiply(string a, string b) {\n        int ra, ia, rb, ib;\n        char buff;\n        stringstream aa(a), bb(b), ans;\n        aa >> ra >> buff >> ia >> buff;\n        bb >> rb >> buff >> ib >> buff;\n        ans << ra*rb - ia*ib << \"+\" << ra*ib + rb*ia << \"i\";\n        return ans.str();\n    }\n};\n"
  },
  {
    "path": "cpp/531-540/Convert BST to Greater Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    void dfs(TreeNode* root, int& sum) {\n        if (!root) return;\n        dfs(root->right, sum);\n        sum += root->val;\n        root->val = sum;\n        dfs(root->left, sum);\n    }\n    \npublic:\n    TreeNode* convertBST(TreeNode* root) {\n        int sum = 0;\n        dfs(root, sum);\n        return root;\n    }\n};\n"
  },
  {
    "path": "cpp/531-540/Encode and Decode TinyURL.cpp",
    "content": "class Solution {\n    \n    int count = 0;\n    unordered_map<int, string> mymap;\n    \npublic:\n\n    // Encodes a URL to a shortened URL.\n    string encode(string longUrl) {\n        string short_url = \"http://tinyurl.com/\" + to_string(count);\n        mymap[count] = longUrl;\n        count++;\n        return short_url;\n    }\n\n    // Decodes a shortened URL to its original URL.\n    string decode(string shortUrl) {\n        string num = shortUrl.substr(19);\n        return mymap[stoi(num)];\n    }\n};\n\n// Your Solution object will be instantiated and called as such:\n// Solution solution;\n// solution.decode(solution.encode(url));\n"
  },
  {
    "path": "cpp/531-540/Lonely Pixel I.cpp",
    "content": "class Solution {\npublic:\n    int findLonelyPixel(vector<vector<char>>& picture) {\n        int ans = 0;\n        map<int, int> col, row;\n        for (int i = 0; i < picture.size(); i++) {\n            for (int j = 0; j < picture[0].size(); j++) {\n                if (picture[i][j] == 'B') {\n                    row[i]++;\n                    col[j]++;\n                }\n            }\n        }\n        \n        for (int i = 0; i < picture.size(); i++) {\n            for (int j = 0; j < picture[0].size(); j++) {\n                if (picture[i][j] == 'B' && row[i] == 1 && col[j] == 1) {\n                    ans++;\n                }\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/531-540/Lonely Pixel II.cpp",
    "content": "class Solution {\npublic:\n    int findBlackPixel(vector<vector<char>>& picture, int N) {\n        map<int, int> row, col;\n        map<int, string> rowSig;\n        for (int i = 0; i < picture.size(); i++) {\n            string signature;\n            for (int j = 0; j < picture[0].size(); j++) {\n                signature = signature + picture[i][j];\n                if (picture[i][j] == 'B') {\n                    row[i]++;\n                    col[j]++;\n                }\n            }\n            rowSig[i] = signature;\n        }\n        \n        int ans = 0;\n        set<int> processed;\n        for (int i = 0; i < picture.size(); i++) {\n            for (int j = 0; j < picture[0].size(); j++) {\n                if (picture[i][j] == 'B') {\n                    if (row[i] != col[j]) continue;\n                    if (row[i] != N) continue;\n                    if (processed.count(j) > 0) continue;\n                    string signature = rowSig[i];\n                    \n                    bool flag = true;\n                    for (int k = 0; k < picture.size(); k++) {\n                        if (picture[k][j] == 'B' && signature != rowSig[k]) {\n                            flag = false;\n                        }\n                    }\n                    if (flag) ans += N;\n                    processed.insert(j);\n                }   \n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/531-540/Single Element in a Sorted Array.cpp",
    "content": "class Solution {\npublic:\n    int singleNonDuplicate(vector<int>& nums) {\n        int n = nums.size(), left = 0, right = n - 1;\n        while (left < right) {\n            int mid = left + (right - left) / 2;\n            if (mid % 2 == 0) {\n                if (nums[mid] == nums[mid-1]) right = mid - 2;\n                else if (nums[mid] == nums[mid+1]) left = mid + 2;\n                else return nums[mid];\n            } else {\n                if (nums[mid] == nums[mid-1]) left = mid + 1;\n                else if (nums[mid] == nums[mid+1]) right = mid - 1;\n            }\n        }\n        return nums[left];\n    }\n};\n"
  },
  {
    "path": "cpp/541-550/01 Matrix.cpp",
    "content": "class Solution {\n    \n    struct point {\n        int i;\n        int j;\n        int d;\n        point (int _i, int _j, int _d): i(_i), j(_j), d(_d) { }\n    };\n    \npublic:\n    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {\n        int row = matrix.size();\n        int column = matrix[0].size();\n        vector<vector<int>> result(row, vector<int>(column, -1));\n        queue<point> myqueue;\n        vector<pair<int, int>> pos{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n        \n        for (int i = 0; i < row; i++) {\n            for (int j = 0; j < column; j++) {\n                if (matrix[i][j] == 0) {\n                    result[i][j] = 0;\n                    myqueue.emplace(point(i, j, 0));\n                }\n            }\n        }\n        \n        while (!myqueue.empty()) {\n            point current = myqueue.front();\n            myqueue.pop();\n            for (const auto& e : pos) {\n                int nexti = current.i + e.first;\n                int nextj = current.j + e.second;\n                if (nexti < 0 || nexti >= row || nextj < 0 || nextj >= column) continue;\n                if (result[nexti][nextj] < 0) {\n                    if (result[nexti][nextj] < 0) {\n                        result[nexti][nextj] = current.d + 1;\n                        myqueue.push(point(nexti, nextj, current.d + 1));\n                    }\n                }\n            }\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/541-550/Binary Tree Longest Consecutive Sequence II.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int longestConsecutive(TreeNode* root) {\n        int longest = 0;\n        dfs(root, root, longest);\n        return longest;\n    }\n\n    pair<int, int> dfs(TreeNode * node, TreeNode * parent, int & longest) {\n        if (node == nullptr) {\n            return make_pair(0, 0);\n        }\n        auto left = dfs(node->left, node, longest);\n        auto right = dfs(node->right, node, longest);\n        longest = max(longest, left.first + right.second + 1);\n        longest = max(longest, left.second + right.first + 1);\n        int inc = 0, dec = 0;\n        if ( node->val == parent->val + 1 ) {\n            inc = max(left.first, right.first) + 1;\n        }\n        if ( node->val == parent->val - 1 ) {\n            dec = max(left.second, right.second) + 1;\n        }\n        return make_pair(inc, dec);\n    }\n};\n"
  },
  {
    "path": "cpp/541-550/Boundary of Binary Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    void leftBoundary(TreeNode* root, vector<int>& nodes) {\n        if(root == nullptr || (root->left == nullptr && root->right == nullptr)) return;\n        nodes.push_back(root->val);\n        if(root->left == nullptr) leftBoundary(root->right, nodes);\n        else leftBoundary(root->left, nodes);\n    }\n    \n    void rightBoundary(TreeNode* root, vector<int>& nodes) {\n        if(root == nullptr || (root->left == nullptr && root->right == nullptr)) return;\n        if(root->right == nullptr) rightBoundary(root->left, nodes);\n        else rightBoundary(root->right, nodes);\n        nodes.push_back(root->val); // add after child visit(reverse)\n    }\n    \n    void leaves(TreeNode* root, vector<int>& nodes) {\n        if(root == nullptr) return;\n        if(root->left == nullptr && root->right == nullptr) {\n            nodes.push_back(root->val);\n            return;\n        }\n        leaves(root->left, nodes);\n        leaves(root->right, nodes);\n    }\n    \npublic:\n    vector<int> boundaryOfBinaryTree(TreeNode* root) {\n        vector<int> nodes;\n        if (root == nullptr) return nodes;\n        nodes.push_back(root->val);\n        leftBoundary(root->left, nodes);\n        leaves(root->left, nodes);\n        leaves(root->right, nodes);\n        rightBoundary(root->right, nodes);\n        return nodes;\n    }\n};\n"
  },
  {
    "path": "cpp/541-550/Diameter of Binary Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    int dfs(TreeNode* root, int& ans) {\n        if (!root) return 0;\n        int leftD = dfs(root->left, ans);\n        int rightD = dfs(root->right, ans);\n        \n        ans = max(ans, 1 + leftD + rightD);\n        return max(leftD, rightD) + 1;\n    }\n    \npublic:\n    int diameterOfBinaryTree(TreeNode* root) {\n        if (!root) return 0;\n        int ans = 0;\n        dfs(root, ans);\n        return ans - 1;\n    }\n};\n"
  },
  {
    "path": "cpp/541-550/Friend Circles.cpp",
    "content": "class Solution {\npublic:\n    void dfs(int i, vector<vector<int>>& M, vector<int>& colors) {\n        colors[i] = 1;\n        int m = M.size();\n        for (int j = 0; j < m; j++) {\n            if (M[i][j] == 0) continue;\n            if (colors[j] == 0) {\n                dfs(j, M, colors);\n            }\n        }\n    }\n    \n    int findCircleNum(vector<vector<int>>& M) {\n        int m = M.size();\n        if (m == 0) return 0;\n        int res = 0;\n        vector<int> colors(m, 0);\n        for (int i = 0; i < m; i++) {\n            if (colors[i] == 0) {\n                res++;\n                dfs(i, M, colors);\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/541-550/Output Contest Matches.cpp",
    "content": "class Solution {\npublic:\n    string findContestMatch(int n) {\n        vector<string> m(n);\n        for (int i = 0; i < n; i++) {\n            m[i] = to_string(i + 1);\n        }\n\n        while (n > 1) {\n            for (int i = 0; i < n / 2; i++) {\n                m[i] = \"(\" + m[i] + \",\" + m[n - 1 - i] + \")\";\n            }\n            n /= 2;\n        }\n        \n        return m[0];\n    }\n};\n"
  },
  {
    "path": "cpp/541-550/Reverse String II.cpp",
    "content": "class Solution {\n    \n    void _reverse(string &str, int i, int j) {\n        while (i < j) swap(str[i++], str[j--]);\n    }\n    \npublic:\n    string reverseStr(string s, int k) {\n        int i = 0;\n        while (true) {\n            if (i >= s.length()) break;\n            int start = i;\n            int end = min(i + 2*k, (int)s.length()) - 1;\n            _reverse(s, start, min(end, start + k - 1) );\n            i = end + 1;\n        }\n        return s;\n    }\n};\n"
  },
  {
    "path": "cpp/541-550/Split Array with Equal Sum.cpp",
    "content": "class Solution {\npublic:\n    bool splitArray(vector<int>& nums) {\n        if (nums.size() < 7) return false;\n        vector<int> sum(nums.size(), 0);\n        sum[0] = nums[0];\n        for (int i = 1; i < nums.size(); i++) {\n            sum[i] = sum[i - 1] + nums[i];\n        }\n        for (int j = 3; j < nums.size() - 3; j++) {\n            unordered_set<int> candidate;\n            for (int i = 1; i < j - 1; i++) {\n                if (sum[i - 1] == sum[j - 1] - sum[i])\n                    candidate.insert(sum[i - 1]);\n            }\n            for (int k = j + 2; k < nums.size() - 1; k++) {\n                if (sum[nums.size() - 1] - sum[k] == sum[k - 1] - sum[j] && candidate.count(sum[k - 1] - sum[j]) > 0)\n                    return true;\n            }\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/551-560/Brick Wall.cpp",
    "content": "class Solution {\npublic:\n    int leastBricks(vector<vector<int>>& wall) {\n        map<int, int> mymap; // pos -> count\n        int maxCount = 0;\n            \n        for (const vector<int>& wal : wall) {\n            int sum = 0;\n            for (int i = 0; i < wal.size() - 1; i++) {\n                sum += wal[i];\n                mymap[sum]++;\n                maxCount = max(maxCount, mymap[sum]);\n            }\n        }\n        \n        return wall.size() - maxCount;\n    }\n};\n"
  },
  {
    "path": "cpp/551-560/Next Greater Element III.cpp",
    "content": "class Solution {\n    \n    void nextPermutation(vector<int> &num) {\n        if (num.empty()) return;\n        \n        // in reverse order, find the first number which is in increasing trend (we call it violated number here)\n        int i(0);\n        for (i = num.size()-2; i >= 0; --i)\n            if (num[i] < num[i+1]) break;\n        \n        // reverse all the numbers after violated number\n        reverse(begin(num)+i+1, end(num));\n        \n        // if violated number not found, because we have reversed the whole array, then we are done!\n        if (i == -1) return;\n        \n        // else binary search find the first number larger than the violated number\n        auto itr = upper_bound(num.begin()+i+1, num.end(), num[i]);\n        \n        // swap them, done!\n        swap(num[i], *itr);\n    }\n    \npublic:\n    int nextGreaterElement(int n) {\n        vector<int> myvec;\n        int nn = n;\n        while (nn > 0) {\n            int digit = nn % 10;\n            nn /= 10;\n            myvec.emplace(myvec.begin(), digit);\n        }\n        \n        nextPermutation(myvec);\n        int ans = 0;\n        for (int e : myvec) {\n            ans = 10 * ans + e;\n        }\n        \n        if (ans > n) return ans;\n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/551-560/Optimal Division.cpp",
    "content": "class Solution {\npublic:\n    string optimalDivision(vector<int>& nums) {\n        string result = to_string(nums[0]);\n        if (nums.size() == 1) return result;\n        if (nums.size() == 2) return result + \"/\" + to_string(nums[1]);\n        result = result + \"/(\" + to_string(nums[1]);\n        \n        for (int i = 2; i < nums.size(); i++) {\n            result = result + \"/\" + to_string(nums[i]);\n        }\n        \n        return result + \")\";\n    }\n};\n"
  },
  {
    "path": "cpp/551-560/Reverse Words in a String III.cpp",
    "content": "class Solution {\npublic:\n    string reverseWords(string s) {\n        size_t front = 0;\n        for(int i = 0; i <= s.length(); ++i){\n            if(i == s.length() || s[i] == ' '){\n                reverse(&s[front], &s[i]);\n                front = i + 1;\n            }\n        }\n        \n        return s;\n    }\n};\n"
  },
  {
    "path": "cpp/551-560/Split Concatenated Strings.cpp",
    "content": "class Solution {\npublic:\n    string splitLoopedString(vector<string>& strs) {\n        for (string& str: strs) {\n            string copyStr(str);\n            reverse(copyStr.begin(), copyStr.end());\n            if (copyStr > str) str = copyStr;\n        }\n        \n        string ans;\n        \n        for (int i = 0; i < strs.size(); i++) {\n            string str = strs[i];\n            \n            string before, after;\n            for (int k = 0; k < i; k++) before += strs[k];\n            for (int k = i+1; k < strs.size(); k++) after += strs[k];\n            \n            for (int k = 0; k < str.length(); k++) {\n                string strPrev = str.substr(0, k);\n                string strNext = str.substr(k);\n                string finalStr = strNext + after + before + strPrev;\n                if (finalStr > ans) ans = finalStr;\n            }\n            \n            reverse(str.begin(), str.end());\n            for (int k = 0; k < str.length(); k++) {\n                string strPrev = str.substr(0, k);\n                string strNext = str.substr(k);\n                string finalStr = strNext + after + before + strPrev;\n                if (finalStr > ans) ans = finalStr;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/551-560/Student Attendance Record I.cpp",
    "content": "class Solution {\npublic:\n    bool checkRecord(string s) {\n        int n = s.length();\n        int A = 0;\n        for (int i = 0; i < n; i++) {\n            char ch = s[i];\n            if (ch == 'A') A++;\n            if (ch == 'L' && (i+1 < n && s[i+1] == 'L') && (i+2<n && s[i+2] == 'L')) return false; \n        }\n        if (A <= 1) return true;\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/551-560/Student Attendance Record II.cpp",
    "content": "class Solution {\n    \n    int MOD = 1000000007;\n    \n    long sum(long nums[]) {\n        return (nums[0]+nums[1]+nums[2]) % MOD;\n    }\npublic:\n    int checkRecord(int n) {\n        // dp[n][A][L], 长度为n，包含A个字符'A'，以L个连续的'L'结尾的字符串的个数\n        long dp[2][3] = {{1, 1, 0}, {1, 0, 0}};\n        for (int i = 2; i <= n; i++) {\n            long ndp[2][3] = {{0, 0, 0}, {0, 0, 0}};\n            ndp[0][0] = sum(dp[0]);\n            ndp[0][1] = dp[0][0];\n            ndp[0][2] = dp[0][1];\n            ndp[1][0] = (sum(dp[0]) + sum(dp[1])) % MOD;\n            ndp[1][1] = dp[1][0];\n            ndp[1][2] = dp[1][1];\n            memcpy(dp, ndp, 6*sizeof(long));\n        }\n        return (int)((sum(dp[0]) + sum(dp[1])) % MOD);\n    }\n};\n"
  },
  {
    "path": "cpp/551-560/Subarray Sum Equals K.cpp",
    "content": "class Solution {\npublic:\n    int subarraySum(vector<int>& nums, int k) {\n        unordered_map<int, int> prefix_sum;\n        prefix_sum[0] = 1;\n        \n        int sum = 0;\n        int ans = 0;\n        for (int num : nums) {\n            sum += num;\n            int target = sum - k;\n            ans += prefix_sum[target];\n            prefix_sum[sum]++;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/561-570/Array Nesting.cpp",
    "content": "class Solution {\npublic:\n    int arrayNesting(vector<int>& nums) {\n        vector<bool> visited(nums.size(), false);\n        int result = 0;\n        for (int i = 0; i < nums.size(); i++) {\n            if (visited[i]) continue;\n            int count = 0;\n            int j = i;\n            while (!visited[j]) {\n                visited[j] = true;\n                j = nums[j];\n                count++;\n            }\n            result = max(result, count);\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/561-570/Array Partition I.cpp",
    "content": "class Solution {\npublic:\n    int arrayPairSum(vector<int>& nums) {\n        int sum = 0;\n        sort(nums.begin(), nums.end());\n        for (int i = 0; i < nums.size(); i++) {\n            if (i % 2 == 0) {\n                sum += nums[i];\n            }\n        }\n        return sum;\n    }\n};\n"
  },
  {
    "path": "cpp/561-570/Binary Tree Tilt.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    int dfs(TreeNode* root, int &result) {\n        if (!root) return 0;\n        int left = dfs(root->left, result);\n        int right = dfs(root->right, result);\n        result += abs(left - right);\n        return left + right + root->val;\n    }\npublic:\n    int findTilt(TreeNode* root) {\n        int result = 0;\n        dfs(root, result);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/561-570/Longest Line of Consecutive One in Matrix.cpp",
    "content": "class Solution {\npublic:\n    int longestLine(vector<vector<int>>& M) {\n        if (M.size() == 0)\n            return 0;\n        int ones = 0;\n        vector<vector<vector<int>>> dp = vector<vector<vector<int>>>(M.size(), vector<vector<int>>(M[0].size(), vector<int>(4,0)));\n        for (int i = 0; i < M.size(); i++) {\n            for (int j = 0; j < M[0].size(); j++) {\n                if (M[i][j] == 1) {\n                    dp[i][j][0] = j > 0 ? dp[i][j - 1][0] + 1 : 1;\n                    dp[i][j][1] = i > 0 ? dp[i - 1][j][1] + 1 : 1;\n                    dp[i][j][2] = (i > 0 && j > 0) ? dp[i - 1][j - 1][2] + 1 : 1;\n                    dp[i][j][3] = (i > 0 && j < M[0].size() - 1) ? dp[i - 1][j + 1][3]+1 : 1;\n                    ones = max(ones, max(max(dp[i][j][0], dp[i][j][1]), max(dp[i][j][2], dp[i][j][3])));\n                }\n            }\n        }\n        return ones;\n    }\n};\n"
  },
  {
    "path": "cpp/561-570/Maximum Vacation Days.cpp",
    "content": "class Solution {\npublic:\n    int maxVacationDays(vector<vector<int>>& flights, vector<vector<int>>& days) {\n        int n = days.size(), k = days[0].size(); // n city , k weeks\n        vector<vector<int>> dp(n, vector<int>(k, -1)); // dp[i][j] - max days play if you spent week j in city i;\n        \n        return dfs(0, 0, dp, flights, days);\n    }\n    \n    int dfs(int city, int week, vector<vector<int>>& dp, const vector<vector<int>>& flights, const vector<vector<int>>& days) {\n        int n = days.size(), k = days[0].size(); // n city , k weeks\n        if (week >= k) return 0;\n        if (dp[city][week] >= 0) return dp[city][week];\n        \n        int max_days = 0;\n        for (int i = 0; i < n; i++) {\n            if (flights[city][i] == 1 || city == i) {\n                max_days = max(dfs(i, week+1, dp, flights, days) + days[i][week], max_days);\n            }\n        }\n        \n        return dp[city][week] = max_days;\n    }\n};\n"
  },
  {
    "path": "cpp/561-570/Permutation in String.cpp",
    "content": "class Solution {\npublic:\n    bool checkInclusion(string s1, string s2) {\n        if (s1.length() > s2.length()) return false;\n        vector<int> mymap(256, 0);\n        vector<int> stats(256, 0);\n        \n        int count = s1.length();\n        for (char ch : s1) {\n            mymap[ch]++;\n        }\n        \n        for (int i = 0; i < s1.length(); i++) {\n            char ch = s2[i];\n            if(mymap[ch] > 0) {\n                stats[ch]++;\n                if (stats[ch] <= mymap[ch]) {\n                    count--;\n                }\n            }\n        }\n        \n        if (count == 0) return true;\n        \n        for (int i = s1.length(); i < s2.length(); i++) {\n            char oldChar = s2[i - s1.length()];\n            char newChar = s2[i];\n            if (oldChar == newChar) continue;\n            if (mymap[oldChar] > 0) {\n                stats[oldChar]--;\n                if (stats[oldChar] < mymap[oldChar] && stats[oldChar] >= 0) {\n                    count++;\n                }\n            }\n            if (mymap[newChar] > 0) {\n                stats[newChar]++;\n                if (stats[newChar] <= mymap[newChar] && stats[newChar] >= 0) {\n                    count--;\n                }\n            }\n            if (count == 0) return true;\n        }\n        \n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/561-570/Reshape the Matrix.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {\n        int m = nums.size(), n = nums[0].size();\n        if (r * c != m * n)\n            return nums;\n        vector<vector<int>> reshaped(r, vector<int>(c, 0));\n        for (int i = 0; i < r * c; i++)\n            reshaped[i/c][i%c] = nums[i/n][i%n];\n        return reshaped;\n    }\n};\n"
  },
  {
    "path": "cpp/571-580/Distribute Candies.cpp",
    "content": "class Solution {\npublic:\n    int distributeCandies(vector<int>& candies) {\n        int n = candies.size();\n        set<int> myset;\n        for (int e : candies) {\n            myset.insert(e);\n        }\n        if (myset.size() >= n / 2) {\n            return n/2;\n        } else {\n            return myset.size();\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/571-580/Out of Boundary Paths.cpp",
    "content": "class Solution {\n    \n    bool inBox(int i, int j, int m, int n) {\n        if (i < 0 || j < 0 || i >= m || j >= n) return false;\n        return true;\n    }\n    \n    long get(int i, int j, int k, vector<vector<vector<long>>>& dp, int m, int n) {\n        if (!inBox(j, k, m, n)) return 0;\n        return dp[i][j][k];\n    }\n    \n    int coeff(int i, int j, int m, int n) {\n        int coe = 0;\n        if (!inBox(i, j - 1, m, n)) coe++;\n        if (!inBox(i, j + 1, m, n)) coe++;\n        if (!inBox(i - 1, j, m, n)) coe++;\n        if (!inBox(i + 1, j, m, n)) coe++;\n        return coe;\n    }\n    \npublic:\n    int findPaths(int m, int n, int N, int i, int j) {\n        if (N == 0) return 0;\n        vector<vector<vector<long>>> dp(N + 1, vector<vector<long>>(m, vector<long>(n, 0)));\n        dp[0][i][j] = 1;\n        long result = 1 * coeff(i, j, m, n);\n        for (int i = 1; i < N; i++) {\n            for (int j = 0; j < m; j++) {\n                for (int k = 0; k < n; k++) {\n                    dp[i][j][k] = (get(i - 1, j - 1, k, dp , m, n)\n                        + get(i - 1, j + 1, k, dp , m, n)\n                        + get(i - 1, j, k - 1, dp , m, n)\n                        + get(i - 1, j, k + 1, dp , m, n)) % 1000000007;\n                    result += coeff(j, k, m, n) * dp[i][j][k];\n                    result %= 1000000007;\n                }\n            } \n        }\n\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/571-580/Squirrel Simulation.cpp",
    "content": "class Solution {\npublic:\n    int minDistance(int height, int width, vector<int>& tree, vector<int>& squirrel, vector<vector<int>>& nuts) {\n        int sum = 0;\n        int save = INT_MAX;\n        for (const auto& nut : nuts) {\n            int d = dis(tree[0], nut[0], tree[1], nut[1]);\n            sum += d*2;\n            int d2 = dis(squirrel[0], nut[0], squirrel[1], nut[1]);\n            save = min(save, d2 - d);\n        }\n        return sum + save;\n    }\n    \n    int dis(int a1, int b1, int a2, int b2) {\n        return abs(a1 - b1) + abs(a2 - b2);\n    }\n};\n"
  },
  {
    "path": "cpp/571-580/Subtree of Another Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    // Encodes a tree to a single string.\n    string serialize(TreeNode* root) {\n        if (root == nullptr) return \"# \";\n        else return to_string(root->val) + \" \" + serialize(root->left) + serialize(root->right);\n    }\n    \n    string serialize2(TreeNode* root, const string& target, bool &b) {\n        if (root == nullptr) return \"# \";\n        string res = to_string(root->val) + \" \" + serialize2(root->left, target, b) + serialize2(root->right, target, b);\n        if (res == target) b = true;\n        return res;\n    }\npublic:\n    bool isSubtree(TreeNode* s, TreeNode* t) {\n        string tstr = serialize(t);\n        bool res = false;\n        serialize2(s, tstr, res);\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/581-590/Delete Operation for Two Strings.cpp",
    "content": "class Solution {\n    int lcs(const string& X, const string& Y) {\n        int m = X.size();\n        int n = Y.size();\n        vector<vector<int>> dp(m+1, vector<int>(n+1, 0));\n        \n        for (int i = 0; i <= m; i++) {\n            for (int j = 0; j <= n; j++) {\n                if (i == 0 || j == 0)\n                    dp[i][j] = 0;\n                else if (X[i-1] == Y[j-1])\n                    dp[i][j] = dp[i-1][j-1] + 1;\n                else\n                    dp[i][j] = max(dp[i-1][j], dp[i][j-1]);\n            }\n       }\n        \n       return dp[m][n];\n    }\npublic:\n    int minDistance(string word1, string word2) {\n        int len = lcs(word1, word2);\n        return word1.size() + word2.size() - 2 * len;\n    }\n};\n"
  },
  {
    "path": "cpp/581-590/Design In-Memory File System.cpp",
    "content": "class FileSystem {\nprivate:\n    struct TrieNode {\n        bool isFile;\n        string content;\n        unordered_map<string, TrieNode *> children;\n        TrieNode() : isFile(false) {}\n    };\n\n    TrieNode *root;\n\n    vector<string> getPaths(const string &path) {\n        vector<string> elems;\n        stringstream ss(path);\n        string item;\n        while (std::getline(ss, item, '/')) {\n            if (!item.empty()) {\n                elems.push_back(item);\n            }\n        }\n        return elems;\n    }\n\npublic:\n    FileSystem() {\n        root = new TrieNode();\n    }\n    \n    vector<string> ls(string path) {\n        vector<string> paths = getPaths(path);\n        TrieNode *curr = root;\n        for (const string &path : paths)\n            curr = curr->children[path];\n        \n        if (curr->isFile)\n            return {paths.back()};\n        \n        vector<string> ans;\n        for (auto &p : curr->children)\n            ans.push_back(p.first);\n        sort(ans.begin(), ans.end());\n        return ans;\n    }\n    \n    void mkdir(string path) {\n        vector<string> paths = getPaths(path);\n        TrieNode *curr = root;\n        for (const string &path : paths) {\n            if (!curr->children.count(path))\n                curr->children[path] = new TrieNode();\n            curr = curr->children[path];\n        }\n    }\n    \n    void addContentToFile(string filePath, string content) {\n        vector<string> paths = getPaths(filePath);\n        TrieNode *curr = root;\n        for (const string &path : paths) {\n            if (!curr->children.count(path))\n                curr->children[path] = new TrieNode();\n            curr = curr->children[path];\n        }\n        curr->isFile = true;\n        curr->content += content;\n    }\n    \n    string readContentFromFile(string filePath) {\n        vector<string> paths = getPaths(filePath);\n        TrieNode *curr = root;\n        for (const string &path : paths)\n            curr = curr->children[path];\n        return curr->content;\n    }\n};\n"
  },
  {
    "path": "cpp/581-590/Erect the Fence.cpp",
    "content": "/**\n * Definition for a point.\n * struct Point {\n *     int x;\n *     int y;\n *     Point() : x(0), y(0) {}\n *     Point(int a, int b) : x(a), y(b) {}\n * };\n */\n// Ref: http://www.algorithmist.com/index.php/Monotone_Chain_Convex_Hull.cpp\nclass Solution {\n public:\n  typedef int coord_t;  // coordinate type\n  typedef long long coord2_t;  // must be big enough to hold 2*max(|coordinate|)^2\n  // 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross\n  // product. Returns a positive value, if OAB makes a counter-clockwise turn,\n  // negative for clockwise turn, and zero if the points are collinear.\n  coord2_t cross(const Point &O, const Point &A, const Point &B) {\n    return (A.x - O.x) * (coord2_t)(B.y - O.y) -\n           (A.y - O.y) * (coord2_t)(B.x - O.x);\n  }\n\n  static bool cmp(Point &p1, Point &p2) {\n    return p1.x < p2.x || (p1.x == p2.x && p1.y < p2.y);\n  }\n\n  static bool equ(Point &p1, Point &p2) { return p1.x == p2.x && p1.y == p2.y; }\n  // Returns a list of points on the convex hull in counter-clockwise order.\n  // Note: the last point in the returned list is the same as the first one.\n  vector<Point> outerTrees(vector<Point> &P) {\n    int n = P.size(), k = 0;\n    vector<Point> H(2 * n);\n\n    // Sort points lexicographically\n    sort(P.begin(), P.end(), cmp);\n\n    // Build lower hull\n    for (int i = 0; i < n; i++) {\n      while (k >= 2 && cross(H[k - 2], H[k - 1], P[i]) < 0) k--;\n      H[k++] = P[i];\n    }\n\n    // Build upper hull\n    for (int i = n - 2, t = k + 1; i >= 0; i--) {\n      while (k >= t && cross(H[k - 2], H[k - 1], P[i]) < 0) k--;\n      H[k++] = P[i];\n    }\n\n    // Remove duplicates\n    H.resize(k);\n    sort(H.begin(), H.end(), cmp);\n    H.erase(unique(H.begin(), H.end(), equ), H.end());\n    return H;\n  }\n};\n"
  },
  {
    "path": "cpp/581-590/Kill Process.cpp",
    "content": "class Solution {\npublic:\n    vector<int> killProcess(vector<int>& pid, vector<int>& ppid, int kill) {\n        map<int, vector<int>> ppids;\n        for (int i = 0; i < pid.size(); i++) {\n            ppids[ppid[i]].push_back(pid[i]);\n        }\n        \n        vector<int> results;\n        queue<int> myqueue;\n        myqueue.push(kill);\n        while (!myqueue.empty()) {\n            int id = myqueue.front();\n            myqueue.pop();\n            results.push_back(id);\n            if (ppids.count(id) > 0) {\n                vector<int> ids = ppids[id];\n                for (int e : ids) myqueue.push(e);\n            }\n        }\n        \n        return results;\n    }\n};\n"
  },
  {
    "path": "cpp/581-590/Shortest Unsorted Continuous Subarray.cpp",
    "content": "class Solution {\npublic:\n    int findUnsortedSubarray(vector<int>& nums) {\n        int minimum = INT_MAX;\n        int lastBadIndex = -1;\n        for (int i = nums.size() - 1; i >= 0; i--) {\n            minimum = min(minimum, nums[i]);\n            if (minimum != nums[i]) lastBadIndex = i;\n        }\n        \n        int maximum = INT_MIN;\n        int lastBadIndex2 = -1;\n        for (int i = 0; i < nums.size(); i++) {\n            maximum = max(maximum, nums[i]);\n            if (maximum != nums[i]) lastBadIndex2 = i;\n        }\n        if (lastBadIndex2 <= lastBadIndex) return 0;\n        return lastBadIndex2 - lastBadIndex + 1;\n    }\n};\n"
  },
  {
    "path": "cpp/591-600/Fraction Addition and Subtraction.cpp",
    "content": "// https://discuss.leetcode.com/topic/90061/small-and-simple-c-and-java/2\nclass Solution {\npublic:\n    string fractionAddition(string expression) {\n        istringstream in(expression);\n        int A = 0, B = 1, a, b;\n        char _;\n        while (in >> a >> _ >> b) {\n            A = A * b + a * B;\n            B *= b;\n            int g = abs(__gcd(A, B));\n            A /= g;\n            B /= g;\n        }\n        return to_string(A) + '/' + to_string(B);\n    }\n};\n"
  },
  {
    "path": "cpp/591-600/Longest Harmonious Subsequence.cpp",
    "content": "class Solution {\npublic:\n    int findLHS(vector<int>& nums) {\n        map<int, int> mymap;\n        for (int num : nums) {\n            mymap[num]++;\n        }\n        \n        int result = 0;\n        for (auto it : mymap) {\n            if (mymap.count(it.first+1)) {\n                result = max(result, mymap[it.first + 1] + mymap[it.first]);\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/591-600/Minimum Index Sum of Two Lists.cpp",
    "content": "class Solution {\npublic:\n    vector<string> findRestaurant(vector<string>& list1, vector<string>& list2) {\n        map<string, int> mymap;\n        for (int i = 0; i < list1.size(); i++) {\n            mymap[list1[i]] = i;\n        }\n        \n        vector<string> result;\n        int minSum = INT_MAX;\n        \n        for (int i = 0; i < list2.size(); i++) {\n            auto it = mymap.find(list2[i]);\n            if (it == mymap.end()) continue;\n            int idx = it->second + i;\n            if (idx == minSum) {\n                result.push_back(list2[i]);\n            }\n            if (idx < minSum) {\n                minSum = idx;\n                result.clear();\n                result.push_back(list2[i]);\n            }\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/591-600/Non-negative Integers without Consecutive Ones.cpp",
    "content": "class Solution {\n    int help(int num, int highestPos) {\n        // 110010 -> 001111\n        if ( (num >> (highestPos-2)) % 2 == 1) {\n            int mask = 0;\n            for (int i = 0; i < (highestPos - 2); i++) {\n                mask = mask*2+1;\n            }\n            return mask;\n        } else {\n            // 1010 -> 0010\n            int mask = 1 << (highestPos-1);\n            return num ^ mask;\n        }\n    }\npublic:\n    int findIntegers(int num) {\n        if (num == 0) return 1;\n        if (num == 1) return 2;\n        if (num == 2 || num == 3) return 3;\n        int dp[33] = {0};\n        dp[0] = dp[1] = dp[2] = 1;\n        int sum = 3;\n        int highestPos = 0;\n        int temp = num;\n        while (temp > 0) {\n            highestPos++;\n            temp = temp >> 1;\n        }\n        for (int i = 3; i < highestPos; i++) {\n            dp[i] = dp[i-2] + dp[i-1];\n            sum += dp[i];\n        }\n        int remain = help(num, highestPos);\n        return sum + findIntegers(remain);\n    }\n};\n"
  },
  {
    "path": "cpp/591-600/Range Addition II.cpp",
    "content": "class Solution {\npublic:\n    int maxCount(int m, int n, vector<vector<int>>& ops) {\n        int a = m, b = n;\n        for (const vector<int>& op : ops) {\n            a = min(a, op[0]);\n            b = min(b, op[1]);\n        }\n        return a*b;\n    }\n};\n"
  },
  {
    "path": "cpp/591-600/Tag Validator.cpp",
    "content": "class Solution {\npublic:\n    bool isValid(string code)  {\n        stack<string> stk;\n\t    for (int i = 0; i < code.length(); i++) {        \n\t        if (i > 0 && stk.empty()) return false;\n\t        if (code.substr(i, 9) == \"<![CDATA[\") {\n\t\t        int j = i + 9;\n\t\t        i = code.find(\"]]>\", j);\n\t\t        if (i < 0) return false;\n\t\t        i += 2;\n            } else if (code.substr(i, 2) == \"</\") {\n                int j = i + 2;\n                i = code.find('>', j);\n                string s = code.substr(j, i - j);\n                if (stk.empty() || s != stk.top()) return false;\n                stk.pop();\n\t        } else if (code.substr(i, 1) == \"<\") {\n                int j = i + 1;\n                i = code.find('>', j);\n                if (i < 0 || i == j || i - j > 9) return false;\n                for (int k = j; k < i; k++) {\n                    if (!isupper(code[k])) return false;\n                }\n                string s = code.substr(j, i - j);\n                stk.push(s);\n            }\n        }\n        return stk.empty();        \n    }\n};\n"
  },
  {
    "path": "cpp/591-600/Valid Square.cpp",
    "content": "class Solution {\n    int dSquare(vector<int>& p1, vector<int>& p2) {\n        return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]);\n    }\npublic:\n    \n    bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {\n        unordered_set<int> s({ dSquare(p1, p2), dSquare(p1, p3), dSquare(p1, p4),\n            dSquare(p2, p3), dSquare(p2, p4), dSquare(p3, p4) });\n        return !s.count(0) && s.size() == 2;\n    }\n    \n};\n"
  },
  {
    "path": "cpp/601-610/Can Place Flowers.cpp",
    "content": "class Solution {\npublic:\n    bool canPlaceFlowers(vector<int>& flowerbed, int n) {\n        if (n <= 0) {\n            return true;\n        }\n        flowerbed.insert(flowerbed.begin(), 0);\n        flowerbed.push_back(0);\n        for (int i = 1; i < flowerbed.size() - 1; ++i) {\n            if (flowerbed[i-1] + flowerbed[i] + flowerbed[i+1] == 0) {\n                --n;\n                ++i;\n            }\n            if (n == 0) {\n                return true;\n            }\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/601-610/Construct String from Binary Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    string tree2str(TreeNode* t) {\n        if (!t) return \"\";\n        string s = to_string(t->val);\n\n        if (t->left) {\n            s += \"(\" + tree2str(t->left) + \")\";\n        }\n        else if (t->right) {\n            s += \"()\";\n        }\n        \n        if (t->right) {\n            s += \"(\" + tree2str(t->right) + \")\";\n        }\n\n        return s;\n    }\n};\n"
  },
  {
    "path": "cpp/601-610/Design Compressed String Iterator.cpp",
    "content": "class StringIterator {\n    string str;\n    char current;\n    int times;\n    int index;\npublic:\n    StringIterator(string compressedString) {\n        str = compressedString;\n        times = 0;\n        index = 0;\n    }\n    \n    char next() {\n        if (hasNext()) {\n            times--;\n            return current;\n        }\n        return ' ';\n    }\n    \n    bool hasNext() {\n        if (times > 0) return true;\n        if (index >= str.length()) return false;\n        current = str[index++];\n        int temp = 0;\n        while (index < str.length() && isdigit(str[index])) {\n            temp = 10 * temp + (str[index] - '0');\n            index++;\n        }\n        times = temp;\n        return true;\n    }\n};\n\n/**\n * Your StringIterator object will be instantiated and called as such:\n * StringIterator obj = new StringIterator(compressedString);\n * char param_1 = obj.next();\n * bool param_2 = obj.hasNext();\n */\n"
  },
  {
    "path": "cpp/601-610/Find Duplicate File in System.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<string>> findDuplicate(vector<string>& paths) {\n        unordered_map<string, vector<string>> files;\n        vector<vector<string>> result;\n\n        for (const auto& path : paths) {\n            stringstream ss(path);\n            string root;\n            string s;\n            getline(ss, root, ' ');\n            while (getline(ss, s, ' ')) {\n                string fileName = root + '/' + s.substr(0, s.find('('));\n                string fileContent = s.substr(s.find('(') + 1, s.find(')') - s.find('(') - 1);\n                files[fileContent].emplace_back(fileName);\n            }\n        }\n\n        for (const auto& file : files) {\n            if (file.second.size() > 1)\n                result.emplace_back(file.second);\n        }\n\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/611-620/Add Bold Tag in String.cpp",
    "content": "class Solution {\npublic:\n    string addBoldTag(string s, vector<string>& dict) {\n        vector<pair<int, int>> ranges = findpairs(s, dict);\n        ranges = merge(ranges);\n        for (auto it = ranges.rbegin(); it != ranges.rend(); it++) {\n            s.insert(it->second, \"</b>\");\n            s.insert(it->first, \"<b>\");\n        }\n        return s;\n    }\n\nprivate:\n    vector<pair<int, int>> findpairs(const string& s, const vector<string>& dict) {\n        vector<pair<int, int>> res;\n        for (const string& w : dict) {\n            int n = w.size();\n            for (int i = 0; (i = s.find(w, i)) != string::npos; i++) {\n                res.emplace_back(make_pair(i, i + n));\n            }\n        }\n        return res;\n    }\n\n    vector<pair<int, int>> merge(vector<pair<int, int>>& a) {\n        vector<pair<int, int>> r;\n        auto cmp = [&](const pair<int, int>& a, const pair<int, int>& b) {\n            return a.first < b.first || a.first == b.first && a.second < b.second;\n        };\n        sort(a.begin(), a.end(), cmp);\n        for (int i = 0, j = -1; i < a.size(); i++) {\n            if (j < 0 || a[i].first > r[j].second) {\n                r.push_back(a[i]);\n                j++;\n            } else {\n                r[j].second = max(r[j].second, a[i].second);\n            }\n        }\n        \n        return r;\n    }\n};\n"
  },
  {
    "path": "cpp/611-620/Merge Two Binary Trees.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {\n        if (t1 == nullptr && t2 == nullptr) return nullptr;\n        TreeNode *root = new TreeNode(0);\n        if (t1 != nullptr && t2 != nullptr) {\n            root->val = t1->val + t2->val;\n            root->left = mergeTrees(t1->left, t2->left);\n            root->right = mergeTrees(t1->right, t2->right);\n        } else if (t1 != nullptr) {\n            root->val = t1->val;\n            root->left = mergeTrees(t1->left, nullptr);\n            root->right = mergeTrees(t1->right, nullptr);\n        } else {\n            root->val = t2->val;\n            root->left = mergeTrees(nullptr, t2->left);\n            root->right = mergeTrees(nullptr, t2->right);\n        }\n        return root;\n    }\n};\n"
  },
  {
    "path": "cpp/611-620/Valid Triangle Number.cpp",
    "content": "class Solution {\npublic:\n    int triangleNumber(vector<int>& nums) {\n        int n = nums.size();\n        int result = 0;\n        sort(nums.begin(), nums.end());\n        for (int i = n - 1; i >= 0; i--) {\n            int left = 0;\n            int right = i - 1;\n            while (left < right) {\n                if ((nums[left] + nums[right]) > nums[i]) {\n                    result += (right - left);\n                    right--;\n                } else {\n                    left++;\n                }\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/621-630/Add One Row to Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    void dfs(TreeNode* root, TreeNode* parent, int v, int d, bool left) {\n        if (root == nullptr && d > 1) return;\n        if (d == 1) {\n            TreeNode* node = new TreeNode(v);\n            if (left) {\n                node->left = root;\n                parent->left = node;\n            } else {\n                node->right = root;\n                parent->right = node;\n            }\n            return;\n        }\n        dfs(root->left, root, v, d - 1, true);\n        dfs(root->right, root, v, d - 1, false);\n    }\npublic:\n    TreeNode* addOneRow(TreeNode* root, int v, int d) {\n        if (d == 1) {\n            TreeNode* newRoot = new TreeNode(v);\n            newRoot->left = root;\n            return newRoot;\n        }\n        dfs(root, nullptr, v, d, true);\n        return root;\n    }\n};\n"
  },
  {
    "path": "cpp/621-630/Course Schedule III.cpp",
    "content": "class Solution {\npublic:\n    int scheduleCourse(vector<vector<int>>& courses) {\n        auto cmp = [](const vector<int> &a, const vector<int> &b) {\n            return a[0] < b[0] || (a[0] == b[0] && a[1] > b[1]);\n        };\n\n        priority_queue<vector<int>, vector<vector<int>>, decltype(cmp)> pq(cmp);\n        \n        sort(begin(courses), end(courses), [](const vector<int> &a, const vector<int> &b) {\n            return a[1] < b[1] || (a[1] == b[1] && a[0] < b[0]);\n        });\n        \n        int totalTime = 0;\n        for (int i = 0; i < courses.size(); i++) {\n            vector<int> current = courses[i];\n            if (current[0] + totalTime <= current[1]) {\n                totalTime += current[0];\n                pq.push(current);\n            } else if (!pq.empty()) {\n                vector<int> mayDiscard = pq.top();\n                if (current[0] < mayDiscard[0]) {\n                    pq.pop();\n                    pq.push(current);\n                    totalTime += (current[0] - mayDiscard[0]);\n                }\n            }\n        }\n        \n        return pq.size();\n    }\n};\n"
  },
  {
    "path": "cpp/621-630/Design Circular Queue.cpp",
    "content": "class MyCircularQueue {\n    vector<int> vec;\n    int head;\n    int tail;\n    int size;\n    int capacity;\npublic:\n    /** Initialize your data structure here. Set the size of the queue to be k. */\n    MyCircularQueue(int k) {\n        vec.resize(k, 0);\n        capacity = k;\n        head = 0;\n        tail = -1;\n        size = 0;\n    }\n    \n    /** Insert an element into the circular queue. Return true if the operation is successful. */\n    bool enQueue(int value) {\n        if (size == capacity) return false;\n        tail = (tail+1) % capacity;\n        vec[tail] = value;\n        size++;\n        return true;\n    }\n    \n    /** Delete an element from the circular queue. Return true if the operation is successful. */\n    bool deQueue() {\n        if (size == 0) return false;\n        head = (head+1) % capacity;\n        size--;\n        return true;\n    }\n    \n    /** Get the front item from the queue. */\n    int Front() {\n        if (size == 0) return -1;\n        return vec[head];\n    }\n    \n    /** Get the last item from the queue. */\n    int Rear() {\n        if (size == 0) return -1;\n        return vec[tail];\n    }\n    \n    /** Checks whether the circular queue is empty or not. */\n    bool isEmpty() {\n        return size == 0;\n    }\n    \n    /** Checks whether the circular queue is full or not. */\n    bool isFull() {\n        return size == capacity;\n    }\n};\n\n/**\n * Your MyCircularQueue object will be instantiated and called as such:\n * MyCircularQueue* obj = new MyCircularQueue(k);\n * bool param_1 = obj->enQueue(value);\n * bool param_2 = obj->deQueue();\n * int param_3 = obj->Front();\n * int param_4 = obj->Rear();\n * bool param_5 = obj->isEmpty();\n * bool param_6 = obj->isFull();\n */\n"
  },
  {
    "path": "cpp/621-630/K Inverse Pairs Array.cpp",
    "content": "class Solution {\n    const int mod = pow(10, 9) + 7;\npublic:\n    int kInversePairs(int n, int k) {\n        vector<vector<int>> dp(n+1, vector<int>(k+1, -1));\n        return dfs(n, k, dp);\n    }\n    \n    long dfs(int n, int k, vector<vector<int>>& dp) {\n        if (n == 0) return 0;\n        if (n == 1 && k == 0) return 1;\n        if (n == 1 && k == 1) return 0;\n        if (k == 0) return 1;\n        if (n == 2 && k == 1) return 1;\n        int bound = (n-1)*n/2;\n        if (k > bound) return 0;\n        if (dp[n][k] > -1) return dp[n][k];\n        int temp = 0;\n        if (k > bound/2) return dp[n][k] = ( dfs(n, bound - k, dp) % mod);\n        else temp = (dfs(n - 1, k, dp) + dfs(n, k - 1, dp)) % mod;\n        int nonused = k - n;\n        if (nonused >= 0) temp = (temp + mod - dfs(n - 1, nonused, dp)) % mod;\n        return dp[n][k] = temp;\n    }\n\n};\n"
  },
  {
    "path": "cpp/621-630/Maximum Distance in Arrays.cpp",
    "content": "class Solution {\npublic:\n    int maxDistance(vector<vector<int>>& arrays) {\n        int left = arrays[0].front();\n        int right = arrays[0].back();\n        int ans = 0;\n        for (int i = 1; i < arrays.size(); i++) {\n            ans = max(ans, max(abs(arrays[i].front() - right), abs(arrays[i].back() - left)));\n            left = min(left, arrays[i].front());\n            right = max(right, arrays[i].back());\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/621-630/Maximum Product of Three Numbers.cpp",
    "content": "class Solution {\npublic:\n    int maximumProduct(vector<int>& nums) {\n        sort(nums.begin(), nums.end());\n        int n = nums.size();\n        int temp1 = nums[n-1] * nums[n-2] * nums[n-3];\n        int temp2 = nums[0] * nums[1] * nums[n-1];\n        return max(temp1, temp2);\n    }\n};\n"
  },
  {
    "path": "cpp/621-630/Minimum Factorization.cpp",
    "content": "class Solution {\npublic:\n    int smallestFactorization(int a) {\n        if (a == 1) return 1;\n        string result = \"\";\n        int temp = 9;\n        while (temp > 1) {\n            if (a % temp == 0) {\n                result = to_string(temp) + result;\n                a /= temp;\n            } else {\n                temp--;\n            }\n        }\n        if (a > 10) return 0;\n        if (result.length() > 10) return 0;\n        if (result.length() < 10) return stoi(result);\n        string mm = to_string(INT_MAX);\n        if (result > mm) return 0;\n        return stoi(result);\n    }\n};\n"
  },
  {
    "path": "cpp/621-630/Task Scheduler.cpp",
    "content": "class Solution {\npublic:\n    int leastInterval(vector<char>& tasks, int n) {\n        map<char, int> mymap;\n        int maximumTimes = 0;\n        for (char ch : tasks) {\n            mymap[ch]++;\n            maximumTimes = max(maximumTimes, mymap[ch]);\n        }\n        \n        int ans = (maximumTimes -  1) * (n + 1);\n        \n        for (const auto& ele : mymap) {\n            if (maximumTimes == ele.second) {\n                ans++;\n            }\n        }\n        \n        return max(int(tasks.size()), ans);\n    }\n};\n"
  },
  {
    "path": "cpp/631-640/Average of Levels in Binary Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<double> averageOfLevels(TreeNode* root) {\n        vector<double> ret;\n        double sum = 0, count = 0;\n        queue<TreeNode*> q;\n        q.push(root);\n        q.push(nullptr);\n        while (!q.empty()) {\n            TreeNode* t = q.front();\n            q.pop();\n            if (t == nullptr) {\n                ret.push_back(sum / count);\n                sum = count = 0;\n                if (!q.empty()) q.push(nullptr);\n            } else {\n                sum += t->val;\n                ++count;\n                if (t->left) q.push(t->left);\n                if (t->right) q.push(t->right);\n            }\n        }\n        return ret;\n    }\n};\n"
  },
  {
    "path": "cpp/631-640/Decode Ways II.cpp",
    "content": "class Solution {\n    const int mod = 1000000007;\n    \n    int ways(char ch) {\n        if (ch == '*') return 9;\n        if (ch == '0') return 0;\n        return 1;\n    }\n    \n    int ways(char ch1, char ch2) {\n        if (ch1 == '0') return 0;\n        if (ch1 == '*') {\n            if (ch2 == '*') return 15;\n            if (ch2 <= '6') return 2;\n            return 1;\n        }\n        if (ch1 == '1') {\n            if (ch2 == '*') return 9;\n            return 1;\n        }\n        if (ch1 == '2') {\n            if (ch2 == '*') return 6;\n            if (ch2 <= '6') return 1;\n            return 0;\n        }\n        return 0;\n    }\n    \npublic:\n    int numDecodings(string s) {\n        int n = s.length();\n        vector<long> dp(n, 0);\n        for (int i = 0; i < n; i++) {\n            if (i == 0) {\n                dp[0] = ways(s[0]);\n            } else if (i == 1) {\n                dp[1] = dp[0] * ways(s[1]) + ways(s[0], s[1]);\n            } else {\n                dp[i] = (dp[i - 1] * ways(s[i]) + dp[i - 2] * ways(s[i - 1], s[i])) % mod;\n            }\n        }\n        return dp[n - 1];\n    }\n};\n"
  },
  {
    "path": "cpp/631-640/Design Excel Sum Formula.cpp",
    "content": "class Excel {\n    vector<vector<int>> matrix;\n    map<pair<int, int>, vector<string>> cellStrMapping;\n    \n    int c2i(char ch) { return ch - 'A'; }\n    \n    pair<int, char> parseNum(const string& num) {\n        int row = stoi(num.substr(1));\n        return {row, num[0]};\n    }\npublic:\n    Excel(int H, char W) {\n        matrix = vector<vector<int>>(H, vector<int>(c2i(W) + 1, 0));\n    }\n    \n    void set(int r, char c, int v) {\n        int col = c2i(c);\n        pair<int, int> mypair = {r, col};\n        if (cellStrMapping.count(mypair) != 0) {\n            cellStrMapping.erase(mypair);\n        }\n        matrix[r-1][c2i(c)] = v;\n    }\n    \n    int get(int r, char c) {\n        int col = c2i(c);\n        pair<int, int> mypair = {r, col};\n        if (cellStrMapping.count(mypair) == 0) {\n            return matrix[r-1][col];\n        } else {\n            vector<string> allStrs = cellStrMapping[mypair];\n            int result = 0;\n            for (const string& num : allStrs) {\n                int idx = num.find(':');\n                if (idx >= 0) {\n                    pair<int, char> cellStart = parseNum(num.substr(0, idx));\n                    pair<int, char> cellEnd = parseNum(num.substr(idx + 1));\n                    int row1 = cellStart.first;\n                    int row2 = cellEnd.first;\n                    int col1 = cellStart.second - 'A';\n                    int col2 = cellEnd.second - 'A';\n                    for (int i = row1; i <= row2; i++) {\n                        for (int j = col1; j <= col2; j++) {\n                            char ch = 'A' + j;\n                            result += (get(i, ch));\n                        }\n                    }\n                } else {\n                    pair<int, char> cell = parseNum(num);\n                    result += get(cell.first, cell.second);\n                }\n            }\n            return result;\n        }\n    }\n    \n    int sum(int r, char c, vector<string> strs) {\n        int col = c2i(c);\n        pair<int, int> mypair = {r, col};\n        cellStrMapping[mypair] = strs;\n        return get(r, c);\n    }\n};\n\n/**\n * Your Excel object will be instantiated and called as such:\n * Excel obj = new Excel(H, W);\n * obj.set(r,c,v);\n * int param_2 = obj.get(r,c);\n * int param_3 = obj.sum(r,c,strs);\n */\n"
  },
  {
    "path": "cpp/631-640/Design Log Storage System.cpp",
    "content": "class LogSystem {\n    vector<pair<int, string>> logs;\npublic:\n    LogSystem() {\n        \n    }\n    \n    void put(int id, string timestamp) {\n        logs.push_back({id, timestamp});\n    }\n    \n    vector<int> retrieve(string s, string e, string gra) {\n        int length = 0;\n        if (gra == \"Year\") {\n            length = 4;\n        } else if (gra == \"Month\") {\n            length = 7;\n        } else if (gra == \"Day\") {\n            length = 10;\n        } else if (gra == \"Hour\") {\n            length = 13;\n        } else if (gra == \"Minute\") {\n            length = 16;\n        } else if (gra == \"Second\") {\n            length = 19;\n        }\n        \n        s = s.substr(0, length);\n        e = e.substr(0, length);\n        \n        vector<int> result;\n        for (const auto& ele : logs) {\n            string str = ele.second.substr(0, length);\n            if (str >= s && str <= e) {\n                result.push_back(ele.first);\n            }\n        }\n        return result;\n    }\n};\n\n/**\n * Your LogSystem object will be instantiated and called as such:\n * LogSystem obj = new LogSystem();\n * obj.put(id,timestamp);\n * vector<int> param_2 = obj.retrieve(s,e,gra);\n */\n"
  },
  {
    "path": "cpp/631-640/Exclusive Time of Functions.cpp",
    "content": "class Solution {\n    vector<string> split(const string &s, char delim) {\n        vector<string> elems;\n        stringstream ss(s);\n        string item;\n        while (getline(ss, item, delim)) {\n            elems.push_back(item);\n        }\n        return elems;\n    }\n    \npublic:\n    vector<int> exclusiveTime(int n, vector<string>& logs) {\n        vector<int> result(n, 0);\n        stack<pair<int, int>> mystack; // pair<id, startTime>\n        for (const string& log : logs) {\n            vector<string> myvec = split(log, ':');\n            int id = stoi(myvec[0]);\n            bool flag = myvec[1] == \"start\" ? true : false; // true start; false end\n            int time = stoi(myvec[2]);\n            if (flag) {\n                mystack.push({id, time});\n            } else {\n                pair<int, int> currentPair = mystack.top();\n                mystack.pop();\n                int timeSpent = time - currentPair.second + 1;\n                result[currentPair.first] += timeSpent;\n                if (!mystack.empty()) {\n                    pair<int, int> callerPair = mystack.top();\n                    result[callerPair.first] -= timeSpent;\n                }\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/631-640/Find the Derangement of An Array.cpp",
    "content": "class Solution {\n    const int mod = 1000000007;\npublic:\n    int findDerangement(int n) {\n        vector<long> dp(n, 0);\n        bool flag = true;\n        for (int i = 2; i <= n; i++) {\n            if (flag) {\n                dp[i - 1] = (dp[i - 2] * i + 1) % mod;\n                flag = false;\n            } else {\n                dp[i - 1] = (dp[i - 2] * i - 1) % mod;\n                flag = true;\n            }\n        }\n        return dp[n - 1];\n    }\n};\n"
  },
  {
    "path": "cpp/631-640/Shopping Offers.cpp",
    "content": "class Solution {\n    void dfs(int currentPrice, int offerIndex, vector<int>& price, vector<vector<int>>& special, vector<int> needs, int& result) {\n        int n = price.size();\n        int nextOffer = offerIndex + 1;\n        if (nextOffer < special.size()) dfs(currentPrice, nextOffer, price, special, needs, result);\n        for (int k = 0; ; k++) {\n            bool finished = true;\n            for (int i = 0; i < special[offerIndex].size() - 1; i++) {\n                needs[i] -= special[offerIndex][i];\n                if (needs[i] < 0) return;\n                if (needs[i] > 0) finished = false;\n            }\n            currentPrice += special[offerIndex].back();\n            if (finished) {\n                result = min(currentPrice, result);\n                return;\n            }\n            if (nextOffer < special.size()) dfs(currentPrice, nextOffer, price, special, needs, result);\n        }\n    }\n    \npublic:\n    int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {\n        int n = price.size();\n        int result = INT_MAX;\n        for (int i = 0; i < n; i++) {\n            vector<int> temp(n + 1, 0);\n            temp[temp.size() - 1] = price[i];\n            temp[i] = 1;\n            special.push_back(temp);\n        }\n        \n        dfs(0, 0, price, special, needs, result);\n        return result == INT_MAX ? 0 : result;\n    }\n};\n"
  },
  {
    "path": "cpp/631-640/Smallest Range.cpp",
    "content": "class Solution {\npublic:\n    vector<int> smallestRange(vector<vector<int>>& nums) {\n        map<int, int> counters;\n        int n = nums.size();\n        int start = INT_MAX;\n        int end = INT_MIN;\n        \n        auto cmp = [](const pair<int, pair<int, int>> &a, const pair<int, pair<int, int>> &b) {\n            return a.first >= b.first;\n        };\n\n        priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, decltype(cmp)> pq(cmp);\n        \n        for (int i = 0; i < n; i++) {\n            pq.push({nums[i][0], {i, 0}});   // {value, {index of vector, index of element in this vector}}\n            start = min(start, nums[i][0]);\n            end = max(end, nums[i][0]);\n        }\n        \n        vector<int> result{start, end};\n        \n        while (true) {\n            if (end - start < result[1] - result[0]) {\n                result[0] = start;\n                result[1] = end;\n            }\n            pair<int, pair<int, int>> ele = pq.top();\n            pq.pop();\n            int v = ele.first;\n            int numsIndex = ele.second.first;\n            int eleIndex = ele.second.second;\n\n            if (eleIndex + 1 < nums[numsIndex].size()) {\n                pq.push({nums[numsIndex][eleIndex + 1], {numsIndex, eleIndex + 1}}); \n                end = max(end, nums[numsIndex][eleIndex + 1]);\n            } else {\n                break;\n            }\n\n            start = pq.top().first;\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/631-640/Solve the Equation.cpp",
    "content": "class Solution {\n    \n    pair<int, int> parse(string str) {\n        int xCount = 0, dCount = 0;\n        int i = 0;\n        int sign = 1;\n        while (i < str.length()) {\n            if (str[i] == '+') { sign = 1; i++; continue;} \n            if (str[i] == '-') { sign = -1; i++; continue;}\n            int num = -1;\n            if (isdigit(str[i])) {\n                while (i < str.length() && isdigit(str[i])) {\n                    if (num < 0) num = str[i] - '0';\n                    else num = num * 10 + (str[i] - '0');\n                    i++;\n                }\n                \n                if (i >= str.length()) {\n                    dCount += (sign * num);\n                    break;\n                }\n            }\n            \n            if (str[i] == 'x') {\n                if (num == -1) num = 1;\n                xCount += (sign * num);\n                i++;\n            } else {\n                dCount += (sign * num);\n            }\n        }\n        return {xCount, dCount};\n    }\n    \npublic:\n    string solveEquation(string equation) {\n        int index = equation.find(\"=\");\n        string left = equation.substr(0, index);\n        string right = equation.substr(index + 1);\n        \n        pair<int, int> temp1 = parse(left);\n        pair<int, int> temp2 = parse(right);\n        \n        int d = temp2.second - temp1.second;\n        int x = temp1.first - temp2.first;\n        \n        if (x == 0) {\n            if (d == 0) {\n                return \"Infinite solutions\";\n            } \n            return \"No solution\";\n        }\n        return \"x=\" + to_string(d/x);\n    }\n};\n"
  },
  {
    "path": "cpp/631-640/Sum of Square Numbers.cpp",
    "content": "class Solution {\npublic:\n    bool judgeSquareSum(int c) {\n        if (c < 0) {\n            return false;\n        }\n        int left = 0, right = (int)sqrt(c);\n        while (left <= right) {\n            int cur = left * left + right * right;\n            if (cur < c) {\n                left++;\n            } else if (cur > c) {\n                right--;\n            } else {\n                return true;\n            }\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/641-650/2 Keys Keyboard.cpp",
    "content": "class Solution {\npublic:\n    int minSteps(int n) {\n        if (n == 1) return 0;\n        if (n == 2) return 2;\n        if (n == 3) return 3;\n        \n        for (int i = 2; i <= n; i++) {\n            if (n % i != 0) continue;\n            int temp = n / i;\n            if (temp < i) return n;\n            if (temp * i == n) {\n                return i + minSteps(temp);\n            }\n        }\n        \n        return n;\n    }\n};\n"
  },
  {
    "path": "cpp/641-650/Design Search Autocomplete System.cpp",
    "content": "class AutocompleteSystem {\n    unordered_map<string, int> dict;\n    string prefix;\n\npublic:\n    AutocompleteSystem(vector<string> sentences, vector<int> times) {\n        for (int i = 0; i < times.size(); i++)\n            dict[sentences[i]] += times[i];\n    }\n    \n    vector<string> input(char c) {\n        if (c == '#') {\n            dict[prefix]++;\n            prefix.clear();\n            return {};\n        }\n\n        prefix.push_back(c);\n        auto cmp = [](const pair<string, int> &a, const pair<string, int> &b) {\n            return a.second > b.second || (a.second == b.second && a.first < b.first);\n        };\n\n        priority_queue<pair<string, int>, vector<pair<string, int>>, decltype(cmp)> pq(cmp);\n\n        for (const auto& ele : dict) {\n            auto res = std::mismatch(prefix.begin(), prefix.end(), ele.first.begin());\n            if (res.first == prefix.end()){\n                pq.push(ele);\n                if (pq.size() > 3) {\n                    pq.pop();\n                }\n            }\n        }\n\n        vector<string> res(pq.size());\n        for (int i = pq.size() - 1; i >= 0; i--) {\n            res[i] = pq.top().first;\n            pq.pop();\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/641-650/Dota2 Senate.cpp",
    "content": "class Solution {\npublic:\n    string predictPartyVictory(string senate) {\n        queue<int> rQ, dQ;\n        for (int i = 0; i < senate.length(); i++) {\n            if (senate[i] == 'R') {\n                rQ.push(i);\n            } else {\n                dQ.push(i);\n            }\n        }\n        \n        while (!rQ.empty() && !dQ.empty()) {\n            int rIndex = rQ.front();\n            int dIndex = dQ.front();\n            rQ.pop();\n            dQ.pop();\n            if (rIndex < dIndex) {\n                rQ.push(rIndex + senate.length());\n            } else {\n                dQ.push(dIndex + senate.length());\n            }\n        }\n        \n        return rQ.empty() ? \"Dire\" : \"Radiant\";\n    }\n};\n"
  },
  {
    "path": "cpp/641-650/Maximum Average Subarray I.cpp",
    "content": "class Solution {\npublic:\n    double findMaxAverage(vector<int>& nums, int k) {\n        double sum = accumulate(nums.begin(), nums.begin() + k, 0);\n        double res = sum/k;\n        for (int i = 0; i < nums.size() - k; i++) {\n            sum = sum - nums[i] + nums[i+k];\n            res = max(res, sum/k);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/641-650/Maximum Average Subarray II.cpp",
    "content": "class Solution {\n    bool validate(const vector<int>& nums, int k, double mid) {\n        vector<double> numsCopy(nums.size());\n        for (int i = 0; i < nums.size(); i++) numsCopy[i] = nums[i] - mid;\n        double sum = 0;\n        double prevSum = 0;\n        double minPrevSum = 0;\n        for (int i = 0; i < numsCopy.size(); i++) {\n            sum += numsCopy[i];\n            if (i >= k) {\n                prevSum += numsCopy[i - k];\n                minPrevSum = min(minPrevSum, prevSum);\n                if (sum > minPrevSum) return true;\n            }\n            if (i == k - 1) {\n                if (sum >= 0) return true;\n            }\n        }\n        return false;\n    }\n    \npublic:\n    double findMaxAverage(vector<int>& nums, int k) {\n        auto result = std::minmax_element(nums.begin(), nums.end());\n        double left = *result.first;\n        double right = *result.second;\n        \n        while (abs(right - left) > 1e-5) {\n            double mid = (left + right) / 2;\n            if (validate(nums, k, mid)) {\n                left = mid;\n            } else {\n                right = mid;\n            }\n        }\n        \n        return left;\n    }\n};\n"
  },
  {
    "path": "cpp/641-650/Maximum Length of Pair Chain.cpp",
    "content": "class Solution {\npublic:\n    int findLongestChain(vector<vector<int>>& pairs) {\n        int n = pairs.size();\n        sort(pairs.begin(), pairs.end(), [](const vector<int>& a, const vector<int>&b) {\n            return a[1] < b[1] || a[1] == b[1] && a[0] < b[0];\n        });\n        \n        int cnt = 0;\n        vector<int>& pair = pairs[0];\n        for (const vector<int>& ele : pairs) {\n            if (cnt == 0 || ele[0] > pair[1]) {\n                pair = ele;\n                cnt++;\n            }\n        }\n        return cnt;\n    }\n};\n"
  },
  {
    "path": "cpp/641-650/Palindromic Substrings.cpp",
    "content": "class Solution {\npublic:\n    int countSubstrings(string s) {\n        int res = 0;\n        vector<vector<bool>> dp(s.length(), vector<bool>(s.length(), false));\n        for (int i = 0; i < s.length(); i++) {\n            dp[i][i] = true;\n            res++;\n        }\n        \n        for (int i = 0; i < s.length() - 1; i++) {\n            if (s[i] == s[i+1]) {\n                dp[i][i+1] = true;\n                res++;\n            }\n        }\n        \n        for (int step = 2; step < s.length(); step++) {\n            for (int i = 0; i < s.length() - step; i++) {\n                int j = i + step;\n                if (s[i] == s[j] && dp[i+1][j-1]) {\n                    dp[i][j] = true;\n                    res++;\n                }\n            }\n        }\n        \n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/641-650/Replace Words.cpp",
    "content": "vector<string> split(const string &s, char delim) {\n    vector<std::string> elems;\n    stringstream ss(s);\n    string item;\n    while (getline(ss, item, delim)) {\n        if (item.length() > 0) {\n            elems.push_back(item);\n        }\n    }\n    return elems;\n}\n\nstruct TrieNode {\n    TrieNode *nodes[26];\n    bool word;\n    // Initialize your data structure here.\n    TrieNode(): word(false) {\n        memset(nodes, 0, sizeof(nodes));\n    }\n};\n\nclass Trie {\n    \npublic:\n    Trie() {\n        root = new TrieNode();\n    }\n    \n    // Inserts a word into the trie.\n    void insert(const string& s) {\n        TrieNode *tmp = root;\n        for(char ch : s) {\n            int index = ch - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                tmp->nodes[index] = new TrieNode();\n            }\n            tmp = tmp->nodes[index];\n        }\n        tmp->word = true;\n    }\n    \n    // Returns if the word is in the trie.\n    string findShortestRoot(const string& word) {\n        TrieNode *tmp = root;\n        for(int i = 0; i < word.length(); i++) {\n            int index = word[i] - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                return word;\n            }\n            tmp = tmp->nodes[index];\n            if (tmp->word == true) {\n                return word.substr(0, i + 1);\n            }\n        }\n        return word;\n    }\n    \nprivate:\n    TrieNode* root;\n};\n\nclass Solution {\npublic:\n    string replaceWords(vector<string>& dict, string sentence) {\n        string returnSentence;\n        Trie myTrie;\n        \n        for (const string& str : dict) {\n            myTrie.insert(str);\n        }\n        \n        vector<string> words = split(sentence, ' ');\n        for (int i = 0; i < words.size(); i++) {\n            returnSentence += myTrie.findShortestRoot(words[i]);\n            if (i != words.size() - 1) {\n                returnSentence += ' ';\n            }\n        }\n        \n        return returnSentence;\n    }\n};\n"
  },
  {
    "path": "cpp/641-650/Set Mismatch.cpp",
    "content": "class Solution {\npublic:\n    vector<int> findErrorNums(vector<int>& nums) {\n        vector<int> result;\n        int n = nums.size();\n        int sum = accumulate(nums.begin(), nums.end(), 0);\n        unordered_set<int> hashset;\n        int i = 0;\n        while (hashset.count(nums[i]) == 0) {\n            hashset.insert(nums[i]);\n            i++;\n        }\n        result.push_back(nums[i]);\n        result.push_back((1+n)*n/2 - sum + nums[i]);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/651-660/4 Keys Keyboard.cpp",
    "content": "class Solution {\n    \npublic:\n    int maxA(int N) {\n        if (N <= 6) return N;\n        return max(3*maxA(N - 4), 4*maxA(N-5));\n    }\n};\n"
  },
  {
    "path": "cpp/651-660/Coin Path.cpp",
    "content": "class Solution {\npublic:\n    vector<int> cheapestJump(vector<int>& A, int B) {\n        vector<int> ans;\n        if (A.empty() || A.back() == -1) return ans;\n        int n = A.size();\n        vector<int> dp(n, INT_MAX), pos(n, -1);\n        dp[n-1] = A[n-1];\n        // working backward\n        for (int i = n-2; i >= 0; i--) {\n            if (A[i] == -1) continue;\n            for (int j = i+1; j <= min(i+B, n-1); j++) {\n                if (dp[j] == INT_MAX) continue;\n                if (A[i]+dp[j] < dp[i]) {\n                    dp[i] = A[i]+dp[j];\n                    pos[i] = j;\n                }\n            }\n        }\n        // cannot jump to An\n        if (dp[0] == INT_MAX) return ans;\n        int k = 0;\n        while (k != -1) {\n            ans.push_back(k+1);\n            k = pos[k];\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/651-660/Find Duplicate Subtrees.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {\n        vector<TreeNode*> result;\n        map<size_t, vector<TreeNode*>> mymap;\n        merkle(root, mymap);\n        for (const auto& ele : mymap) {\n            if (ele.second.size() > 1) {\n                result.push_back(ele.second[0]);\n            }\n        }\n        return result;\n    }\n    \n    string merkle(TreeNode* root, map<size_t, vector<TreeNode*>>& mymap) {\n        if (root == nullptr) {\n            return \"#\";\n        }\n        string left = merkle(root->left, mymap);\n        string right = merkle(root->right, mymap);\n        size_t current = hash<string>{}(left + to_string(root->val) + right);\n        mymap[current].push_back(root);\n        return to_string(current);\n    }\n};\n"
  },
  {
    "path": "cpp/651-660/Find K Closest Elements.cpp",
    "content": "// Solution 1.\nclass Solution {\npublic:\n    vector<int> findClosestElements(vector<int>& arr, int k, int x) {\n        auto it = lower_bound(arr.begin(), arr.end(), x);\n        int idx = it - arr.begin();\n        if (idx == arr.size()) {\n            idx--;\n        } else if (idx > 0) {\n            if (abs(arr[idx - 1] - x) <= abs(arr[idx] - x)) {\n                idx = idx - 1;\n            }\n        }\n        \n        int l = idx - 1;\n        int r = idx + 1;\n        for (int i = 2; i <= k; i++) {\n            if (l < 0) {\n                r++;\n            } else if (r >= arr.size()) {\n                l--;\n            } else {\n                if (abs(arr[l] - x) <= abs(arr[r] - x)) {\n                    l--;\n                } else {\n                    r++;\n                }\n            }\n        }\n        \n        return vector<int>(arr.begin() + l + 1, arr.begin() + r);\n    }\n};\n\n\n\n// Solution 2.\nclass Solution {\npublic:\n    vector<int> findClosestElements(vector<int>& arr, int k, int x) {\n        int left = 0;\n        int right = arr.size() - k;\n        \n        while (left < right) {\n            int mid = (left + right) / 2;\n            \n            if (x - arr[mid] > arr[mid + k] - x) {\n                left = mid + 1;\n            } else {\n                right = mid;\n            }\n        }\n        \n        return vector<int>(arr.begin() + left, arr.begin() + left + k);\n    }\n};\n"
  },
  {
    "path": "cpp/651-660/Judge Route Circle.cpp",
    "content": "class Solution {\npublic:\n    bool judgeCircle(string moves) {\n        pair<int, int> pos{0, 0};\n        for (char ch : moves) {\n            if (ch == 'U') {\n                pos.second++;\n            } else if (ch == 'D') {\n                pos.second--;\n            } else if (ch == 'L') {\n                pos.first--;\n            } else {\n                pos.first++;\n            }\n        }\n        \n        if (pos.first == 0 && pos.second == 0) return true;\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/651-660/Maximum Binary Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    TreeNode* dfs(std::vector<int>::iterator start, std::vector<int>::iterator end) {\n        if (start > end) {\n            return nullptr;\n        }\n        if (start == end) {\n            return new TreeNode(*start);\n        }\n        \n        std::vector<int>::iterator result;\n        result = std::max_element(start, end+1);\n        TreeNode* temp = new TreeNode(*result);\n        temp->left = dfs(start, result-1);\n        temp->right = dfs(result+1, end);\n        return temp;\n    }\n    \npublic:\n    TreeNode* constructMaximumBinaryTree(vector<int>& nums) {\n        if (nums.size() == 0) return nullptr;\n        return dfs(nums.begin(), --nums.end());\n    }\n};\n"
  },
  {
    "path": "cpp/651-660/Print Binary Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    int height(TreeNode* root, int h) {\n        if (root == nullptr) {\n            return 0;\n        }\n        int hl = height(root->left, h + 1);\n        int hr = height(root->right, h + 1);\n        return max(hl, hr) + 1;\n    }\n    \n    void dfs(TreeNode* root, vector<vector<string>>& result, int height, int pos, int base) {\n        if (root == nullptr) return;\n        result[height][pos] = to_string(root->val);\n        dfs(root->left, result, height+1, pos - base/2, base/2);\n        dfs(root->right, result, height+1, pos + base/2, base/2);\n    }\n    \npublic:\n    vector<vector<string>> printTree(TreeNode* root) {\n        int h = height(root, 0);\n        int cols = 1;\n        for (int i = 2; i <= h; i++) {\n            cols = cols * 2 + 1;\n        }\n        vector<vector<string>> result(h, vector<string>(cols, \"\"));\n        \n        dfs(root, result , 0, cols/2, (cols+1)/2);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/651-660/Remove 9.cpp",
    "content": "class Solution {\npublic:\n    int newInteger(int n) {\n        int result = 0;\n        \n        int base = 1;\n        \n        while (n > 0) {\n            int temp = n % 9;\n            n = (n - temp)/9;\n            result += base * temp;\n            base *= 10;\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/651-660/Split Array into Consecutive Subsequences.cpp",
    "content": "class Solution {\npublic:\n\tbool isPossible(vector<int>& nums) {\n\t\tunordered_map<int, priority_queue<int, vector<int>, std::greater<int>>> backs;\n\n\t\t// Keep track of the number of sequences with size < 3\n\t\tint need_more = 0;\n\n\t\tfor (int num : nums) {\n\t\t\tif (! backs[num - 1].empty()) {\t\n                // There exists a sequence that ends in num-1\n\t\t\t\t// Append 'num' to this sequence\n\t\t\t\t// Remove the existing sequence\n\t\t\t\t// Add a new sequence ending in 'num' with size incremented by 1 \n\t\t\t\tint count = backs[num - 1].top();\n\t\t\t\tbacks[num - 1].pop();\n\t\t\t\tbacks[num].push(++count);\n\n\t\t\t\tif (count == 3)\n\t\t\t\t\tneed_more--;\n\t\t\t} else {\t\n                // There is no sequence that ends in num-1\n\t\t\t\t// Create a new sequence with size 1 that ends with 'num'\n\t\t\t\tbacks[num].push(1);\n\t\t\t\tneed_more++;\n\t\t\t}\n\t\t}\n\t\treturn need_more == 0;\n\t}\n};\n"
  },
  {
    "path": "cpp/651-660/Two Sum IV - Input is a BST.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    bool found;\n    \n    void dfs(TreeNode* root, unordered_set<int>& myset, int k) {\n        if (root == nullptr) return;\n        if (found) return;\n        if (myset.count(k - root->val) > 0) {\n            found = true;\n            return;\n        }\n        \n        myset.insert(root->val);\n        dfs(root->left, myset, k);\n        dfs(root->right, myset, k);\n    }\n    \npublic:\n    bool findTarget(TreeNode* root, int k) {\n        found = false;\n        unordered_set<int> myset;\n        dfs(root, myset, k);\n        return found;\n    }\n};\n"
  },
  {
    "path": "cpp/661-670/Beautiful Arrangement II.cpp",
    "content": "class Solution {\npublic:\n    vector<int> constructArray(int n, int k) {\n        vector<int> result(n, 1);\n        bool flag = false;\n        int i = 2;\n        for (; i <= k; i++) {\n            flag = !flag;\n            if (flag == false) {\n                result[i-1] = result[i-3]+1;\n            } else {\n                result[i-1] = i-3 >= 0 ? result[i-3]-1 : n;\n            }\n        }\n        if (flag == false) {\n            while (i-1 < n && result[i-1] == 1) {\n                result[i-1] = result[i-2]+1;\n                i++;\n            }\n        } else {\n            while (i-1 < n && result[i-1] == 1) {\n                result[i-1] = result[i-2]-1;\n                i++;\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/661-670/Equal Tree Partition.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    set<int> myset;\n    \n    int dfs(TreeNode* root) {\n        if (!root) return 0;\n        int sum = root->val + dfs(root->left) + dfs(root->right);\n        myset.insert(sum);\n        return sum;\n    }\npublic:\n    bool checkEqualTree(TreeNode* root) {\n        if (!root) return false;\n        int sum1 = dfs(root->left);\n        int sum2 = dfs(root->right);\n        int sum = root->val + sum1 + sum2;\n        if (sum % 2 != 0) return false;\n        int target = sum / 2;\n        if (myset.count(target) > 0) return true;\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/661-670/Image Smoother.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> imageSmoother(vector<vector<int>>& M) {\n        int m = M.size();\n        int n = M[0].size();\n        vector<vector<int>> result(m, vector<int>(n, 0));\n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                int gray = 0;\n                int total = 0;\n                for (int k1 = -1; k1 <= 1; k1++) {\n                    for (int k2 = -1; k2 <= 1; k2++) {\n                        int newi = i + k1;\n                        int newj = j + k2;\n                        if (newi < 0 || newj < 0 || newi >= m || newj >= n) continue;\n                        total++;\n                        gray += M[newi][newj];\n                    }\n                }\n                result[i][j] = gray / total;\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/661-670/Kth largest Number in Multiplication Table.cpp",
    "content": "class Solution {\n    bool validate(int p, int m, int n, int k){\n        int cnt = 0;\n        for (int i = 0; i < n; i++) {\n            if (m * (i + 1) <= p) cnt += m;\n            else cnt += p / (i+1);\n        }\n        return cnt >= k;\n    }\n    \npublic:\n    int findKthNumber(int m, int n, int k) {\n        int left = 0;\n        int right = n * m +1;\n        while(right - left > 1){\n            int mid = (left + right) >> 1;\n            if(validate(mid, m, n, k)) {\n                right = mid;\n            }\n            else left = mid;\n        }\n        return right;\n    }\n};\n"
  },
  {
    "path": "cpp/661-670/Maximum Swap.cpp",
    "content": "class Solution {\npublic:\n    int maximumSwap(int num) {\n        vector<int> records(10, -1);\n        string numStr = to_string(num);\n        for (int i = 0; i < numStr.size(); i++) {\n            records[numStr[i] - '0'] = i;\n        }\n        \n        for (int i = 0; i < numStr.size(); i++) {\n            for (int j = 9; j >= 0; j--) {\n                if (records[j] > i && j > (numStr[i] - '0')) {\n                    swap(numStr[i], numStr[records[j]]);\n                    return stoi(numStr);\n                }\n            }\n        }\n        return num;\n    }\n};\n"
  },
  {
    "path": "cpp/661-670/Maximum Width of Binary Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int widthOfBinaryTree(TreeNode* root) {\n        if (!root) return 0;\n        int result = 0;\n        vector<pair<TreeNode*, int>> trees;\n        trees.push_back({root, 0});\n        while (!trees.empty()) {\n            auto left = trees.front();\n            auto right = trees.back();\n            result = max(result, right.second - left.second + 1);\n            vector<pair<TreeNode*, int>> temp;\n            for (const auto& ele : trees) {\n                TreeNode *node = ele.first;\n                int v = ele.second;\n                if (node->left) {\n                    temp.push_back({node->left, 2*v});\n                } \n                if (node->right) {\n                    temp.push_back({node->right, 2*v+1});\n                }\n            }\n            trees = temp;\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/661-670/Non-decreasing Array.cpp",
    "content": "class Solution {\npublic:\n    bool checkPossibility(vector<int>& nums) {\n        int n = nums.size();\n        int cnt = 0;\n        for (int i = 0; i < n - 1; i++) {\n            if(nums[i] > nums[i+1]) {\n                ++cnt;\n                // 2 3 3 2 4 => 2 3 3 3 4\n                // 4 2 3 => 2 2 3\n                // 4 2 1 => 4 4 1\n                // 3 4 2 3 => 3 4 4 3\n                if (i > 0 && nums[i+1] < nums[i-1]) {\n                    nums[i+1] = nums[i];\n                }\n                else nums[i] = nums[i+1];\n            }\n        }\n        return cnt <= 1;\n    }\n};\n"
  },
  {
    "path": "cpp/661-670/Path Sum IV.cpp",
    "content": "class Solution {\n    int getLeftChild(int key) {\n        int d = key/10;\n        int p = key%10;\n        return 10*(d+1) + (2*p-1);\n    }\npublic:\n    int pathSum(vector<int>& nums) {\n        map<int, int> mymap;\n        for (int num : nums) {\n            int key = num/10;\n            int value = num%10;\n            mymap[key] = value;\n        }\n        \n        int result = 0;\n        for (auto it : mymap) {\n            int key = it.first;\n            if ( mymap.count(getLeftChild(key)) == 0 && mymap.count(getLeftChild(key)+1) == 0) {\n                // this is leaf\n                while (mymap.count(key) > 0) {\n                    result += mymap[key];\n                    int d = key/10;\n                    int p = key%10;\n                    key = 10*(d-1)+(p+1)/2;\n                }\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/661-670/Strange Printer.cpp",
    "content": "class Solution {\npublic:\n    int strangePrinter(string s) {\n        if (s.length() == 1) return 1;\n        if (s.empty()) return 0;\n        string str = \"\";\n        str += s[0];\n        for (int i = 1; i < s.length(); i++) {\n            if (s[i] != str.back()) {\n                str += s[i];\n            }\n        }\n        \n        int n = str.length();\n        vector<vector<int>> dp(n, vector<int>(n, 1));\n        \n        for (int step = 1; step < n; step++) {\n            for (int i = 0; i < n - step; i ++) {\n                int j = i + step;\n                int temp = INT_MAX;\n                for (int k = i; k < j; k++) {\n                    int v = dp[i][k] + dp[k+1][j];\n                    if (str[k] == str[j]) v--;\n                    temp = min(temp, v);\n                }\n                dp[i][j] = temp;\n            }\n        }\n        \n        return dp[0][n-1];\n    }\n};\n"
  },
  {
    "path": "cpp/661-670/Trim a Binary Search Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode* trimBST(TreeNode* root, int L, int R) {\n        if (!root) return nullptr;\n        if (root->val < L) {\n            return trimBST(root->right, L, R);\n        } else if (root->val > R) {\n            return trimBST(root->left, L, R);\n        } else {\n            root->left = trimBST(root->left, L, R);\n            root->right = trimBST(root->right, L, R);\n            return root;\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/671-680/24 Game.cpp",
    "content": "class Solution {\n    \n    vector<double> op(double d1, double d2) {\n        vector<double> result;\n        result.push_back(d1 + d2);\n        result.push_back(d1 - d2);\n        result.push_back(d2 - d1);\n        result.push_back(d1 * d2);\n        if (fabs(d2) > 1e-5) result.push_back(d1 / d2);\n        if (fabs(d1) > 1e-5) result.push_back(d2 / d1);\n        return result;\n    }\n    \n    bool almost(double num) {\n        return fabs(num - 24.0) < 1e-5;\n    }\n    \n    bool dfs(vector<double> nums) {\n        if (nums.size() == 2) {\n            vector<double> result = op(nums[0], nums[1]);\n            for (double e : result) if (almost(e)) return true;\n            return false;\n        }\n        for (int i = 0; i < nums.size(); i++) {\n            for (int j = i+1; j < nums.size(); j++) {\n                vector<double> opResult = op(nums[i], nums[j]);\n                for (double e : opResult) {\n                    vector<double> temp;\n                    for (int k = 0; k < nums.size(); k++) {\n                        if (k != i && k != j) {\n                            temp.push_back(nums[k]);\n                        }\n                    }\n                    temp.push_back(e);\n                    bool r = dfs(temp);\n                    if (r) return true;\n                }\n            }\n        }\n        return false;\n    } \n    \npublic:\n    bool judgePoint24(vector<int>& nums) {\n        vector<double> temp;\n        for (int e : nums) temp.push_back(e * 1.0);\n        return dfs (temp);\n    }\n};\n"
  },
  {
    "path": "cpp/671-680/Cut Off Trees for Golf Event.cpp",
    "content": "class Solution {\npublic:\n    int cutOffTree(vector<vector<int>>& forest) {\n        if (forest.empty() || forest[0].empty()) return 0;\n        int m = forest.size(), n = forest[0].size();\n        vector<vector<int>> trees;\n        // get all the tree positions and sort based on height\n        // trees[i][0] is height. The default comparison of vector compare first element before other elements.\n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                if (forest[i][j] > 1) trees.push_back({forest[i][j], i, j});\n            }\n        }\n        sort(trees.begin(), trees.end());\n        int ans = 0;\n        // accumulate all the paths\n        for (int i = 0, cur_row = 0, cur_col = 0; i < trees.size(); i++) {\n            int step = next_step(forest, cur_row, cur_col, trees[i][1], trees[i][2]);\n            // if next tree cannot be reached, step = -1;\n            if (step == -1) return -1;\n            ans += step;\n            cur_row = trees[i][1];\n            cur_col = trees[i][2];\n        }\n        return ans;\n    }\nprivate:\n    // BFS to find shortest path to next tree; if cannot reach next tree, return -1\n    int next_step(vector<vector<int>>& forest, int sr, int sc, int er, int ec) {\n        if (sr == er && sc == ec) return 0;\n        int m = forest.size(), n = forest[0].size();\n        queue<pair<int, int>> myq;\n        myq.push({sr, sc}); \n        vector<vector<int>> visited(m, vector<int>(n, 0));\n        visited[sr][sc] = 1;\n        int step = 0;\n        vector<int> dir = {-1, 0, 1, 0, -1};\n        while (!myq.empty()) {\n            step++;\n            int sz = myq.size();\n            for (int i = 0; i < sz; i++) {\n                int row = myq.front().first, col = myq.front().second;\n                myq.pop();\n                for (int i = 0; i < 4; i++) {\n                    int r = row + dir[i], c = col + dir[i+1];\n                    if (r < 0 || r >= m || c < 0 || c >= n || visited[r][c] == 1 || forest[r][c] == 0) continue;\n                    if (r == er && c == ec) return step;\n                    visited[r][c] = 1;\n                    myq.push({r, c});\n                }\n            }\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/671-680/Implement Magic Dictionary.cpp",
    "content": "struct TrieNode {\n    TrieNode *nodes[26];\n    bool word;\n    // Initialize your data structure here.\n    TrieNode(): word(false) {\n        memset(nodes, 0, sizeof(nodes));\n    }\n};\n\nclass Trie {\n    \npublic:\n    Trie() {\n        root = new TrieNode();\n    }\n    \n    // Inserts a word into the trie.\n    void insert(const string& s) {\n        TrieNode *tmp = root;\n        for(char ch : s) {\n            int index = ch - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                tmp->nodes[index] = new TrieNode();\n            }\n            tmp = tmp->nodes[index];\n        }\n        tmp->word = true;\n    }\n    \n    // Returns if the word is in the trie.\n    bool search(TrieNode* tmp, const string& key, int strIndex, int count) {\n        if (tmp == nullptr) return false;\n        if (count > 1) return false;\n        if (strIndex == key.length()) {\n            return count == 1 && tmp->word;\n        }\n        char ch = key[strIndex];\n        int index = ch - 'a';\n        for (int i = 0; i < 26; i++) {\n            int added = index == i ? 0 : 1;\n            if (search(tmp->nodes[i], key, strIndex+1, count+added)) return true;\n        }\n        return false;\n    }\n    \n    TrieNode* root;\n};\n\nclass MagicDictionary {\n    Trie trie;\npublic:\n    /** Initialize your data structure here. */\n    MagicDictionary() {\n    }\n    \n    /** Build a dictionary through a list of words */\n    void buildDict(vector<string> dict) {\n        for (const string& word : dict) trie.insert(word);\n    }\n    \n    /** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */\n    bool search(string word) {\n        return trie.search(trie.root, word, 0, 0);\n    }\n};\n\n/**\n * Your MagicDictionary object will be instantiated and called as such:\n * MagicDictionary obj = new MagicDictionary();\n * obj.buildDict(dict);\n * bool param_2 = obj.search(word);\n */\n"
  },
  {
    "path": "cpp/671-680/Longest Continuous Increasing Subsequence.cpp",
    "content": "class Solution {\npublic:\n    int findLengthOfLCIS(vector<int>& nums) {\n        int res = 0, cnt = 0;\n        for (int i = 0; i < nums.size(); i++){\n            if (i == 0 || nums[i-1] < nums[i]) {\n                res = max(res, ++cnt);\n            } else {\n                cnt = 1;\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/671-680/Map Sum Pairs.cpp",
    "content": "struct TrieNode {\n    TrieNode *nodes[26];\n    bool word;\n    int value;\n    // Initialize your data structure here.\n    TrieNode(): word(false) {\n        memset(nodes, 0, sizeof(nodes));\n    }\n};\n\nclass Trie {\n    \n    int dfs(TrieNode *tmp) {\n        if (tmp == nullptr) return 0;\n        int v = 0;\n        if (tmp->word) v += tmp->value;\n        for (int i = 0; i < 26; i++) v += dfs(tmp->nodes[i]);\n        return v;\n    }\n    \npublic:\n    Trie() {\n        root = new TrieNode();\n    }\n    \n    // Inserts a word into the trie.\n    void insert(const string& s, int val) {\n        TrieNode *tmp = root;\n        for(char ch : s) {\n            int index = ch - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                tmp->nodes[index] = new TrieNode();\n            }\n            tmp = tmp->nodes[index];\n        }\n        tmp->word = true;\n        tmp->value = val;\n    }\n    \n    int startsWith(const string& prefix) {\n        TrieNode *tmp = root;\n        for(char ch : prefix) {\n            int index = ch - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                return 0;\n            }\n            tmp = tmp->nodes[index];\n        }\n        return dfs(tmp);\n    }\n    \nprivate:\n    TrieNode* root;\n};\n\nclass MapSum {\n    Trie trie;\npublic:\n    /** Initialize your data structure here. */\n    MapSum() {\n    }\n    \n    void insert(string key, int val) {\n        trie.insert(key, val);\n    }\n    \n    int sum(string prefix) {\n        return trie.startsWith(prefix);\n    }\n};\n\n/**\n * Your MapSum object will be instantiated and called as such:\n * MapSum obj = new MapSum();\n * obj.insert(key,val);\n * int param_2 = obj.sum(prefix);\n */\n"
  },
  {
    "path": "cpp/671-680/Number of Longest Increasing Subsequence.cpp",
    "content": "class Solution {\npublic:\n    int findNumberOfLIS(vector<int>& nums) {\n        if(nums.empty()) return 0;\n        int n = nums.size(), maxCnt=0, maxLen=0;\n        vector<int> dp(n,1), cnt(n,1);\n        for(int i=0; i<n; ++i){\n            for(int j =0; j<i; ++j)\n                if (nums[i] > nums[j]) {\n                    if(dp[j] + 1 == dp[i]) \n                        cnt[i] += cnt[j];\n                    else if(dp[j] + 1 > dp[i]){\n                        dp[i] =  dp[j] + 1;\n                        cnt[i] = cnt[j];\n                    }                   \n                }           \n            maxLen = max(maxLen, dp[i]);\n\t    }\n        for(int i=0; i<n; ++i)  {\n            if(dp[i] == maxLen)  \n                maxCnt += cnt[i];\n        }\n        \n        return maxCnt;     \n    }\n};\n"
  },
  {
    "path": "cpp/671-680/Second Minimum Node In a Binary Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int findSecondMinimumValue(TreeNode* root) {\n        if (!root) return -1;\n        return minval(root, root->val);\n    }\nprivate:\n    int minval(TreeNode* p, int first) {\n        if (p == nullptr) return -1;\n        if (p->val != first) return p->val;\n        int left = minval(p->left, first), right = minval(p->right, first);\n        if (left == -1) return right;\n        if (right == -1) return left;\n        return min(left, right);\n    }\n};\n"
  },
  {
    "path": "cpp/671-680/Valid Palindrome II.cpp",
    "content": "class Solution {\npublic:\n    bool validPalindrome(string s) {\n        for (int i = 0, j = s.size() - 1; i < j; i++, j--) {\n            if (s[i] != s[j]) {\n                int i1 = i, j1 = j - 1, i2 = i + 1, j2 = j;\n                while (i1 < j1 && s[i1] == s[j1]) {\n                    i1++;\n                    j1--;\n                };\n                if (i1 >= j1) {\n                    return true;\n                }\n                while (i2 < j2 && s[i2] == s[j2]) {\n                    i2++;\n                    j2--;\n                };\n                if (i2 >= j2) {\n                    return true;\n                }\n                \n                return false;\n            }\n        }\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/671-680/Valid Parenthesis String.cpp",
    "content": "class Solution {\npublic:\n    bool checkValidString(string s) {\n        int minLeft = 0, maxLeft = 0;\n        \n        for (char ch : s) {\n            if (ch == '(') {\n                minLeft++;\n                maxLeft++;\n            } else if (ch == ')') {\n                minLeft--;\n                maxLeft--;\n            } else {\n                minLeft--;\n                maxLeft++;\n            }\n            \n            if (maxLeft < 0) {\n                return false;\n            }\n            \n            minLeft = max(0, minLeft);\n        }\n        \n        return minLeft == 0;\n    }\n};\n"
  },
  {
    "path": "cpp/681-690/Baseball Game.cpp",
    "content": "class Solution {\npublic:\n    int calPoints(vector<string>& ops) {\n        int sum = 0, score = 0;\n        vector<int> rounds;\n        for (string op : ops) {\n            if (op == \"C\") {\n                sum -= rounds.back();\n                rounds.pop_back();\n                continue;\n            } else if (op == \"D\") {\n                sum += score = rounds.back() * 2;\n            } else if (op == \"+\") {\n                sum += score = rounds[rounds.size() - 1] + rounds[rounds.size() - 2];\n            } else {\n                sum += score = stoi(op);\n            }\n            rounds.push_back(score);\n        }\n        return sum;\n    }\n};\n"
  },
  {
    "path": "cpp/681-690/Employee Importance.cpp",
    "content": "/*\n// Employee info\nclass Employee {\npublic:\n    // It's the unique ID of each node.\n    // unique id of this employee\n    int id;\n    // the importance value of this employee\n    int importance;\n    // the id of direct subordinates\n    vector<int> subordinates;\n};\n*/\nclass Solution {\n    \n    int dfs(const map<int, Employee*>& mymap, int id) {\n        int sum = mymap.at(id)->importance;\n        for (int sub_id : mymap.at(id)->subordinates) {\n             sum += dfs(mymap, sub_id);\n        }\n        return sum;\n    }\n    \npublic:\n    int getImportance(vector<Employee*> employees, int id) {\n        map<int, Employee*> mymap;\n        for (Employee* employee : employees) {\n            mymap[employee->id] = employee;\n        }\n        return dfs(mymap, id);\n    }\n};\n"
  },
  {
    "path": "cpp/681-690/K Empty Slots.cpp",
    "content": "class Solution {\npublic:\n    int kEmptySlots(vector<int>& flowers, int k) {\n        int n = flowers.size();\n        vector<int> days(n, 0);\n        \n        for (int i = 0; i < n; i++) {\n            days[flowers[i]-1] = i;\n        }\n        \n        int ans = INT_MAX;\n        int left = 0;\n        while (left + k + 1 < n) {\n            int right = left + k + 1;\n            int startDay = days[left];\n            int endDay = days[right];\n            bool invalid = false;\n            for (int i = left + 1; i < right; i++) {\n                if (days[i] > startDay && days[i] > endDay) continue;\n                invalid = true;\n                left = i;\n                break;\n            }\n            if (!invalid) {\n                ans = min(ans, 1 + max(startDay, endDay));\n                left = right;\n            }\n        }\n        \n        return ans == INT_MAX ? -1 : ans;\n    }\n};\n"
  },
  {
    "path": "cpp/681-690/Knight Probability in Chessboard.cpp",
    "content": "class Solution {\npublic:\n    double knightProbability(int N, int K, int r, int c) {\n        vector<vector<vector<double>>> dp(K+1, vector<vector<double>>(N, vector<double>(N, -1.0)));\n        return helper(dp, N, K, r, c)/pow(8, K);\n    }\nprivate:\n    double helper(vector<vector<vector<double>>>& dp, int N, int k, int r, int c) {\n        // if out of board, return 0.0\n        if (r < 0 || r >= N || c < 0 || c >= N) return 0.0;\n        // when k = 0, no more move, so it's 100% safe\n        if (k == 0) return 1.0;\n        if (dp[k][r][c] > -0.000001) return dp[k][r][c];\n        dp[k][r][c] = 0.0;\n        for (int i = -2; i <= 2; i++) {\n            if (i == 0) continue;\n            dp[k][r][c] += helper(dp, N, k-1, r+i, c+3-abs(i)) + helper(dp, N, k-1, r+i, c-(3-abs(i)));\n        }      \n        return dp[k][r][c];\n    }\n};\n"
  },
  {
    "path": "cpp/681-690/Longest Univalue Path.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    int res;\n    \n    int dfs(TreeNode* root) {\n        if (root == nullptr) return 0;\n        int left = root->left ? dfs(root->left) : 0;\n        int right = root->right ? dfs(root->right) : 0;\n        int temp = 0;\n        int returnValue = 0;\n        if (root->left && root->left->val == root->val) {\n            temp += left;\n            returnValue = max(returnValue, left);\n        }\n        if (root->right && root->right->val == root->val) {\n            temp += right;\n            returnValue = max(returnValue, right);\n        }\n        res = max(res, temp);\n        return returnValue + 1;\n    }\n    \npublic:\n    int longestUnivaluePath(TreeNode* root) {\n        dfs(root);\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/681-690/Maximum Sum of 3 Non-Overlapping Subarrays.cpp",
    "content": "class Solution {\npublic:\n    vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {\n        int n = nums.size(), maxsum = 0;\n        vector<int> sum = {0}, posLeft(n, 0), posRight(n, n-k), ans(3, 0);\n        for (int i : nums) {\n            sum.push_back(sum.back() + i);\n        }\n\n        for (int i = k, tot = sum[k]-sum[0]; i < n; i++) {\n            if (sum[i+1]-sum[i+1-k] > tot) {\n                posLeft[i] = i+1-k;\n                tot = sum[i+1]-sum[i+1-k];\n            } else {\n                posLeft[i] = posLeft[i-1];\n            }\n        }\n\n        for (int i = n-k-1, tot = sum[n] - sum[n-k]; i >= 0; i--) {\n            // >= for lexicographical ordering\n            if (sum[i+k]-sum[i] >= tot) {\n                posRight[i] = i;\n                tot = sum[i+k]-sum[i];\n            } else {\n                posRight[i] = posRight[i+1];\n            }\n        }\n        // test all possible middle interval\n        for (int i = k; i <= n-2*k; i++) {\n            int l = posLeft[i-1];\n            int r = posRight[i+k];\n            int tot = (sum[i+k]-sum[i]) + (sum[l+k]-sum[l]) + (sum[r+k]-sum[r]);\n            if (tot > maxsum) {\n                maxsum = tot;\n                ans = {l, i, r};\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/681-690/Next Closest Time.cpp",
    "content": "class Solution {\npublic:\n    string nextClosestTime(string time) {\n        int cur = 60 * stoi(time.substr(0, 2)) + stoi(time.substr(3));\n        set<int> allowed;\n        for (char c : time) if (c != ':') allowed.insert(c - '0');\n\n        while (true) {\n            bool found = true;\n            cur = (cur + 1) % (24 * 60);\n            int digits[4] = {cur / 60 / 10, cur / 60 % 10, cur % 60 / 10, cur % 60 % 10};\n            for (int d: digits) if (allowed.count(d) == 0) {\n                found = false;\n                break;\n            };\n            if (!found) continue;\n            string result;\n            if (cur / 60 < 10) {\n                result += \"0\";\n            }\n            result += to_string(cur / 60);\n            result += \":\";\n            if (cur % 60 < 10) {\n                result += \"0\";\n            }\n            result += to_string(cur % 60);\n            return result;\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/681-690/Redundant Connection II.cpp",
    "content": "class UF {\n    \nprivate:\n    vector<int> parent;\n    vector<int> rank;\n    int count;\n    int N;\n    \npublic:\n    \n    UF(int N) : parent(N), rank(N, 0), N(N), count(N) {\n        for (int i = 0; i < N; i++) {\n            parent[i] = i;\n        }\n    }\n    \n    int find(int p) {\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];    // path compression by halving\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    void Union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rootP == rootQ) return;\n        \n        // make root of smaller rank point to root of larger rank\n        if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;\n        else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;\n        else {\n            parent[rootQ] = rootP;\n            rank[rootP]++;\n        }\n        count--;\n    }\n};\n\nclass Solution {\npublic:\n    vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {\n        int n = edges.size();\n        UF uf(n+1);\n        map<int, int> mymap;\n        \n        int c(-1), canA, canB;\n        \n        for (const auto& edge : edges) {\n            int u = edge[0];\n            int v = edge[1];\n            // two parent, must incorrect\n            if (mymap.find(v) != mymap.end()) {\n                c = v;\n                canA = mymap[v];\n                canB = u;\n            }\n            mymap[v] = u;\n        }\n        \n        for (const auto& edge : edges) {\n            int u = edge[0];\n            int v = edge[1];\n            if (u == canB && v == c) continue;\n            if (uf.connected(u, v)) {\n                if (c == -1) {\n                    // Every node has only one parent\n                    // The edge causes the circle must be the bad one\n                    return edge;\n                }\n                return vector<int>{canA, c};\n            }\n            uf.Union(u, v);\n        }\n        \n        return vector<int>{canB, c};\n    }\n};\n"
  },
  {
    "path": "cpp/681-690/Redundant Connection.cpp",
    "content": "class UF {\n    \nprivate:\n    vector<int> parent;\n    vector<int> rank;\n    int count;\n    int N;\n    \npublic:\n    \n    UF(int N) : parent(N), rank(N, 0), N(N), count(N) {\n        for (int i = 0; i < N; i++) {\n            parent[i] = i;\n        }\n    }\n    \n    int find(int p) {\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];    // path compression by halving\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    void Union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rootP == rootQ) return;\n        \n        // make root of smaller rank point to root of larger rank\n        if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;\n        else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;\n        else {\n            parent[rootQ] = rootP;\n            rank[rootP]++;\n        }\n        count--;\n    }\n};\n\nclass Solution {\npublic:\n    vector<int> findRedundantConnection(vector<vector<int>>& edges) {\n        int n = edges.size();\n        UF uf(n+1);\n        \n        for (const auto& edge : edges) {\n            int u = edge[0];\n            int v = edge[1];\n            if (uf.connected(u, v)) return edge;\n            uf.Union(u, v);\n        }\n        \n        return edges.back();\n    }\n};\n"
  },
  {
    "path": "cpp/681-690/Repeated String Match.cpp",
    "content": "class Solution {\npublic:\n    int repeatedStringMatch(string A, string B) {\n        int l = B.length() / A.length();\n        string temp;\n        for (int i = 0; i < l; i++) temp += A;\n        if (temp.find(B) != string::npos) {\n            return l;\n        }\n        temp += A;\n        if (temp.find(B) != string::npos) {\n            return l+1;\n        }\n        temp += A;\n        if (temp.find(B) != string::npos) {\n            return l+2;\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/691-700/Binary Number with Alternating Bits.cpp",
    "content": "class Solution {\npublic:\n    bool hasAlternatingBits(int n) {\n        while (n > 0) {\n            if (n%2 == ((n>>1)%2)) {\n                return false;\n            }\n            n=n>>1;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/691-700/Count Binary Substrings.cpp",
    "content": "class Solution {\npublic:\n    int countBinarySubstrings(string s) {\n        int result = 0;\n        char current = s[0];\n        int previousCount = 0;\n        int count = 1;\n        \n        for (int i = 1; i < s.length(); i++) {\n            if (s[i] == current) {\n                count++;\n            } else {\n                current = s[i];\n                previousCount = count;\n                count = 1;\n            }\n            \n            if (count <= previousCount) {\n                result++;\n            }\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/691-700/Degree of an Array.cpp",
    "content": "class Solution {\npublic:\n    int findShortestSubArray(vector<int>& nums) {\n        if (nums.size() < 2) return nums.size();\n        map<int, int> startIndex, count;\n        int len = nums.size(), fre = 0;\n        for (int i = 0; i < nums.size() ;i++) {\n            if (startIndex.count(nums[i]) == 0) startIndex[nums[i]] = i;\n            count[nums[i]]++;\n            if (count[nums[i]] == fre) {\n                len = min(i - startIndex[nums[i]] + 1, len);\n            }\n            if (count[nums[i]] > fre) {\n                len = i - startIndex[nums[i]] + 1;\n                fre = count[nums[i]];\n            }\n        }\n        return len;\n    }\n};\n"
  },
  {
    "path": "cpp/691-700/Falling Squares.cpp",
    "content": "class Solution {\npublic:\n    vector<int> fallingSquares(vector<pair<int, int>>& positions) {\n        vector<int> ans;\n        vector<tuple<int, int, int>> points; // x, y, sidelength\n        int current = 0;\n        \n        for (const pair<int, int>& position : positions) {\n            int top = position.second;\n            \n            // Find all previous squares that are in current width range\n            for (const auto& point : points) {\n                int x = get<0>(point);\n                int y = get<1>(point);\n                int length = get<2>(point);\n                    \n                if (x + length <= position.first) continue;\n                if (position.first + position.second <= x) continue;\n                top = max(top, y + position.second);\n            }\n\n            points.emplace_back(make_tuple(position.first, top, position.second));\n            current = max(current, top);\n            ans.push_back(current);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/691-700/Max Area of Island.cpp",
    "content": "class Solution {\npublic:\n    int maxAreaOfIsland(vector<vector<int>>& grid) {\n        int max_area = 0;\n        for(int i = 0; i < grid.size(); i++)\n            for(int j = 0; j < grid[0].size(); j++)\n                if(grid[i][j] == 1)max_area = max(max_area, AreaOfIsland(grid, i, j));\n        return max_area;\n    }\n    \n    int AreaOfIsland(vector<vector<int>>& grid, int i, int j){\n        if( i >= 0 && i < grid.size() && j >= 0 && j < grid[0].size() && grid[i][j] == 1){\n            grid[i][j] = 0;\n            return 1 + AreaOfIsland(grid, i+1, j) + AreaOfIsland(grid, i-1, j) + AreaOfIsland(grid, i, j-1) + AreaOfIsland(grid, i, j+1);\n        }\n        return 0;\n    }\n};\n"
  },
  {
    "path": "cpp/691-700/Number of Distinct Islands.cpp",
    "content": "class Solution {\npublic:\n    int numDistinctIslands(vector<vector<int>>& grid) {\n        int m = grid.size(), n = grid[0].size();\n        set<vector<int>> islands;\n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                vector<int> island;\n                if (dfs(i, j, i, j, grid, m, n, island))\n                    islands.insert(island);\n            }\n        }\n        return islands.size();\n    }\n\nprivate:\n    int delta[4][2] = { 0, 1, 1, 0, 0, -1, -1, 0};\n\n    bool dfs(int i0, int j0, int i, int j, vector<vector<int>>& grid, int m, int n, vector<int>& island) {\n        if (i < 0 || m <= i || j < 0 || n <= j || grid[i][j] <= 0) return false;\n        island.push_back(i - i0);\n        island.push_back(j - j0);\n        grid[i][j] = -1;\n        for (int d = 0; d < 4; d++) {\n            dfs(i0, j0, i + delta[d][0], j + delta[d][1], grid, m, n, island);\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/691-700/Partition to K Equal Sum Subsets.cpp",
    "content": "class Solution {\n\n    bool isKPartitionPossibleRec(const vector<int>& nums, int subsetSum, bool taken[], int target, int K, int limitIdx) {\n        if (subsetSum == target) {\n            if (K == 2) return true;\n            return isKPartitionPossibleRec(nums, 0, taken, target, K - 1, 0);\n        }\n\n        for (int i = limitIdx; i < nums.size(); i++) {\n            if (taken[i]) continue;\n            int tmp = subsetSum + nums[i];\n\n            if (tmp <= target) {\n                taken[i] = true;\n                bool nxt = isKPartitionPossibleRec(nums, subsetSum + nums[i], taken, target, K, i + 1);\n                taken[i] = false;\n                if (nxt) return true;\n            }\n        }\n        return false;\n    }\n    \npublic:\n    bool canPartitionKSubsets(vector<int>& nums, int k) {\n        int N = nums.size();\n        if (k == 1) return true;\n        if (N < k) return false;\n\n        int sum = accumulate(nums.begin(), nums.end(), 0);\n        if (sum % k != 0) return false;\n\n        int subset = sum / k;\n        bool taken[N];\n        fill(taken, taken + N, false);\n        taken[0] = true;\n\n        //  call recursive method to check K-substitution condition\n        return isKPartitionPossibleRec(nums, nums[0], taken, subset, k, 0);\n    }\n};\n"
  },
  {
    "path": "cpp/691-700/Top K Frequent Words.cpp",
    "content": "class Solution {\npublic:\n    vector<string> topKFrequent(vector<string>& words, int k) {\n        unordered_map<string, int> freq;\n        for(auto w : words){\n            freq[w]++;\n        }\n        \n        auto comp = [&](const pair<string,int>& a, const pair<string,int>& b) {\n            return a.second > b.second || (a.second == b.second && a.first < b.first);\n        };\n        typedef priority_queue< pair<string,int>, vector<pair<string,int>>, decltype(comp) > my_priority_queue_t;\n        my_priority_queue_t  pq(comp);\n        \n        for(auto w : freq ){\n            pq.emplace(w.first, w.second);\n            if(pq.size()>k) pq.pop();\n        }\n        \n        vector<string> output;\n        while(!pq.empty()){\n            output.insert(output.begin(), pq.top().first);\n            pq.pop();\n        }\n        return output;\n    }\n};\n"
  },
  {
    "path": "cpp/701-710/Insert into a Binary Search Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode* insertIntoBST(TreeNode* root, int val) {\n        if (root == nullptr) {\n            return new TreeNode(val);\n        }\n        \n        if (root->val > val) {\n            root->left = insertIntoBST(root->left, val);\n        } else {\n            root->right = insertIntoBST(root->right, val);\n        }\n        \n        return root;\n    }\n};\n\n\n\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode* insertIntoBST(TreeNode* root, int val) {\n        if (root == nullptr) {\n            return new TreeNode(val);\n        }\n        \n        TreeNode* parent = nullptr;\n        TreeNode* cur = root;\n        while (cur != nullptr) {\n            parent = cur;\n            if (cur->val > val) {\n                cur = cur->left;\n                if (cur == nullptr) {\n                    parent->left = new TreeNode(val);\n                }\n            } else {\n                cur = cur->right;\n                if (cur == nullptr) {\n                    parent->right = new TreeNode(val);\n                }\n            }\n        }\n        \n        return root;\n    }\n};\n"
  },
  {
    "path": "cpp/701-710/Random Pick with Blacklist.cpp",
    "content": "// Solution 1: Binary Search. O(log)\nclass Solution {\n    vector<int> v;\n    std::random_device rd;\n    int mod;\npublic:\n    Solution(int N, vector<int> blacklist) {\n        mod = N - blacklist.size();\n        sort(blacklist.begin(), blacklist.end());\n        v = blacklist;\n        v.push_back(N);\n        for (int i = 0; i < v.size(); i++) v[i] -= i;\n    }\n    \n    int pick() {\n        int index = rd() % mod;\n        auto it = upper_bound(v.begin(), v.end(), index);\n        return index + (it - v.begin());\n    }\n};\n\n// Solution 2: hash_map; O(1)\nclass Solution {\n    random_device rd;\n    unordered_map<int, int> updated_index;\n    int mod;\npublic:\n    Solution(int N, vector<int>& blacklist) {\n        mod = N - blacklist.size();\n        set<int> blacklist_set(blacklist.begin(), blacklist.end());\n        \n        int swap_num = N - 1;\n        for (int blacklist_element : blacklist_set) {\n            if (blacklist_element >= mod) break;\n            while (blacklist_set.count(swap_num) > 0) {\n                swap_num--;\n            }\n            updated_index[blacklist_element] = swap_num;\n            swap_num--;\n        }\n    }\n    \n    int pick() {\n        int index = rd() % mod;\n        if (updated_index.count(index) > 0) {\n            return updated_index[index];\n        }\n        return index;\n    }\n};\n"
  },
  {
    "path": "cpp/701-710/To Lower Case.cpp",
    "content": "class Solution {\npublic:\n    string toLowerCase(string str) {\n        int d = 'A' - 'a';\n        for (char& ch : str) {\n            if (ch >= 'A' && ch <= 'Z') {\n                ch -= d;\n            }\n        }\n        return str;\n    }\n};\n"
  },
  {
    "path": "cpp/711-720/1-bit and 2-bit Characters.cpp",
    "content": "class Solution {\npublic:\n    bool isOneBitCharacter(vector<int>& bits) {\n        int i = 0;\n        while (i < bits.size()) {\n            if (i == bits.size() - 1) return true;\n            if (bits[i] == 1) {\n                i = i + 2;\n            } else {\n                i++;\n            }\n        }\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/711-720/Best Time to Buy and Sell Stock with Transaction Fee.cpp",
    "content": "class Solution {\npublic:\n    int maxProfit(vector<int>& prices, int fee) {\n        int n = prices.size();\n        int holdStock = -prices[0];\n        int noStock = 0;\n\n        for (int e : prices) {\n            int tmpHoldStock = holdStock;\n            holdStock = max(holdStock, noStock - e);\n            noStock = max(noStock, tmpHoldStock + e - fee);\n        }\n        \n        return noStock;\n    }\n};\n"
  },
  {
    "path": "cpp/711-720/Find K-th Smallest Pair Distance.cpp",
    "content": "class Solution {\npublic:\n    int smallestDistancePair(vector<int>& nums, int k) {\n        if (nums.empty() || k <= 0) return INT_MIN;\n        sort (nums.begin(), nums.end());\n        int n = nums.size(), low = 0, high = nums[n-1] - nums[0];\n        while (low < high) {\n            int mid = low + (high-low) / 2;\n            int left = 0;\n            int right = 1;\n            int cnt = 0;\n            while (right < n) {\n                if (nums[right] - nums[left] > mid) {\n                    ++left;\n                } else {\n                    cnt += (right-left);\n                    ++right;\n                }\n            }\n            if (cnt < k) low = mid+1;\n            else high = mid;\n        }\n        return low;\n    }\n};\n"
  },
  {
    "path": "cpp/711-720/Longest Word in Dictionary.cpp",
    "content": "class Solution {\npublic:\n    string longestWord(vector<string>& words) {\n        sort(words.begin(), words.end());\n        unordered_set<string> built;\n        string res;\n        for (string w : words) {\n            if (w.size() == 1 || built.count(w.substr(0, w.size() - 1))) {\n                res = w.size() > res.size() ? w : res;\n                built.insert(w);\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/711-720/Max Stack.cpp",
    "content": "class MaxStack {\n    stack<int> s1;\n    stack<int> s2;\npublic:\n    /** initialize your data structure here. */\n    MaxStack() {\n    }\n    \n    void push(int x) {\n        s1.push(x);\n        if (s2.empty() || s2.top() <= x) s2.push(x);\n    }\n    \n    int pop() {\n        int tmp = s1.top();\n        s1.pop();\n        if (tmp == s2.top())\n            s2.pop();\n        return tmp;\n    }\n    \n    int top() {\n        return s1.top();\n    }\n    \n    int peekMax() {\n        return s2.top();\n    }\n    \n    int popMax() {\n        int tmp = s2.top();\n        s2.pop();\n        \n        stack<int> tmpStack;\n        \n        while (s1.top() < tmp) {\n            tmpStack.push(s1.top());\n            s1.pop();\n        }\n        s1.pop();\n        while (!tmpStack.empty()) {\n            push(tmpStack.top());\n            tmpStack.pop();\n        }\n        \n        return tmp;\n    }\n};\n\n/**\n * Your MaxStack object will be instantiated and called as such:\n * MaxStack obj = new MaxStack();\n * obj.push(x);\n * int param_2 = obj.pop();\n * int param_3 = obj.top();\n * int param_4 = obj.peekMax();\n * int param_5 = obj.popMax();\n */\n"
  },
  {
    "path": "cpp/711-720/Maximum Length of Repeated Subarray.cpp",
    "content": "class Solution {\n\npublic:\n    int findLength(vector<int>& A, vector<int>& B) {\n        int maxlen = 0;\n        vector<vector<int>>dp (A.size(), vector<int>(B.size(), 0));\n        for(int i = 0; i < A.size(); ++i) {\n            for(int j = 0; j < B.size(); ++j) {\n                if(A[i] == B[j]) {\n                    if(i && j) {\n                        dp[i][j] = dp[i-1][j-1] + 1;\n                    } else if(i == 0 || j == 0) {\n                        dp[i][j] = 1;\n                    }\n                    if(dp[i][j] > maxlen) {\n                        maxlen = dp[i][j];\n                    }\n                }\n            }\n        }\n        return maxlen;\n    }\n};\n"
  },
  {
    "path": "cpp/711-720/Minimum ASCII Delete Sum for Two Strings.cpp",
    "content": "class Solution {\npublic:\n    int minimumDeleteSum(string s1, string s2) {\n        int m = s1.length();\n        int n = s2.length();\n        \n        vector<vector<int>> dp (m + 1, vector<int>(n + 1, 0));\n        \n        for (int i = 1; i <= m; i++) {\n            dp[i][0] = dp[i-1][0] + s1[i-1];\n        }\n        for (int i = 1; i <= n; i++) {\n            dp[0][i] = dp[0][i-1] + s2[i-1];\n        }\n        \n        for (int i = 1; i <= m; i++) {\n            for (int j = 1; j <= n; j++) {\n                if (s1[i-1] == s2[j-1]) {\n                    dp[i][j] = dp[i-1][j-1];\n                } else {\n                    dp[i][j] = min(dp[i][j-1] + s2[j-1], dp[i-1][j] + s1[i-1]);\n                }\n            }\n        }\n        \n        return dp[m][n];\n    }\n};\n"
  },
  {
    "path": "cpp/711-720/Number of Distinct Islands II.cpp",
    "content": "class Solution {\npublic:\n    map<int, vector<pair<int,int>>> mp;\n    \n    void dfs(int r, int c, vector<vector<int>> &g, int cnt) {\n        if ( r < 0 || c < 0 || r >= g.size() || c >= g[0].size()) return;\n        if (g[r][c] != 1) return;\n        g[r][c] = cnt;\n        mp[cnt].push_back({r,c});\n        dfs(r+1,c,g,cnt);\n        dfs(r-1,c,g,cnt);\n        dfs(r,c+1,g,cnt);\n        dfs(r,c-1,g,cnt);\n    }\n    \n    vector<pair<int,int>> norm(vector<pair<int,int>> v) {\n        vector<vector<pair<int,int>>> s(8);\n        // compute rotations/reflections.\n        for (auto p:v) {\n            int x = p.first, y = p.second;\n            s[0].push_back({x,y});\n            s[1].push_back({x,-y});\n            s[2].push_back({-x,y});\n            s[3].push_back({-x,-y});\n            s[4].push_back({y,-x});\n            s[5].push_back({-y,x});\n            s[6].push_back({-y,-x});\n            s[7].push_back({y,x});\n        }\n        for (auto &l:s) sort(l.begin(),l.end());\n        for (auto &l:s) {\n            for (int i = 1; i < v.size(); ++i) \n                l[i] = {l[i].first-l[0].first, l[i].second - l[0].second};\n            l[0] = {0,0};\n        }\n        sort(s.begin(),s.end());\n        return s[0];\n    }\n    \n    int numDistinctIslands2(vector<vector<int>>& g) {\n        int cnt = 1;\n        set<vector<pair<int,int>>> s;\n        for (int i = 0; i < g.size(); ++i) for (int j = 0; j < g[i].size(); ++j) if (g[i][j] == 1) {\n            dfs(i,j,g, ++cnt);\n            s.insert(norm(mp[cnt]));\n        }\n        \n        return s.size();\n    }\n};\n"
  },
  {
    "path": "cpp/711-720/Range Module.cpp",
    "content": "class RangeModule {\npublic:\n   void addRange(int left, int right) {\n        int n = invals.size();\n        vector<pair<int, int>> tmp;\n        for (int i = 0; i <= n; i++) {\n            if (i == n || invals[i].first > right) {\n                tmp.push_back({left, right});\n                while (i < n) tmp.push_back(invals[i++]);\n            }\n            else if (invals[i].second < left) \n                tmp.push_back(invals[i]);\n            else {\n                left = min(left, invals[i].first);\n                right = max(right, invals[i].second);\n            }\n        }\n        invals = tmp;\n    }\n    \n    bool queryRange(int left, int right) {\n        int n = invals.size(), l = 0, r = n-1;\n        while (l <= r) {\n            int m = l+(r-l)/2;\n            if (invals[m].first >= right)\n                r = m-1;\n            else if (invals[m].second <= left)\n                l = m+1;\n            else \n                return invals[m].first <= left && invals[m].second >= right;\n        }\n        return false;\n    }\n    \n    void removeRange(int left, int right) {\n        int n = invals.size();\n        vector<pair<int, int>> tmp;\n        for (int i = 0; i < n; i++) {\n            if (invals[i].second <= left || invals[i].first >= right)\n                tmp.push_back(invals[i]);\n            else {\n                if (invals[i].first < left)  tmp.push_back({invals[i].first, left});\n                if (invals[i].second > right) tmp.push_back({right, invals[i].second});\n            }\n        }\n        invals = tmp;\n    }\nprivate:\n    vector<pair<int, int>> invals;\n};\n"
  },
  {
    "path": "cpp/711-720/Subarray Product Less Than K.cpp",
    "content": "class Solution {\npublic:\n    int numSubarrayProductLessThanK(vector<int>& nums, int k) {\n        int i = 0, j = 0, result = 0, product = 1;\n        while (i < nums.size()) {\n            while (j < nums.size() && nums[j] * product < k) {\n                product *= nums[j];\n                j++;\n            }\n            if (i == j) {\n                i++;\n                j++;\n                continue;\n            }\n            result += (j-i);\n            product /= nums[i];\n            i++;\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/721-730/Accounts Merge.cpp",
    "content": "/*\n * Solution 1: DFS, slower when building graph.\n */\nclass Solution {\n    void dfs(const vector<vector<int>>& graph, const vector<vector<string>>& accounts, int ind, vector<bool>& visited, set<string>& emails) {\n        visited[ind] = true;\n        for (int i = 1; i < accounts[ind].size(); i++) {\n            emails.insert(accounts[ind][i]);\n        }\n        for (int neighbor : graph[ind]) {\n            if (!visited[neighbor]) {\n                dfs(graph, accounts, neighbor, visited, emails);\n            }\n        }\n    }\npublic:\n    vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {\n        vector<vector<string>> res;\n        int n = accounts.size();\n        vector<vector<int>> graph(n);\n        vector<bool> visited(n, false);\n        \n        for (int i = 0; i < n; i++) {\n            unordered_set<string> emails(accounts[i].begin()+1, accounts[i].end());\n            for (int j = 0; j < i; j++) {\n                if (accounts[i][0] != accounts[j][0]) {\n                    continue;\n                }\n                for (int k = 1; k < accounts[j].size(); k++) {\n                    if (emails.count(accounts[j][k]) > 0) {\n                        graph[i].push_back(j);\n                        graph[j].push_back(i);\n                        break;\n                    }\n                }\n            }\n        }\n        \n        for (int i = 0; i < accounts.size(); i++) {\n            if (!visited[i]) {\n                set<string> emailSet;\n                dfs(graph, accounts, i, visited, emailSet);\n                res.resize(res.size() + 1);\n                res.back().push_back(accounts[i][0]);\n                for (const string& email : emailSet) {\n                    res.back().push_back(email);\n                }\n            }\n        }\n        \n        return res;\n    }\n};\n\n/********************************************************************************/\n/*\n * Solution 2: DFS, faster when building graph.\n */\nclass Solution {\n    void dfs(const vector<vector<int>>& graph, const vector<vector<string>>& accounts, int ind, vector<bool>& visited, set<string>& emails) {\n        visited[ind] = true;\n        for (int i = 1; i < accounts[ind].size(); i++) {\n            emails.insert(accounts[ind][i]);\n        }\n        for (int neighbor : graph[ind]) {\n            if (!visited[neighbor]) {\n                dfs(graph, accounts, neighbor, visited, emails);\n            }\n        }\n    }\npublic:\n    vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {\n        vector<vector<string>> res;\n        int n = accounts.size();\n        vector<vector<int>> graph(n);\n        vector<bool> visited(n, false);\n        \n        unordered_map<string, vector<int>> email_to_ids;\n        for (int i = 0; i < n; i++) {\n            for (int j = 1; j < accounts[i].size(); j++) {\n                email_to_ids[accounts[i][j]].push_back(i);\n            }\n        }\n        for (const auto& pair : email_to_ids) {\n            const vector<int>& ids = pair.second;\n            for (int i = 1; i < ids.size(); i++) {\n                graph[ids[0]].push_back(ids[i]);\n                graph[ids[i]].push_back(ids[0]);\n            }\n        }\n        \n        for (int i = 0; i < accounts.size(); i++) {\n            if (!visited[i]) {\n                set<string> emailSet;\n                dfs(graph, accounts, i, visited, emailSet);\n                res.resize(res.size() + 1);\n                res.back().push_back(accounts[i][0]);\n                for (const string& email : emailSet) {\n                    res.back().push_back(email);\n                }\n            }\n        }\n        \n        return res;\n    }\n};\n\n/********************************************************************************/\n/*\n * Solution 3: Union-Find.\n */\nclass UF {\n    \nprivate:\n    vector<int> parent;\n    vector<int> rank;\n    int count;\n    int N;\n    \npublic:\n    \n    UF(int N) : parent(N), rank(N, 0), N(N), count(N) {\n        for (int i = 0; i < N; i++) {\n            parent[i] = i;\n        }\n    }\n    \n    int find(int p) {\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];    // path compression by halving\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    int getCount() const {\n        return count;\n    }\n    \n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    void Union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rootP == rootQ) return;\n        \n        // make root of smaller rank point to root of larger rank\n        if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;\n        else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;\n        else {\n            parent[rootQ] = rootP;\n            rank[rootP]++;\n        }\n        count--;\n    }\n};\n\nclass Solution {\npublic:\n    vector<vector<string>> accountsMerge(vector<vector<string>>& accounts) {\n        int n = accounts.size();\n        map<string, vector<int>> mymap;\n        for (int i = 0; i < n; i++) {\n            for (int j = 1; j < accounts[i].size(); j++) {\n                mymap[accounts[i][j]].push_back(i);\n            }\n        }\n        \n        UF uf(n);\n        for (const auto& it : mymap) {\n            for (int i = 1; i < it.second.size(); i++) {\n                uf.Union(it.second[0], it.second[i]);\n            }\n        }\n        \n        vector<vector<string>> result;\n        unordered_map<int, int> root_2_result_idx;\n        for (const auto& it : mymap) {\n            int root = uf.find(it.second[0]);\n            int resultSize = root_2_result_idx.size();\n            if (root_2_result_idx.count(root) == 0) {\n                root_2_result_idx[root] = resultSize;\n                vector<string> temp;\n                temp.push_back(accounts[root][0]);\n                result.push_back(temp);\n            }\n            int index = root_2_result_idx[root];\n            result[index].push_back(it.first);\n        }\n\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/721-730/Candy Crush.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> candyCrush(vector<vector<int>>& board) {\n        int n = board.size(), m = board[0].size();\n        while (true) {\n            vector<pair<int,int>> vp;\n            for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) if (board[i][j]) {\n                int i0 = i, i1 = i, j0 = j, j1 = j;\n                while (i1 < n &&  i1 < i + 3 && board[i1][j] == board[i][j]) ++i1;\n                while (i0 >= 0 && i0 > i - 3 && board[i0][j] == board[i][j]) --i0;\n                while (j1 < m && j1 < j + 3 && board[i][j1] == board[i][j]) ++j1;\n                while (j0 >= 0 && j0 > j - 3 && board[i][j0] == board[i][j]) --j0;\n                if (i1 - i0 >3 || j1 -j0 > 3) vp.push_back({i,j});\n            }\n            if (vp.empty()) break;\n            for (auto p:vp) board[p.first][p.second] = 0;\n            for (int j = 0; j < m; ++j) {\n                int t = n-1;\n                for (int i = n-1; i >=0; --i) if (board[i][j]) swap(board[i][j], board[t--][j]);\n            }\n        }\n        \n        return board;\n    }\n};\n"
  },
  {
    "path": "cpp/721-730/Count Different Palindromic Subsequences.cpp",
    "content": "class Solution {\npublic:\n  int countPalindromicSubsequences(string S) {\n    int n = S.size();\n    int mod = 1000000007;\n    auto dp_ptr = new vector<vector<vector<int>>>(4, vector<vector<int>>(n, vector<int>(n)));\n    auto& dp = *dp_ptr;\n\n    for (int i = n-1; i >= 0; --i) {\n      for (int j = i; j < n; ++j) {\n        for (int k = 0; k < 4; ++k) {\n          char c = 'a' + k;\n          if (j == i) {\n            if (S[i] == c) dp[k][i][j] = 1;\n            else dp[k][i][j] = 0;\n          } else { // j > i\n            if (S[i] != c) dp[k][i][j] = dp[k][i+1][j];\n            else if (S[j] != c) dp[k][i][j] = dp[k][i][j-1];\n            else { // S[i] == S[j] == c\n              if (j == i+1) dp[k][i][j] = 2; // \"aa\" : {\"a\", \"aa\"}\n              else { // length is > 2\n                dp[k][i][j] = 2;\n                for (int m = 0; m < 4; ++m) { // count each one within subwindows [i+1][j-1]\n                  dp[k][i][j] += dp[m][i+1][j-1];\n                  dp[k][i][j] %= mod;\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n\n    int ans = 0;\n    for (int k = 0; k < 4; ++k) {\n      ans += dp[k][0][n-1];\n      ans %= mod;\n    }\n\n    return ans;\n  }\n};\n"
  },
  {
    "path": "cpp/721-730/Find Pivot Index.cpp",
    "content": "class Solution {\npublic:\n    int pivotIndex(vector<int>& nums) {\n        if (nums.empty()) return -1;\n        int rightSum = std::accumulate(nums.begin() + 1, nums.end(), 0);\n        if (rightSum == 0) return 0;\n        \n        int leftSum = 0;\n        for (int i = 1; i < nums.size(); i++) {\n            leftSum += nums[i - 1];\n            rightSum -= nums[i];\n            if (leftSum == rightSum) return i;\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/721-730/My Calendar I.cpp",
    "content": "class MyCalendar {\n    vector<pair<int, int>> books;\npublic:\n    MyCalendar() {\n        \n    }\n    \n    bool book(int start, int end) {\n        for (const pair<int, int>& p : books)\n            if (max(p.first, start) < min(end, p.second)) return false;\n        books.push_back({start, end});\n        return true;\n    }\n};\n\n/**\n * Your MyCalendar object will be instantiated and called as such:\n * MyCalendar obj = new MyCalendar();\n * bool param_1 = obj.book(start,end);\n */\n"
  },
  {
    "path": "cpp/721-730/Number of Atoms.cpp",
    "content": "class Solution {\n    \n    void merge(map<string,int> &local, const map<string, int>& inners) {\n        for (auto it : inners) {\n            local[it.first] += it.second;\n        }\n    }\n    \n    void multiply(map<string,int> &local, int k) {\n        for (auto it : local) {\n            local[it.first] = it.second * k;\n        }\n    }\n    \n    int parseValue(const string& formula, int& i) {\n        int start = i;\n        while (i < formula.size() && isdigit(formula[i])) {\n            i++;\n        }\n        int value = 1;\n        if (i > start) {\n            value = stoi(formula.substr(start, i - start));\n        }\n        return value;\n    }\n    \n    void parseOneItem(map<string,int> &local, const string& formula, int& i) {\n        int start = i;\n        while (i+1 < formula.size() && islower(formula[i+1])) {\n            i++;\n        }\n        i++;\n        string key = formula.substr(start, i - start);\n        local[key] += parseValue(formula, i);\n    }\n    \n    map<string, int> dfs(const string& formula, int& i) {\n        map<string, int> locals;\n        \n        while (i < formula.size() && formula[i] != ')') {\n            if (formula[i] == '(') {\n                i++;\n                map<string, int> inners = dfs(formula, i);\n                merge(locals, inners);\n            } else {\n                parseOneItem(locals, formula, i);\n            }\n        }\n        \n        int k = 1;\n        if (formula[i] == ')') {\n            i++;\n            k = parseValue(formula, i);\n        }\n        multiply(locals, k);\n        \n        return locals;\n    }\n    \npublic:\n    string countOfAtoms(string formula) {\n        int i = 0;\n        map<string, int> counts = dfs(formula, i);\n        \n        string result = \"\";\n        for (auto it : counts) {\n            result += (it.first + (it.second > 1 ? to_string(it.second) : \"\"));\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/721-730/Remove Comments.cpp",
    "content": "class Solution {\npublic:\n    vector<string> removeComments(vector<string>& source) {\n        vector<string> ans;\n        bool inBlock = false;\n        string sf;\n        for (const string &t : source) {\n            for (int i = 0; i < t.size();) {\n                if (!inBlock) {\n                    if (i + 1 == t.size()) sf += t[i++];\n                    else {\n                        string m = t.substr(i,2);\n                        if (m == \"/*\") inBlock = true, i+=2;\n                        else if (m == \"//\") break;\n                        else sf += t[i++];\n                    }\n                } else {\n                    if (i + 1 == t.size()) i++;\n                    else {\n                        string m = t.substr(i,2);\n                        if (m == \"*/\") inBlock = false, i+=2;\n                        else i++;\n                    }\n                }\n            }\n            if (sf.size() && !inBlock) ans.push_back(sf), sf = \"\";\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/721-730/Self Dividing Numbers.cpp",
    "content": "class Solution {\npublic:\n    vector<int> selfDividingNumbers(int left, int right) {\n        vector<int> v;\n        for (int i = left; i <= right; ++i) {\n            int j = i;\n            bool ok = 1;\n            while (j) {\n                int d= (j%10);\n                if (d == 0 || i % d) ok = 0;\n                j/=10;\n            }\n            if (ok) v.push_back(i);\n        }\n        \n        return v;\n    }\n};\n"
  },
  {
    "path": "cpp/721-730/Split Linked List in Parts.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<ListNode*> splitListToParts(ListNode* root, int k) {\n        vector<ListNode*> parts(k, nullptr);\n        int len = 0;\n        for (ListNode* node = root; node != nullptr; node = node->next)\n            len++;\n        int n = len / k, r = len % k; // n : minimum guaranteed part size; r : extra nodes spread to the first r parts;\n        ListNode* node = root, *prev = nullptr;\n        for (int i = 0; i < k; i++, r--) {\n            parts[i] = node;\n            for (int j = 0; j < n + (r > 0); j++) {\n                prev = node;\n                node = node->next;\n            }\n            if (prev) prev->next = nullptr;\n        }\n        return parts;\n    }\n};\n"
  },
  {
    "path": "cpp/731-740/Asteroid Collision.cpp",
    "content": "class Solution {\npublic:\n    vector<int> asteroidCollision(vector<int>& asteroids) {\n        stack<int> mystack;\n        for (int ast : asteroids) {\n            bool eat = false;\n            while (!mystack.empty() && ast < 0 && 0 < mystack.top()) {\n                if (mystack.top() < -ast) {\n                    mystack.pop();\n                    continue;\n                } else if (mystack.top() == -ast) {\n                    eat = true;\n                    mystack.pop();\n                } else {\n                    eat = true;\n                }\n                break;\n            }\n            if (!eat) mystack.push(ast);\n        }\n\n        vector<int> ans(mystack.size());\n        for (int t = ans.size() - 1; t >= 0; --t) {\n            ans[t] = mystack.top();\n            mystack.pop();\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/731-740/Daily Temperatures.cpp",
    "content": "class Solution {\npublic:\n    vector<int> dailyTemperatures(vector<int>& temperatures) {\n        vector<int> res(temperatures.size(), 0);\n        stack<pair<int, int>> mystack;\n\n        for (int i = 0; i < temperatures.size(); i++) {\n            while (!mystack.empty() && mystack.top().first < temperatures[i]) {\n                res[mystack.top().second] = i - mystack.top().second;\n                mystack.pop();\n            }\n            mystack.push({temperatures[i], i});\n        }\n\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/731-740/Delete and Earn.cpp",
    "content": "class Solution {\n    \n    int rob(vector<int> &num) {\n        if (num.empty()) return 0;\n        \n        int p[num.size()];\n        p[0] = num[0];\n        p[1] = max(num[0], num[1]);\n        \n        for (int i = 2;i < num.size();i++)\n            p[i] = max(p[i-2] + num[i], p[i-1]);\n        return p[num.size()-1];\n    }\n    \npublic:\n    int deleteAndEarn(vector<int>& nums) {\n        int n = 10001;\n        vector<int> values(n, 0);\n        for (int num : nums)\n            values[num] += num;\n        \n        return rob(values);\n    }\n};\n"
  },
  {
    "path": "cpp/731-740/Flood Fill.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {\n        if (image[sr][sc] != newColor)\n            dfs(image, sr, sc, image[sr][sc], newColor);\n        return image;\n    }\n\nprivate:\n    void dfs(vector<vector<int>>& image, int i, int j, int c0, int c1) {\n        if (i < 0 || j < 0 || i >= image.size() || j >= image[0].size() || image[i][j] != c0) return;\n        image[i][j] = c1;\n        dfs(image, i, j - 1, c0, c1);\n        dfs(image, i, j + 1, c0, c1);\n        dfs(image, i - 1, j, c0, c1);\n        dfs(image, i + 1, j, c0, c1);\n    }\n};\n"
  },
  {
    "path": "cpp/731-740/Monotone Increasing Digits.cpp",
    "content": "class Solution {\npublic:\n    int monotoneIncreasingDigits(int N) {\n        string n_str = to_string(N);\n        \n        int marker = n_str.size();\n        for(int i = n_str.size()-1; i > 0; i --) {\n            if(n_str[i] < n_str[i-1]) {\n                marker = i;\n                n_str[i-1] = n_str[i-1]-1;\n            }\n        }\n        \n        for(int i = marker; i < n_str.size(); i ++) n_str[i] = '9';\n        \n        return stoi(n_str);\n    }\n};\n"
  },
  {
    "path": "cpp/731-740/My Calendar II.cpp",
    "content": "class MyCalendarTwo {\n    vector<pair<int, int>> once;\n    vector<pair<int, int>> twice;\n    \npublic:\n    MyCalendarTwo() {\n        \n    }\n    \n    bool book(int start, int end) {\n        \n        for (const pair<int, int>& p : twice)\n            if (max(p.first, start) < min(end, p.second)) return false;\n        \n        for (const pair<int, int>& p : once) {\n            if (max(p.first, start) < min(end, p.second)) {\n                int duplicateStart = max(p.first, start);\n                int duplicateEnd = min(end, p.second);\n                twice.push_back({duplicateStart, duplicateEnd});\n            }\n        }\n        \n        once.push_back({start, end});\n        \n        return true;\n    }\n};\n\n/**\n * Your MyCalendarTwo object will be instantiated and called as such:\n * MyCalendarTwo obj = new MyCalendarTwo();\n * bool param_1 = obj.book(start,end);\n */\n"
  },
  {
    "path": "cpp/731-740/My Calendar III.cpp",
    "content": "class MyCalendarThree {\n    map<int, int> timeline;\npublic:\n    int book(int s, int e) {\n        timeline[s]++; // 1 new event will be starting at [s]\n        timeline[e]--; // 1 new event will be ending at [e];\n        int ongoing = 0, k = 0;\n        for (const pair<int, int>& t : timeline)\n            k = max(k, ongoing += t.second);\n        return k;\n    }\n};\n\n/**\n * Your MyCalendarThree object will be instantiated and called as such:\n * MyCalendarThree obj = new MyCalendarThree();\n * int param_1 = obj.book(start,end);\n */\n"
  },
  {
    "path": "cpp/731-740/Parse Lisp Expression.cpp",
    "content": "class Solution {\npublic:\n    int evaluate(string expression) {\n        unordered_map<string, int> myMap;\n        return help(expression, myMap);\n    }\n    \n    int help(string expression, unordered_map<string, int> myMap) {\n        if ((expression[0] == '-') || (isdigit(expression[0])))\n            return stoi(expression);\n        else if (expression[0] != '(')\n            return myMap[expression];\n        //to get rid of the first '(' and the last ')'\n        string s = expression.substr(1, expression.size()-2);\n        int start = 0;\n        string word = parse(s, start);\n        if (word == \"let\") {\n            while (true) {\n                string variable = parse(s, start);\n                //if there is no more expression, simply evaluate the variable\n                if (start >= s.size())\n                    return help(variable, myMap);\n                string temp = parse(s,start);\n                myMap[variable] = help(temp, myMap);                    \n            }\n        }\n        else if (word == \"add\") \n            return help(parse(s,start), myMap) + help(parse(s,start), myMap);\n        else if (word == \"mult\") \n            return help(parse(s,start), myMap) * help(parse(s,start), myMap);\n    }\n    \n    //function to seperate each expression\n    string parse(string &s, int &start) {\n        int end = start+1, temp = start;\n        if (s[start] == '(') {\n            int count = 1;\n            while (count != 0) {\n                if (s[end] == '(')\n                    count++;\n                else if (s[end] == ')')\n                    count--;\n                end++;\n            }\n        }\n        else {\n            while (end < s.size() && s[end] != ' ')\n                end++;\n        }\n        start = end+1;\n        return s.substr(temp, end-temp);\n    }\n};\n"
  },
  {
    "path": "cpp/731-740/Sentence Similarity II.cpp",
    "content": "class UF {\n    \nprivate:\n    vector<int> parent;\n    vector<int> rank;\n    int count;\n    int N;\n    \npublic:\n    \n    UF(int N) : parent(N), rank(N, 0), N(N), count(N) {\n        for (int i = 0; i < N; i++) {\n            parent[i] = i;\n        }\n    }\n    \n    int find(int p) {\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];    // path compression by halving\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    int getCount() const {\n        return count;\n    }\n    \n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    void Union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rootP == rootQ) return;\n        \n        // make root of smaller rank point to root of larger rank\n        if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;\n        else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;\n        else {\n            parent[rootQ] = rootP;\n            rank[rootP]++;\n        }\n        count--;\n    }\n};\n\nclass Solution {\npublic:\n    bool areSentencesSimilarTwo(vector<string>& words1, vector<string>& words2, vector<pair<string, string>> pairs) {\n        if (words1.size() != words2.size()) return false;\n        map<string, int> mymap;\n        int k = 0;\n        for (const auto& pair : pairs) {\n            if (mymap.count(pair.first) == 0) {\n                mymap[pair.first] = k++;\n            }\n            if (mymap.count(pair.second) == 0) {\n                mymap[pair.second] = k++;\n            }\n        }\n        \n        UF uf(k);\n        for (const auto& pair : pairs) {\n            uf.Union(mymap[pair.first], mymap[pair.second]);\n        }\n        \n        for (int i = 0; i < words1.size(); i++) {\n            if (words1[i] == words2[i]) continue;\n            if (mymap.count(words1[i]) == 0 || mymap.count(words2[i]) == 0) return false;\n            if (!uf.connected(mymap[words1[i]], mymap[words2[i]])) return false;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/731-740/Sentence Similarity.cpp",
    "content": "class Solution {\npublic:\n    bool areSentencesSimilar(vector<string>& words1, vector<string>& words2, vector<pair<string, string>> pairs) {\n        if (words1.size() != words2.size()) return false;\n        map<string, set<string>> mymap;\n        for (const auto& pair : pairs) {\n            mymap[pair.first].insert(pair.second);\n            mymap[pair.second].insert(pair.first);\n        }\n        for (int i = 0; i < words1.size(); i++) {\n            if (words1[i] == words2[i]) continue;\n            if (mymap[words1[i]].count(words2[i]) == 0) return false;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/741-750/Closest Leaf in a Binary Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    vector<int> nodes[1001];\n    \n    void dfs(TreeNode* root, int k) {\n        if (!root) return;\n        if (root-> left) {\n            nodes[root->val].push_back(root->left->val);\n            nodes[root->left->val].push_back(root->val);\n            dfs(root->left, k);\n        }\n        if (root->right) {\n            nodes[root->val].push_back(root->right->val);\n            nodes[root->right->val].push_back(root->val);\n            dfs(root->right, k);   \n        }\n    }\n    \npublic:\n    int findClosestLeaf(TreeNode* root, int k) {\n        if (!root->left && !root->right) return root->val;\n        dfs (root, k);\n        queue<int> myqueue;\n        set<int> visited;\n        visited.insert(k);\n        myqueue.push(k);\n        \n        while (!myqueue.empty()) {\n            int e = myqueue.front();\n            myqueue.pop();\n            \n            if (nodes[e].size() == 1 && e != root->val) return e;\n            \n            for (int t : nodes[e]) {\n                if (visited.count(t) == 0) {\n                    myqueue.push(t);\n                    visited.insert(t);\n                }\n            }\n            \n        }\n        \n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/741-750/Find Smallest Letter Greater Than Target.cpp",
    "content": "class Solution {\npublic:\n    char nextGreatestLetter(vector<char>& letters, char target) {\n        vector<char>::iterator it = upper_bound(letters.begin(), letters.end(), target);\n        if (it == letters.end()) return letters.front();\n        return *it;\n    }\n};\n\n\n\n\nclass Solution {\npublic:\n    char nextGreatestLetter(vector<char>& letters, char target) {\n        if (target >= letters.back()) {\n            return letters.front();\n        }\n        int i = 0;\n        int j = letters.size() - 1;\n        \n        while (i < j) {\n            int mid = (i + j) / 2;\n            if (target < letters[mid]) {\n                j = mid;\n            } else if (target >= letters[mid]) {\n                i = mid + 1;\n            }\n        }\n        \n        return letters[i];\n    }\n};\n"
  },
  {
    "path": "cpp/741-750/Largest Number At Least Twice of Others.cpp",
    "content": "class Solution {\npublic:\n    int dominantIndex(vector<int>& nums) {\n        int maxOne = 0, maxTwo = 0, idx = 0;\n        for (int i = 0; i < nums.size(); i++) {\n            if (maxOne < nums[i]) {\n                maxTwo = maxOne;\n                maxOne = nums[i];\n                idx = i;\n            } else if (maxTwo < nums[i]) {\n                maxTwo = nums[i];\n            }\n        }\n        return maxOne >= maxTwo * 2 ? idx : -1;\n    }\n};\n"
  },
  {
    "path": "cpp/741-750/Min Cost Climbing Stairs.cpp",
    "content": "class Solution {\npublic:\n    int minCostClimbingStairs(vector<int>& cost) {\n        int n = cost.size();\n        vector<int> dp (n+1, 0);\n        dp[0] = cost[0];\n        dp[1] = cost[1];\n        for (int i = 2; i < n; i++) {\n            dp[i] = cost[i] + min(dp[i-2], dp[i-1]);\n        }\n        return min(dp[n-1], dp[n-2]);\n    }\n};\n"
  },
  {
    "path": "cpp/741-750/Network Delay Time.cpp",
    "content": "class Solution {\npublic:\n    int networkDelayTime(vector<vector<int>>& times, int N, int K) {\n        // Bellman-Ford\n        vector<int> dist(N + 1, INT_MAX);\n        dist[K] = 0;\n        for (int i = 0; i < N; i++) {\n            for (const vector<int>& e : times) {\n                int u = e[0], v = e[1], w = e[2];\n                if (dist[u] != INT_MAX && dist[v] > dist[u] + w) {\n                    dist[v] = dist[u] + w;\n                }\n            }\n        }\n\n        int maxwait = 0;\n        for (int i = 1; i <= N; i++)\n            maxwait = max(maxwait, dist[i]);\n        return maxwait == INT_MAX ? -1 : maxwait;\n    }\n};\n"
  },
  {
    "path": "cpp/741-750/Number Of Corner Rectangles.cpp",
    "content": "class Solution {\npublic:\n    int countCornerRectangles(vector<vector<int>>& grid) {\n        int ans = 0;\n        for (int i = 0; i < grid.size() - 1; i++) {\n            for (int j = i + 1; j < grid.size(); j++) {\n                int counter = 0;\n                for (int k = 0; k < grid[0].size(); k++) {\n                    if (grid[i][k] == 1 && grid[j][k] == 1) counter++;\n                }\n                if (counter > 0) ans += counter * (counter - 1) / 2;\n            }\n        }\n        return ans;\n    }\n};\n\n"
  },
  {
    "path": "cpp/741-750/Prefix and Suffix Search.cpp",
    "content": "struct TrieNode {\n    TrieNode *nodes[26];\n    bool word;\n    // Initialize your data structure here.\n    TrieNode(): word(false) {\n        memset(nodes, 0, sizeof(nodes));\n    }\n};\n\nclass Trie {\n    \n    void dfs(TrieNode *tmp, unordered_set<string>& words, string prefix) {\n        if (tmp->word) {\n            words.insert(prefix);\n        }\n        for (int i = 0; i < 26; i++) {\n            if (tmp->nodes[i]) {\n                char t = 'a' + i;\n                dfs(tmp->nodes[i], words, prefix + t);\n            }\n        }\n    }\n    \npublic:\n    Trie() {\n        root = new TrieNode();\n    }\n    \n    // Inserts a word into the trie.\n    void insert(const string& s) {\n        TrieNode *tmp = root;\n        for(char ch : s) {\n            int index = ch - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                tmp->nodes[index] = new TrieNode();\n            }\n            tmp = tmp->nodes[index];\n        }\n        tmp->word = true;\n    }\n    \n    // Returns if the word is in the trie.\n    unordered_set<string> search(const string& prefix) {\n        unordered_set<string> result;\n        TrieNode *tmp = root;\n        for(char ch : prefix) {\n            int index = ch - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                return result;\n            }\n            tmp = tmp->nodes[index];\n        }\n        dfs(tmp, result, prefix);\n        return result;\n    }\n    \nprivate:\n    TrieNode* root;\n};\n\nclass WordFilter {\n    \n    Trie T1, T2;\n    unordered_map<string, int> weights;\n    \npublic:\n    WordFilter(vector<string> words) {\n        int i = 0;\n        for (string word: words) {\n            weights[word] = i++;\n            T1.insert(word);\n            reverse(word.begin(), word.end());\n            T2.insert(word);\n        }\n    }\n    \n    int f(string prefix, string suffix) {\n        unordered_set<string> set1 = T1.search(prefix);\n        reverse(suffix.begin(), suffix.end());\n        unordered_set<string> set2 = T2.search(suffix);\n        \n        if (set1.empty() || set2.empty()) return -1;\n        \n        string ans;\n        for (string str : set2) {\n            reverse(str.begin(), str.end());\n            if (set1.count(str) > 0) {\n                if (ans.empty()) {\n                    ans = str;\n                } else if (weights[ans] < weights[str]) {\n                    ans = str;\n                }\n            }\n        }\n        \n        if (ans.empty()) return -1;\n        return weights[ans];\n    }\n};\n\n/**\n * Your WordFilter object will be instantiated and called as such:\n * WordFilter obj = new WordFilter(words);\n * int param_1 = obj.f(prefix,suffix);\n */\n"
  },
  {
    "path": "cpp/741-750/Shortest Completing Word.cpp",
    "content": "class Solution {\npublic:\n    string shortestCompletingWord(string licensePlate, vector<string>& words) {\n        transform(licensePlate.begin(), licensePlate.end(), licensePlate.begin(), ::tolower);\n        int counts[26] = {0};\n        string ans = \"\";\n        for (char ch : licensePlate) {\n            if (isalpha(ch)) {\n                counts[ch - 'a']++;\n            }\n        }\n        \n        for (const string& word : words) {\n            int temp[26] = {0};\n            for (char ch : word) {\n                temp[ch - 'a']++;\n            }\n            \n            bool match = true;\n            for (int i = 0; i < 26; i++) {\n                if (counts[i] > temp[i]) {\n                    match = false;\n                    break;\n                }\n            }\n            \n            if (match && ( ans.empty() || ans.length() > word.length() )) {\n                ans = word;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/751-760/Bold Words in String.cpp",
    "content": "class Solution {\nprivate:\n    vector<pair<int, int>> findpairs(const string& s, const vector<string>& dict) {\n        vector<pair<int, int>> res;\n        for (const string& w : dict) {\n            int n = w.size();\n            for (int i = 0; (i = s.find(w, i)) != string::npos; i++) {\n                res.emplace_back(make_pair(i, i + n));\n            }\n        }\n        return res;\n    }\n\n    vector<pair<int, int>> merge(vector<pair<int, int>>& a) {\n        vector<pair<int, int>> r;\n        auto cmp = [&](const pair<int, int>& a, const pair<int, int>& b) {\n            return a.first < b.first || a.first == b.first && a.second < b.second;\n        };\n        sort(a.begin(), a.end(), cmp);\n        for (int i = 0, j = -1; i < a.size(); i++) {\n            if (j < 0 || a[i].first > r[j].second) {\n                r.push_back(a[i]);\n                j++;\n            } else {\n                r[j].second = max(r[j].second, a[i].second);\n            }\n        }\n        \n        return r;\n    }\npublic:\n    string boldWords(vector<string>& words, string S) {\n        vector<pair<int, int>> ranges = findpairs(S, words);\n        ranges = merge(ranges);\n        for (auto it = ranges.rbegin(); it != ranges.rend(); it++) {\n            S.insert(it->second, \"</b>\");\n            S.insert(it->first, \"<b>\");\n        }\n        return S;\n    }\n};\n\n"
  },
  {
    "path": "cpp/751-760/Cracking the Safe.cpp",
    "content": "class Solution {\n    \n    bool dfs(int total, string& ans, int n, int k, bool* nodes) {\n        if (total == 0) return true;\n        ans += '0';\n        for (int d = 0; d < k; d++) {\n            ans.back() = d + '0';\n            int t = stoi(ans.substr(ans.size()-n, n));\n            if (!nodes[t]) {\n                nodes[t] = true;\n                bool OK = dfs (total-1, ans, n, k, nodes);\n                if (OK) {\n                    return true;\n                }\n                nodes[t] = false;\n            }\n        }\n        ans.pop_back();\n        return false;\n    }    \n    \npublic:\n    string crackSafe(int n, int k) {\n        bool nodes[10000] = {false};\n        string ans(n, '0');\n        int total = pow(k, n);\n        nodes[0] = true;\n        dfs(total - 1, ans, n, k, nodes);\n        return ans;\n    }\n};\n\n"
  },
  {
    "path": "cpp/751-760/Employee Free Time.cpp",
    "content": "/*\n// Definition for an Interval.\nclass Interval {\npublic:\n    int start;\n    int end;\n\n    Interval() {}\n\n    Interval(int _start, int _end) {\n        start = _start;\n        end = _end;\n    }\n};\n*/\n\nclass Solution {\npublic:\n    vector<Interval> employeeFreeTime(vector<vector<Interval>> schedule) {\n        map<int, int> mymap;\n        for (const vector<Interval>& s : schedule) {\n            for (const Interval& i : s) {\n                mymap[i.start]++;\n                mymap[i.end]--;\n            }\n        }\n        \n        int last = -1;\n        int cnt = 0;\n        vector<Interval> ans;\n        \n        for (const auto& pair : mymap) {\n            int pcnt = cnt;\n            cnt += pair.second;\n            \n            if (pcnt == 0 && last != -1) {\n                Interval in(last, pair.first);\n                ans.push_back(in);\n            } else if (cnt == 0) {\n                last = pair.first;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/751-760/Find Anagram Mappings.cpp",
    "content": "class Solution {\npublic:\n    vector<int> anagramMappings(vector<int>& A, vector<int>& B) {\n        map<int, int> mymap;\n        for (int i = 0; i < B.size(); i++) {\n            mymap[B[i]] = i;\n        }\n        \n        vector<int> result(A.size());\n        for (int i = 0; i < A.size(); i++) {\n            result[i] = mymap[A[i]];\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/751-760/IP to CIDR.cpp",
    "content": "class Solution {\n    \n    vector<string> split(const string &s, char delim) {\n        vector<string> elems;\n        stringstream ss(s);\n        string item;\n        while (getline(ss, item, delim)) {\n            if (item.length() > 0) {\n                elems.push_back(item);\n            }\n        }\n        return elems;\n    }\n    \n    string construct(long x, long rightMost) {\n        vector<string> ans(4);\n\t\tans[0] = to_string(x & 255); x >>= 8;\n\t\tans[1] = to_string(x & 255); x >>= 8;\n\t\tans[2] = to_string(x & 255); x >>= 8;\n\t\tans[3] = to_string(x);\n\t\tint len = 33;\n\t\twhile (rightMost > 0) {\n\t\t\tlen --;\n\t\t\trightMost /= 2;\n\t\t}\n\t\treturn ans[3] + \".\" + ans[2] + \".\" + ans[1] + \".\" + ans[0] + \"/\" + to_string(len);\n    }\n    \npublic:\n    vector<string> ipToCIDR(string ip, int n) {\n        vector<string> digits = split(ip, '.');\n        long start = stol(digits[0])*256*256*256 + stol(digits[1])*256*256 + stol(digits[2])*256 + stol(digits[3]);\n        vector<string> ans;\n        \n        while (n > 0) {\n            long rightMost = start == 0 ? 1 << 30 : start & -start;\n            while (rightMost > n) rightMost /= 2;\n            ans.push_back(construct(start, rightMost));\n            n -= rightMost;\n            start += rightMost;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/751-760/Open the Lock.cpp",
    "content": "class Solution {\n    \n    string transform(string str, int index, int sign) {\n        int i = str[index] - '0';\n        if (sign > 0) i = (i + 1)%10;\n        else i = (i + 9)%10;\n        char ch = i + '0';\n        str[index] = ch;\n        return str;\n    }\n    \npublic:\n    int openLock(vector<string>& deadends, string target) {\n        queue<pair<string, int>> myqueue;\n        set<string> deadset(deadends.begin(), deadends.end());\n        set<string> visited;\n        if (deadset.count(\"0000\") == 0) myqueue.push({\"0000\", 0});\n        \n        while (!myqueue.empty()) {\n            auto ele = myqueue.front();\n            myqueue.pop();\n            \n            if (ele.first == target) {\n                return ele.second;\n            }\n            \n            visited.insert(ele.first);\n            \n            for (int i = 0; i < 4; i++) {\n                for (int sign = 0; sign < 2; sign++) {\n                    string str = transform(ele.first, i, sign);\n                    if (deadset.count(str) == 0 && visited.count(str) == 0) {\n                        visited.insert(str);\n                        myqueue.push({str, ele.second + 1});\n                    }\n                }\n            }\n        }\n        \n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/751-760/Pour Water.cpp",
    "content": "class Solution {\npublic:\n    vector<int> pourWater(vector<int>& heights, int V, int K) {\n        for (int i = 0; i < V; i++) {\n            // try left\n            int candidateHeight = heights[K];\n            int candidateIndex = K;\n            \n            int j = K - 1;\n            while(j >= 0 && heights[j] <= candidateHeight) {\n                if (heights[j] < candidateHeight) {\n                    candidateHeight = heights[j];\n                    candidateIndex = j;\n                }\n                j--;\n            }\n            \n            // try right\n            if (candidateIndex == K) {\n                j = K + 1;\n                while(j < heights.size() && heights[j] <= candidateHeight) {\n                    if (heights[j] < candidateHeight) {\n                        candidateHeight = heights[j];\n                        candidateIndex = j;\n                    }\n                    j++;\n                }\n            }\n            \n            heights[candidateIndex]++;\n        }\n        \n        return heights;\n    }\n};\n"
  },
  {
    "path": "cpp/751-760/Pyramid Transition Matrix.cpp",
    "content": "class Solution {\n\n    bool dfs (vector<vector<char>>& pyramid, map<pair<char, char>, set<char>>& allowed, int i, int j) {\n        if (i < 0) return true;\n        \n        char ch1 = pyramid[i+1][j];\n        char ch2 = pyramid[i+1][j+1];\n        auto key = make_pair(ch1, ch2);\n        if (allowed.count(key) == 0) return false;\n        set<char> chars = allowed[key];\n        \n        for (char ch : chars) {\n            pyramid[i][j] = ch;\n            int nexti, nextj;\n            if (i == j) {\n                nexti = i - 1;\n                nextj = 0;\n            } else {\n                nexti = i;\n                nextj = j + 1;\n            }\n            if(dfs(pyramid, allowed, nexti, nextj)) return true;\n        }\n        \n        return false;\n    }\n    \npublic:\n    bool pyramidTransition(string bottom, vector<string>& allowed) {\n        map<pair<char, char>, set<char>> myallowed;\n        for (string str : allowed) {\n            myallowed[{str[0], str[1]}].insert(str[2]);\n        }\n\n        int n = bottom.length();\n        vector<vector<char>> pyramid(n, vector<char>(n));\n        for (int i = 0; i < n; i++) {\n            pyramid[n-1][i] = bottom[i];\n        }\n        return dfs(pyramid, myallowed, n-2, 0);\n    }\n};\n"
  },
  {
    "path": "cpp/751-760/Reach a Number.cpp",
    "content": "class Solution {\npublic:\n    int reachNumber(int target) {\n        target = abs(target);\n        int n = 1;\n        while (target > 0) {\n            target -= n; \n            n++;\n        }\n        \n        if (target %2 == 0) return n - 1;\n        if (n % 2 == 1) return n;\n        return n + 1;\n    }\n};\n"
  },
  {
    "path": "cpp/751-760/Set Intersection Size At Least Two.cpp",
    "content": "class Solution {\npublic:\n    int intersectionSizeTwo(vector<vector<int>>& intervals) {\n        auto comp = [](const vector<int>& p1, const vector<int>& p2) \n            { return p1[1] < p2[1] || (p1[1] == p2[1] && p1[0] > p2[0]); };\n        sort(intervals.begin(), intervals.end(), comp);\n        \n        int n = intervals.size();\n        vector<int> count(n, 2);\n        int ans = 0;\n        int end = -1;\n        \n        for (int i = 0; i < n; i++) {\n            if (count[i] == 0) continue;\n            ans += count[i];\n            for (int j = i+1; j < n; j++) {\n                if (count[j] > 0) {\n                    if (count[i] == 2) {\n                        int overlap = intervals[i][1] - intervals[j][0] + 1;\n                        if (overlap > 0) {\n                            count[j] -= overlap;\n                            count[j] = max(0, count[j]);\n                        }\n                    } else if (count[i] == 1) {\n                        int overlap = intervals[i][1] >= intervals[j][0] ? 1 : 0;\n                        count[j] -= overlap;\n                    }\n                }\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/761-770/Couples Holding Hands.cpp",
    "content": "class Solution {\n    \n    int getMatch(int a) {\n        if (a % 2 == 0) {\n            return a + 1;\n        } else {\n            return a - 1;\n        }\n    }\n    \n    bool match(int a, int b) {\n        return getMatch(a) == b;\n    }\n    \npublic:\n    int minSwapsCouples(vector<int>& row) {\n        int ans = 0;\n        map<int, int> mymap;\n        for (int i = 0; i < row.size(); i ++) {\n            mymap[row[i]] = i;\n        }\n        vector<bool> visited(row.size()/2, false);\n        \n        for (int i = 0; i < row.size(); i += 2) {\n            if (match(row[i], row[i+1])) continue;\n            int loop = 0;\n            int copy_i = i;\n            while (true) {\n                int virtual_index = copy_i / 2;\n                if (visited[virtual_index]) break;\n                visited[virtual_index] = true;\n                int mismatch = row[copy_i];\n                int match = getMatch(mismatch);\n                int match_index = mymap[match];\n                loop++;\n                copy_i = getMatch(match_index);\n            }\n            \n            ans += loop > 0 ? (loop - 1) : 0;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/761-770/Largest Plus Sign.cpp",
    "content": "class Solution {\npublic:\n    int orderOfLargestPlusSign(int N, vector<vector<int>>& mines) {\n        set<pair<int, int>> myset;\n        for (const auto& mine : mines) {\n            myset.insert({mine[0], mine[1]});\n        }\n        \n        vector<vector<int>> left (N, vector<int>(N, 0));\n        vector<vector<int>> right (N, vector<int>(N, 0));\n        vector<vector<int>> up (N, vector<int>(N, 0));\n        vector<vector<int>> down (N, vector<int>(N, 0));\n        \n        for (int i = 0; i < N; i++) {\n            int temp = 0;\n            for (int j = 0; j < N; j++) {\n                if (myset.count({i, j}) > 0) {\n                    temp = 0;\n                } else {\n                    temp++;\n                }\n                left[i][j] = temp;\n            }\n        }\n        \n        for (int i = 0; i < N; i++) {\n            int temp = 0;\n            for (int j = N-1; j >= 0; j--) {\n                if (myset.count({i, j}) > 0) {\n                    temp = 0;\n                } else {\n                    temp++;\n                }\n                right[i][j] = temp;\n            }\n        }\n        \n        for (int i = 0; i < N; i++) {\n            int temp = 0;\n            for (int j = 0; j < N; j++) {\n                if (myset.count({j, i}) > 0) {\n                    temp = 0;\n                } else {\n                    temp++;\n                }\n                up[j][i] = temp;\n            }\n        }\n        \n        for (int i = 0; i < N; i++) {\n            int temp = 0;\n            for (int j = N-1; j >= 0; j--) {\n                if (myset.count({j, i}) > 0) {\n                    temp = 0;\n                } else {\n                    temp++;\n                }\n                down[j][i] = temp;\n            }\n        }\n        \n        int ans = 0;\n        for (int i = 0; i < N; i++) {\n            for (int j = 0; j < N; j++) {\n                int current = min(left[i][j], right[i][j]);\n                current = min(up[i][j], current);\n                current = min(down[i][j], current);\n                ans = max(ans, current);\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/761-770/Max Chunks To Make Sorted II.cpp",
    "content": "class Solution {\npublic:\n    int maxChunksToSorted(vector<int>& arr) {\n        int n = arr.size();\n        vector<int> leftMax(n, arr[0]);\n        vector<int> rightMin(n, arr[n-1]);\n        \n        for (int i = 1; i < n; i++) {\n            leftMax[i] = max(leftMax[i-1], arr[i]);\n        }\n        for (int i = n - 2; i >= 0; i--) {\n            rightMin[i] = min(rightMin[i+1], arr[i]);\n        }\n        \n        int result = 0;\n        for (int i = 0; i < n; i++) {\n            if (i == n - 1) {\n                result++;\n            } else if (rightMin[i + 1] >= leftMax[i]) {\n                result++;\n            }\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/761-770/Max Chunks To Make Sorted.cpp",
    "content": "class Solution {\npublic:\n    int maxChunksToSorted(vector<int>& arr) {\n        int result = 0;\n        int temp_max = arr[0];\n        for (int i = 0; i < arr.size(); i++) {\n            temp_max = max(temp_max, arr[i]);\n            if (temp_max == i) {\n                result++;\n            }\n        }\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/761-770/Partition Labels.cpp",
    "content": "class Solution {\npublic:\n    vector<int> partitionLabels(string S) {\n        map<char, int> mymap;\n        for (int i = 0; i < S.length(); i++) {\n            mymap[S[i]] = i;\n        }\n        \n        vector<int> ans;\n        int maximum_pos = 0;\n        int last = -1;\n        for (int i = 0; i < S.length(); i++) {\n            char ch = S[i];\n            maximum_pos = max(maximum_pos, mymap[ch]);\n            if (i == maximum_pos) {\n                ans.push_back(i - last);\n                last = i;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/761-770/Prime Number of Set Bits in Binary Representation.cpp",
    "content": "class Solution {\npublic:\n    int countPrimeSetBits(int L, int R) {\n        set<int> primes = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };\n        int cnt = 0;\n        for (int i = L; i <= R; i++) {\n            int bits = 0;\n            for (int n = i; n; n >>= 1)\n                bits += n & 1;\n            cnt += primes.count(bits);\n        }\n        return cnt;\n    }\n};\n"
  },
  {
    "path": "cpp/761-770/Reorganize String.cpp",
    "content": "class Solution {\npublic:\n    string reorganizeString(string S) {\n        \n        map<char, int> mymap;\n        \n        for (char ch : S) {\n            mymap[ch]++;\n            if (mymap[ch] > (S.length() + 1) / 2) return \"\";\n        }\n        \n        auto cmp = [](const pair<int, char> &a, const pair<int, char> &b) {\n            return a.first < b.first;\n        };\n\n        priority_queue<pair<int, char>, vector<pair<int, char>>, decltype(cmp)> pq(cmp);\n        \n        for (const auto& e : mymap) {\n            pq.push({e.second, e.first});\n        }\n        \n        string ans;\n        while (!pq.empty()) {\n            pair<int, char> first = pq.top();\n            pq.pop();\n            ans += first.second;\n            if (!pq.empty()) {\n                pair<int, char> second = pq.top();\n                pq.pop();\n                ans += second.second;\n                if (first.first > 1) pq.push({first.first - 1, first.second});\n                if (second.first > 1) pq.push({second.first - 1, second.second});\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/761-770/Special Binary String.cpp",
    "content": "class Solution {\n    \n    static bool cmp(const string& a, const string& b) {\n        return a > b;\n    }\n    \npublic:\n    string makeLargestSpecial(string S) {\n        if (S.length() == 0) return \"\";\n        int cnt = 0;\n        vector<string> groups;\n        int start = 0;\n        for (int i = 0; i < S.length(); i++) {\n            if (S[i] == '1') {\n                cnt++;\n            } else {\n                cnt--;\n            }\n            \n            if (cnt == 0) {\n                groups.push_back(\"1\" + makeLargestSpecial(S.substr(start + 1, i - start - 1)) + \"0\");\n                start = i + 1;\n            }\n        }\n\n        sort(begin(groups), end(groups), cmp);\n        string result;\n        result = accumulate(begin(groups), end(groups), result);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/761-770/Toeplitz Marix.cpp",
    "content": "class Solution {\npublic:\n    bool isToeplitzMatrix(vector<vector<int>>& matrix) {\n        for (int r = 0; r < matrix.size(); r++)\n            for (int c = 0; c < matrix[0].size(); c++)\n                if (r > 0 && c > 0 && matrix[r-1][c-1] != matrix[r][c])\n                    return false;\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/771-780/Basic Calculator III.cpp",
    "content": "class Solution {\n    \n    void apply(stack<int>&s, char c) {\n        int b = s.top();s.pop();\n        int a = s.top();s.pop();\n        if(c == '+') s.push(a+b);\n        else if(c == '-') s.push(a-b);\n        else if(c == '*') s.push(a*b);\n        else s.push(a/b);\n    }\n    \npublic:\n    int calculate(string s) {\n        \n        stack<char> symbol;\n        stack<int>ss;\n        int v = 0;\n        bool number = false;\n        for (char e : s) {\n            if (number && !isdigit(e)) {\n                ss.push(v);\n                v = 0;\n                number = false;\n            }\n            \n            if (e == ' ') continue;\n            else if (e == ')') {\n                while (symbol.top() != '(') {\n                    char c = symbol.top();\n                    apply(ss, c);\n                    symbol.pop();\n                }\n                symbol.pop();\n            } else if (e == '(') {\n                symbol.push('(');\n            } else if (isdigit(e)) {\n                v = 10*v + (e-'0');\n                number = true;\n            } else if (e == '+' || e == '-') {\n                while (!symbol.empty() && (symbol.top() == '*' || symbol.top() == '/' || symbol.top() == '+' || symbol.top() == '-')) {\n                    char c = symbol.top();\n                    symbol.pop();\n                    apply(ss, c);\n                }\n                symbol.push(e);\n            } else if (e == '*' || e == '/') {\n                while (!symbol.empty() && (symbol.top() == '*' || symbol.top() == '/') ) {\n                    char c = symbol.top();\n                    symbol.pop();\n                    apply(ss, c);\n                }\n                symbol.push(e);\n            }\n        }\n        \n        if (number) {\n            ss.push(v);\n        }\n        \n        while (!symbol.empty()) {\n            char c = symbol.top();\n            apply(ss,c);\n            symbol.pop();\n        }\n        \n        return ss.top();\n    }\n};\n"
  },
  {
    "path": "cpp/771-780/Global and Local Inversions.cpp",
    "content": "class Solution {\n    \npublic:\n    bool isIdealPermutation(vector<int>& A) {\n        vector<int> dp(A.size(), 0);\n        dp[0] = A[0];\n        for (int i = 1; i < A.size(); i++) {\n            dp[i] = max(dp[i-1], A[i]);\n        }\n        \n        for (int i = 2; i < A.size(); i++) {\n            if (A[i] < dp[i-2]) {\n                return false;\n            }\n        }\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/771-780/Jewels and Stones.cpp",
    "content": "class Solution {\npublic:\n    int numJewelsInStones(string J, string S) {\n        set<char> jewel;\n        for (char ch : J) jewel.insert(ch);\n        int ans = 0;\n        for (char ch : S) {\n            if (jewel.count(ch) > 0) {\n                ans++;\n            }\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/771-780/K-th Symbol in Grammar.cpp",
    "content": "class Solution {\npublic:\n    int kthGrammar(int N, int K) {\n        if (N == 1) return 0;\n        if (N == 2) {\n            if (K == 1) return 0;\n            return 1;\n        }\n        int temp = kthGrammar(N-1, (K+1)/2);\n        if (K % 2 == 1) return temp;\n        return (temp+1)%2;\n    }\n};\n"
  },
  {
    "path": "cpp/771-780/Minimize Max Distance to Gas Station.cpp",
    "content": "class Solution {\npublic:\n    double minmaxGasDist(vector<int>& stations, int K) {\n        int maxGap = 0;\n        for (int i = 1; i < stations.size(); i++) {\n            maxGap = max(maxGap, stations[i] - stations[i-1]);\n        }\n        \n        double lower = 0, upper = maxGap;\n        while (upper - lower >= 1e-6) {\n            double mid = (lower + upper) / 2;\n            int num = 0;\n            for (int i = 1; i < stations.size(); i++) {\n                num += ceil((stations[i] - stations[i-1]) / mid) - 1;\n            }\n            if (num > K) {\n                lower = mid;\n            } else {\n                upper = mid;\n            }\n        }\n        \n        return upper;\n    }\n};\n"
  },
  {
    "path": "cpp/771-780/Sliding Puzzle.cpp",
    "content": "class Solution {\n    \n    int seralize(vector<vector<int>>& board) {\n        int result = 0;\n        for (int i = 0; i < 2; i++) {\n            for (int j = 0; j < 3; j++) {\n                result = result * 10 + board[i][j];\n            }\n        }\n        return result;\n    }\n    \npublic:\n    int slidingPuzzle(vector<vector<int>>& board) {\n        int goal = 123450;\n        int mi = 0, mj = 0;\n        for (int i = 0; i < 2; i++) {\n            for (int j = 0; j < 3; j++) {\n                if (board[i][j] == 0) {\n                    mi = i;\n                    mj = j;\n                }\n            }\n        }\n        \n        queue<pair<int, vector<vector<int>>>>myqueue;\n        myqueue.push({0, board});\n        set<int>visited;\n        \n        while (!myqueue.empty()) {\n            pair<int, vector<vector<int>>> e = myqueue.front();\n            myqueue.pop();\n            int key = seralize(e.second);\n            if (key == goal) {\n                return e.first;\n            }\n            if (visited.count(key) > 0) continue;\n            visited.insert(key);\n            vector<vector<int>> myboard = e.second;\n            \n            int ii, jj;\n            for (int i = 0; i < 2; i++) {\n                for (int j = 0; j < 3; j++) {\n                    if (myboard[i][j] == 0) {\n                        ii = i;\n                        jj = j;\n                    }\n                }\n            }\n            \n            pair<int, int> mypair[4] = {{1,0}, {-1, 0}, {0,-1}, {0,1}};\n            for (int i = 0; i < 4; i++) {\n                int ni = ii + mypair[i].first;\n                int nj = jj + mypair[i].second;\n                if (ni < 0 || nj < 0 || ni >= 2 || nj >= 3) continue;\n                vector<vector<int>> Tboard = myboard;\n                Tboard[ii][jj] = Tboard[ni][nj];\n                Tboard[ni][nj] = 0;\n                myqueue.push({e.first + 1, Tboard});\n            }\n        }\n        \n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/771-780/Split BST.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<TreeNode*> splitBST(TreeNode* root, int V) {\n        if (root == nullptr) {\n            return vector<TreeNode*> {nullptr, nullptr};\n        } else if (root->val <= V) {\n            vector<TreeNode*> result = splitBST(root->right, V);\n            root->right = result[0];\n            result[0] = root;\n            return result;\n        } else {\n            vector<TreeNode*> result = splitBST(root->left, V);\n            root->left = result[1];\n            result[1] = root;\n            return result;\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/771-780/Swap Adjacent in LR String.cpp",
    "content": "class Solution {\npublic:\n    bool canTransform(string start, string end) {\n        string s, t;\n        \n        for (char ch : start) {\n            if (ch != 'X') {\n                s += ch;   \n            }\n        }\n        for (char ch : end) {\n            if (ch != 'X') {\n                t += ch;   \n            }\n        }\n        if (s != t) return false;\n        \n        int sR = 0, sL = 0, eR = 0, eL = 0;\n        for (int i = 0; i < start.length(); i++) {\n            if (start[i] == 'L') sL++;\n            if (start[i] == 'R') sR++;\n            if (end[i] == 'R') eR++;\n            if (end[i] == 'L') eL++;\n\n            if (eR > sR) return false;\n            if (sL > eL) return false;\n        }\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/771-780/Swim in Rising Water.cpp",
    "content": "class Solution {\npublic:\n    int swimInWater(vector<vector<int>>& grid) {\n        int N = grid.size();\n        int ans = 0;\n        auto cmp = [](const pair<int, pair<int, int>> &a, pair<int, pair<int, int>> &b) {\n            return a.first > b.first;\n        };\n        \n        priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>, decltype(cmp)> pq(cmp);\n        \n        pair<int, pair<int, int>> start{grid[0][0], {0, 0}};\n        pq.push(start);\n        \n        set<int> visited;\n        \n        while (!pq.empty()) {\n            pair<int, pair<int, int>> current = pq.top();\n            pq.pop();\n            ans = max(ans, current.first);\n            visited.insert(current.second.first * 10000 + current.second.second);\n            \n            if(current.second.first == N - 1 && current.second.second == N - 1) {\n                break;\n            }\n            \n            pair<int, int> mypair[4] = {{1, 0}, {-1, 0}, {0,1}, {0,-1}};\n            for (pair<int, int> pos : mypair) {\n                int nexti = current.second.first + pos.first;\n                int nextj = current.second.second + pos.second;\n                if (nexti < 0 || nextj < 0 || nexti >= N || nextj >= N) continue;\n                if (visited.count(nexti * 10000 + nextj) > 0) continue;\n                pq.push({grid[nexti][nextj], {nexti, nextj}});\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/781-790/Cheapest Flights Within K Stops.cpp",
    "content": "class Solution {\npublic:\n    int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {\n        vector<int> dis(n, -1);\n        dis[src] = 0;\n        \n        for (int i = 0; i <= K; i++) {\n            vector<int> copy(dis);\n            for (const vector<int>& flight : flights) {\n                int u = flight[0];\n                int v = flight[1];\n                int cost = flight[2];\n\n                if (copy[u] < 0) continue;\n                if (dis[v] < 0) dis[v] = copy[u] + cost;\n                else dis[v] = min(dis[v], copy[u] + cost);\n            }\n        }\n        \n        return dis[dst];\n    }\n};\n"
  },
  {
    "path": "cpp/781-790/Escape The Ghosts.cpp",
    "content": "class Solution {\n    \n    int dis(int x, int y) {\n        return abs(x) + abs(y);\n    }\n    \npublic:\n    bool escapeGhosts(vector<vector<int>>& ghosts, vector<int>& target) {\n        int temp = dis(target[0], target[1]); \n        for (const auto& ghost : ghosts) {\n            if (dis(target[0] - ghost[0], target[1] - ghost[1]) <= temp) return false;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/781-790/Is Graph Bipartite?.cpp",
    "content": "class Solution {\n    \n    bool dfs(int node, vector<int>& colors, const vector<vector<int>>& graph, int c) {\n        colors[node] = c;\n        for (int neighbor : graph[node]) {\n            if (colors[neighbor] == c) {\n                return false;\n            }\n            if (colors[neighbor] == 0 && !dfs(neighbor, colors, graph, 3 - c)) {\n                return false;\n            }\n        }\n        return true;\n    }\n    \npublic:\n    bool isBipartite(vector<vector<int>>& graph) {\n        int n = graph.size();\n        vector<int> colors(n, 0);\n        \n        for (int i = 0; i < n; i++)\n            if (colors[i] == 0)\n                if(!dfs(i, colors, graph, 1))\n                    return false;\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/781-790/K-th Smallest Prime Fraction.cpp",
    "content": "class Solution {\npublic:\n    vector<int> kthSmallestPrimeFraction(vector<int>& A, int K) {\n        auto cmp = [](const vector<int> &a, const vector<int> &b) {\n            return a[0]*b[1] > b[0]*a[1];\n        };\n\n        priority_queue<vector<int>, vector<vector<int>>, decltype(cmp)> pq(cmp);\n        \n        for (int i = 1; i < A.size(); i++) {\n            vector<int> temp {1, A[i], 0};\n            pq.push(temp);\n        }\n        \n        while (--K) {\n            vector<int> top = pq.top();\n            pq.pop();\n            int nindex = top[2] + 1;\n            int next = A[nindex];\n            if (next >= top[1]) continue;\n            vector<int> temp {next, top[1], nindex};\n            pq.push(temp);\n        }\n        \n        return vector<int> {pq.top()[0], pq.top()[1]};\n    }\n};\n"
  },
  {
    "path": "cpp/781-790/Letter Case Permutation.cpp",
    "content": "class Solution {\n    \n    void dfs(string S, int i, vector<string>& result) {\n        if (i == S.length()) {\n            result.push_back(S);\n            return;\n        }\n        if (isdigit(S[i])) {\n            dfs(S, i+1, result);\n        } else {\n            S[i] = tolower(S[i]);\n            dfs(S, i+1, result);\n            S[i] = toupper(S[i]);\n            dfs(S, i+1, result);\n        }\n    }\n    \npublic:\n    vector<string> letterCasePermutation(string S) {\n        vector<string> result;\n        dfs(S, 0, result);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/781-790/Minimum Distance Between BST Nodes.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    void dfs(TreeNode* root, int &pv, int& result) {\n        if (!root) return;\n        dfs(root->left, pv, result);\n        if (pv != INT_MIN) result = min(result, abs(pv - root->val));\n        pv = root->val;\n        dfs(root->right, pv, result);\n    }\n    \npublic:\n    int minDiffInBST(TreeNode* root) {\n        int pv = INT_MIN;\n        int result = INT_MAX;\n        dfs(root, pv, result);\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/781-790/Rabbits in Forest.cpp",
    "content": "class Solution {\npublic:\n    int numRabbits(vector<int>& answers) {\n        unordered_map<int, int> mymap;\n        \n        int ans = 0;\n        for (int e : answers) {\n            if (mymap[e] == 0) {\n                ans += (e+1);\n                mymap[e] = e;\n            } else {\n                mymap[e]--;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/781-790/Rotated Digits.cpp",
    "content": "class Solution {\n    \n    bool isValid(int N) {\n        bool validFound = false;\n        while (N > 0) {\n            int lastDigit = N % 10;\n            if (lastDigit == 2 || lastDigit == 5 || lastDigit == 6 || lastDigit == 9) validFound = true;\n            if (lastDigit == 3 || lastDigit == 4 || lastDigit == 7) return false;\n            N = N / 10;\n        }\n        return validFound;\n    }\n    \npublic:\n    int rotatedDigits(int N) {\n        int count = 0;\n        for (int i = 1; i <= N; i ++) {\n            if (isValid(i)) count++;\n        }\n        return count;\n    }\n};\n"
  },
  {
    "path": "cpp/781-790/Transform to Chessboard.cpp",
    "content": "class Solution {\n    \n    unsigned int countSetBits(unsigned int n) {\n        unsigned int count = 0;\n        while (n) {\n            count += n & 1;\n            n >>= 1;\n        }\n        return count;\n    }\n    \npublic:\n    int movesToChessboard(vector<vector<int>>& board) {\n        int n = board.size();\n        map<int, int> mymap;\n        for (const vector<int>& row : board) {\n            int num = 0;\n            for (int e : row) {\n                num = 2*num + e;\n            }\n            mymap[num]++;\n        }\n        \n        int c1 = check(mymap, n);\n        if (c1 < 0) return -1;\n        \n        map<int, int> mymap2;\n        for (int i = 0; i < n; i++) {\n            int num = 0;\n            for (int j = 0; j < n; j++) {\n                num = 2*num + board[j][i];\n            }\n            mymap2[num]++;\n        }\n        \n        int c2 = check(mymap2, n);\n        if (c2 < 0) return -1;\n        \n        return c1 + c2;\n    }\n    \n    int check(map<int, int>& mymap, int n) {\n        if (mymap.size() != 2) return -1;\n        int nOne = (1 << n) - 1;\n        int key1 = -1, key2 = -1;\n        \n        // get the two key\n        for (auto it : mymap) {\n            if (key1 == -1) {\n                key1 = it.first;\n            } else {\n                key2 = it.first;\n            }\n        }\n        \n        if ((key1 ^ key2) != nOne) return -1;\n        if (abs(mymap[key1] - mymap[key2]) > 1) return -1;\n        \n        if (n%2 == 1) {\n            int totalOne = countSetBits(key1);\n            if (totalOne == n / 2) return countSetBits(key1 ^ (0xAAAAAAAA&nOne))/2;\n            else return countSetBits(key1 ^ (0x55555555&nOne))/2;\n        }\n        return (min(countSetBits(key1 ^ (0xAAAAAAAA&nOne)), countSetBits(key1 ^ (0x55555555&nOne))) + 1)/2;\n    }\n};\n"
  },
  {
    "path": "cpp/791-800/All Paths From Source to Target.cpp",
    "content": "class Solution {\n    \n    void dfs(int current, int target, vector<int> path, const vector<vector<int>>& graph, vector<vector<int>>& result) {\n        if (current == target) {\n            result.emplace_back(path);\n            return;\n        }\n        \n        for (int e : graph[current]) {\n            vector<int> pathCopy(path);\n            pathCopy.push_back(e);\n            dfs(e, target, pathCopy, graph, result);\n        }\n    }\n    \npublic:\n    vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {\n        vector<vector<int>> result;\n        int n = graph.size();\n        vector<int> vec{0};\n        \n        dfs(0, n-1, vec, graph, result);\n        \n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/791-800/Champagne Tower.cpp",
    "content": "class Solution {\npublic:\n    double champagneTower(int poured, int query_row, int query_glass) {\n        vector<vector<double>> myvec (query_row+2, vector<double>(query_row+3, 0));\n        myvec[0][0] = poured;\n        for (int i = 0; i <= query_row; i++) {\n            for (int j = 0; j <= i; j++) {\n                double overflow = fmax(myvec[i][j] - 1, 0);\n                myvec[i][j] -= overflow;\n                myvec[i+1][j] += overflow/2;\n                myvec[i+1][j+1] += overflow/2;\n            }\n        }\n        return myvec[query_row][query_glass];\n    }\n};\n"
  },
  {
    "path": "cpp/791-800/Custom Sort String.cpp",
    "content": "class Solution {\npublic:\n    string customSortString(string S, string T) {\n        map<char, int> mymap;\n        for (char ch : T) mymap[ch]++;\n        string result;\n        for (char ch : S) {\n            string temp(mymap[ch], ch);\n            result += temp;\n            mymap[ch] = 0;\n        }\n        for (const auto& it : mymap) {\n            if (it.second > 0) {\n                string temp(it.second, it.first);\n                result += temp;\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/791-800/Number of Matching Subsequences.cpp",
    "content": "class Solution {\npublic:\n    int numMatchingSubseq(string S, vector<string>& words) {\n        vector<const char*> waiting[128];\n        for (auto &w : words)\n            waiting[w[0]].push_back(w.c_str());\n        for (char c : S) {\n            vector<const char*> advance = waiting[c];\n            waiting[c].clear();\n            for (const char* it : advance)\n                waiting[*++it].push_back(it);\n        }\n        return waiting[0].size();\n    }\n};\n"
  },
  {
    "path": "cpp/791-800/Number of Subarrays with Bounded Maximum.cpp",
    "content": "class Solution {\npublic:\n    int numSubarrayBoundedMax(vector<int>& A, int L, int R) {\n        int count = 0, ans = 0;\n        int previous = 0;\n        \n        for (int i = 0; i < A.size(); i++) {\n            if (A[i] >= L && A[i] <= R) {\n                count = 1 + i - previous;\n                ans += count;\n            } else if (A[i] < L) {\n                ans += count;\n            } else {\n                previous = i + 1;\n                count = 0;\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/791-800/Preimage Size of Factorial Zeroes Function.cpp",
    "content": "class Solution {\n    \npublic:\n    int preimageSizeFZF(long K) {\n        long a = 1;\n        while (K >= 5*a + 1) a = 5*a + 1;\n        cout << a << endl;\n        while (K >= 6) {\n            if (K % a == 0) {\n                if (K == 5*a) {\n                    return 0;\n                } else {\n                    return 5;\n                }\n            }\n            K = K % a;\n            a = (a-1)/5;\n        }\n        \n        if (K == 5) return 0;\n        return 5;\n    }\n};\n\n// 1 1 1 1 2 1 1 1 1 2 1 1 1 1 2 1 1 1 1 2 1 1 1 1 3 \n// 12 30\n"
  },
  {
    "path": "cpp/791-800/Rotate String",
    "content": "class Solution {\npublic:\n    bool rotateString(string A, string B) {\n        string AA = A + A;\n        if (AA.find(B) != string::npos) return true;\n        return false;\n    }\n};\n"
  },
  {
    "path": "cpp/791-800/Similar RGB Color.cpp",
    "content": "class Solution {\n    \n    string helper(string str) {\n        string dec_to_hex = \"0123456789abcdef\";\n\n        int dec_num = stoi(str, nullptr, 16);\n        int q = (dec_num+8) / 17;\n        string res(2, dec_to_hex[q]);\n        return res;\n    }\n    \npublic:\n    string similarRGB(string color) {\n        return \"#\" + helper(color.substr(1, 2)) + helper(color.substr(3, 2)) + helper(color.substr(5, 2));\n    }\n};\n"
  },
  {
    "path": "cpp/791-800/Valid Tic-Tac-Toe State.cpp",
    "content": "class Solution {\npublic:\n    bool validTicTacToe(vector<string>& board) {\n        vector<int> rowSum(3, 0);\n        vector<int> colSum(3, 0);\n        int dig1 = 0, dig2 = 0;\n        int numX = 0, numO = 0;\n        \n        int winX = 0, winO = 0;\n        \n        for (int i = 0; i < 3; i++) {\n            string str = board[i];\n            for (int j = 0; j < str.length(); j++) {\n                if (str[j] == 'X') {\n                    numX++;\n                    rowSum[i]++;\n                    colSum[j]++;\n                    if (i == j) dig1++;\n                    if (i + j == 2) dig2++;\n                } else if (str[j] == 'O') {\n                    numO++;\n                    rowSum[i]--;\n                    colSum[j]--;\n                    if (i == j) dig1--;\n                    if (i + j == 2) dig2--;\n                }\n                if (rowSum[i] == 3) winX++;\n                if (colSum[j] == 3) winX++;\n                if (dig1 == 3) winX++;\n                if (dig2 == 3) winX++;\n                if (rowSum[i] == -3) winO++;\n                if (colSum[j] == -3) winO++;\n                if (dig1 == -3) winO++;\n                if (dig2 == -3) winO++;\n                if (winX > 0 && winO > 0) return false;\n            }\n        }\n        \n        if (winX > 0) {\n            if (numX != numO + 1) return false;\n        } else if (winO > 0) {\n            if (numX != numO) return false;\n        }\n        if (numO > numX || numX - numO >= 2) return false;\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/801-810/Bricks Falling When Hit.cpp",
    "content": "class UF {\n    \nprivate:\n    vector<int> parent;\n    vector<int> rank;\n    vector<int> size;\n    int N;\n    \npublic:\n    \n    UF(int N) : parent(N), rank(N, 0), size(N, 1), N(N) {\n        for (int i = 0; i < N; i++) {\n            parent[i] = i;\n        }\n    }\n    \n    int find(int p) {\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];    // path compression by halving\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    int getSize(int p) {\n        return size[find(p)];\n    }\n    \n    void Union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rootP == rootQ) return;\n        \n        // make root of smaller rank point to root of larger rank\n        if (rank[rootP] < rank[rootQ])  { parent[rootP] = rootQ; size[rootQ] += size[rootP]; }\n        else if (rank[rootP] > rank[rootQ]) { parent[rootQ] = rootP; size[rootP] += size[rootQ]; }\n        else {\n            parent[rootQ] = rootP;\n            size[rootP] += size[rootQ];\n            rank[rootP]++;\n        }\n    }\n};\n\nclass Solution {\n    \npublic:\n    vector<int> hitBricks(vector<vector<int>>& grid, vector<vector<int>>& hits) {\n        int m = grid.size();\n        int n = grid.front().size();\n        int root = m * n;\n        UF uf (m*n+1);\n        vector<vector<int>> gridCopy(grid);\n        for (const vector<int>& hit : hits) {\n            gridCopy[hit[0]][hit[1]] = 0;\n        }\n        pair<int, int> pos[4] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};\n        \n        for (int i = 0; i < n; i++) {\n            if (gridCopy[0][i] == 1) {\n                uf.Union(root, i);\n            }\n        }\n        \n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                if (gridCopy[i][j] == 0) continue;\n                for (auto it : pos) {\n                    int ni = i + it.first;\n                    int nj = j + it.second;\n                    if (ni < 0 || ni >= m || nj < 0 || nj >= n || gridCopy[ni][nj] == 0) continue;\n                    uf.Union(i*n+j, ni*n+nj);\n                }\n            }\n        }\n        \n        vector<int> ans(hits.size(), 0);\n        for (int k = hits.size() - 1; k >= 0; k--) {\n            int x = hits[k][0];\n            int y = hits[k][1];\n            if (grid[x][y] == 0) continue;\n            int count = uf.getSize(root);\n            for (auto it : pos) {\n                int nx = x + it.first;\n                int ny = y + it.second;\n                if (nx < 0 || nx >= m || ny < 0 || ny >= n || gridCopy[nx][ny] == 0) continue;\n                uf.Union(x*n+y, nx*n+ny);\n            }\n            if (x == 0) uf.Union(root, y);\n            gridCopy[x][y] = 1;\n            ans[k] = max(0, uf.getSize(root) - count - 1);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/801-810/Chalkboard XOR Game.cpp",
    "content": "class Solution {\npublic:\n    bool xorGame(vector<int>& nums) {\n        int x = 0;\n        for (int v : nums) x ^= v;\n        return x == 0 || nums.size() % 2 == 0;\n    }\n};\n"
  },
  {
    "path": "cpp/801-810/Expressive Words.cpp",
    "content": "class Solution {\npublic:\n    int expressiveWords(string S, vector<string>& words) {\n        int ans = 0;\n        int ls = S.length();\n        for (const string& word : words) {\n            int i(0), j(0);\n            int lw = word.length();\n            bool ok = true;\n            while (i < ls && j < lw) {\n                if (S[i] != word[j]) {\n                    ok = false;\n                    break;\n                }\n                int numS = 1, numW = 1;\n                while (i+1 < ls && S[i] == S[i+1]) {\n                    numS++;\n                    i++;\n                }\n                while (j+1 < lw && word[j] == word[j+1]) {\n                    numW++;\n                    j++;\n                }\n                if (numS < numW) {\n                    ok = false;\n                    break;\n                }\n                if (numS > numW && numS < 3) {\n                    ok = false;\n                    break;\n                }\n                i++;\n                j++;\n            }\n            if (ok && i == ls && j == lw) ans++;\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/801-810/Find Eventual Safe States.cpp",
    "content": "class Solution {\n    \n    bool dfs(int i, const vector<vector<int>>& graph, vector<int>& colors) {\n        if (colors[i] == 2) return true;\n        if (colors[i] == 1) return false;\n        \n        colors[i] = 1;\n        for (int v : graph[i]) {\n            if (!dfs(v, graph, colors)) {\n                return false;  \n            }\n        }\n        \n        colors[i] = 2;\n        return true;\n    }\n    \npublic:\n    vector<int> eventualSafeNodes(vector<vector<int>>& graph) {\n        int n = graph.size();\n        vector<int> colors(n, 0);\n        vector<int> ans;\n        \n        for (int i = 0; i < graph.size(); i++) {\n            if (dfs(i, graph, colors)) {\n                ans.push_back(i);\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/801-810/Max Increase to Keep City Skyline.cpp",
    "content": "class Solution {\npublic:\n    int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) {\n        int n = grid.size();\n        vector<int> col(n, 0), row(n, 0);\n        for (int i = 0; i < n; i++) {\n            for (int j = 0; j < n; j++) {\n                row[i] = max(row[i], grid[i][j]);\n                col[j] = max(col[j], grid[i][j]);\n            }\n        }\n        int res = 0;\n        for (int i = 0; i < n; i++)\n            for (int j = 0; j < n; j++)\n                res += min(row[i], col[j]) - grid[i][j];\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/801-810/Minimum Swaps To Make Sequences Increasing.cpp",
    "content": "class Solution {\npublic:\n    int minSwap(vector<int>& A, vector<int>& B) {\n        // int nswap (no swap), swap\n        // if size == 1, at the beginning, it must be true.\n        int nswap = 0, swap = 1;\n        \n        for (int i = 1; i < A.size(); i++) {\n            int temp_nswap = INT_MAX, temp_swap = INT_MAX;\n            if (A[i] > A[i-1] && B[i] > B[i-1]) {\n                temp_nswap = nswap;\n                temp_swap = swap + 1;\n            }\n            \n            if (A[i] > B[i-1] && B[i] > A[i-1]) {\n                temp_nswap = min(temp_nswap, swap);\n                temp_swap = min(temp_swap, nswap + 1);\n            }\n            \n            nswap = temp_nswap;\n            swap = temp_swap;\n        }\n        \n        return min(nswap, swap);\n    }\n};\n"
  },
  {
    "path": "cpp/801-810/Number of Lines To Write String.cpp",
    "content": "class Solution {\npublic:\n    vector<int> numberOfLines(vector<int>& widths, string S) {\n        int res = 1, cur = 0;\n        for (char c : S) {\n            int width = widths[c - 'a'];\n            res = cur + width > 100 ? res + 1 : res;\n            cur = cur + width > 100 ? width : cur + width;\n        }\n        return {res, cur};\n    }\n};\n"
  },
  {
    "path": "cpp/801-810/Soup Servings.cpp",
    "content": "class Solution {\n    \n    double dfs(int A, int B, map<pair<int, int>, double>& mymap) {\n        if (A <= 0 && B > 0) return 1;\n        if (A <= 0 && B <= 0) return 0.5;\n        if (B <= 0) return 0;\n        \n        pair<int, int> mypair = make_pair(A, B);\n        if (mymap.count(mypair)) {\n            return mymap[mypair];\n        }\n        \n        double res = 0.25 * (dfs(A-4, B, mymap) + dfs(A-3, B-1, mymap) + dfs(A-2, B-2, mymap) + dfs(A-1, B-3, mymap));\n        return mymap[mypair] = res;\n    }\n    \npublic:\n    double soupServings(int N) {\n        N = (N + 24)/25;\n        if (N >= 200) return 1.0;\n        map<pair<int, int>, double> mymap;\n        return dfs(N, N, mymap);\n    }\n};\n"
  },
  {
    "path": "cpp/801-810/Unique Morse Code Words.cpp",
    "content": "class Solution {\npublic:\n    int uniqueMorseRepresentations(vector<string>& words) {\n        vector<string> d = {\".-\", \"-...\", \"-.-.\", \"-..\", \".\", \"..-.\", \"--.\", \"....\", \"..\", \".---\", \"-.-\", \".-..\", \"--\", \"-.\", \"---\", \".--.\", \"--.-\", \".-.\", \"...\", \"-\", \"..-\", \"...-\", \".--\", \"-..-\", \"-.--\", \"--..\"};\n        set<string> s;\n        for (const auto& word : words) {\n            string code;\n            for (auto c : word) code += d[c - 'a'];\n            s.insert(code);\n        }\n        return s.size();\n    }\n};\n"
  },
  {
    "path": "cpp/811-820/Ambiguous Coordinates.cpp",
    "content": "class Solution {\n    \n    // 1.0 -> false\n    // 0001 -> false\n    // 0.0\n    bool valid(const string& str) {\n        string part1(str), part2;\n        int idx = str.find('.');\n        if (idx >= 0) {\n            part1 = str.substr(0, idx);\n            part2 = str.substr(idx + 1);\n        }\n        \n        if (part1.length() != to_string(stol(part1)).length()) return false;\n        if (part2.length() > 0) {\n            if (stol(part2) == 0) return false;\n            reverse(part2.begin(), part2.end());\n            if (part2.length() != to_string(stol(part2)).length()) return false;\n        }\n        \n        return true;\n    }\n    \n    // Given a string, return all possible results\n    // 123 -> [1.23, 12.3, 123]\n    vector<string> make(const string& str) {\n        vector<string> result;\n        for (int i = 1; i < str.length(); i++) {\n            string temp(str);\n            temp.insert(i, 1, '.');\n            if (valid(temp))\n                result.push_back(temp);\n        }\n        if (valid(str)) result.push_back(str);\n        return result;\n    }\n    \npublic:\n    vector<string> ambiguousCoordinates(string S) {\n        vector<string> result;\n        int len = S.length();\n        for (int i = 1; i < S.length() - 2; i++) {\n            string leftStr = S.substr(1, i);\n            string rightStr = S.substr(i+1, len - 2 - i);\n            \n            vector<string> left = make(leftStr);\n            vector<string> right = make(rightStr);\n            \n            for (const string& ls : left) {\n                for (const string& rs : right) {\n                    string ans = \"(\"  + ls + \", \" + rs + \")\";\n                    result.push_back(ans);\n                }\n            }\n        }\n        return result;\n    }\n};\n"
  },
  {
    "path": "cpp/811-820/Binary Tree Pruning.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode* pruneTree(TreeNode* root) {\n        if (!root) return nullptr;\n        root->left = pruneTree(root->left);\n        root->right = pruneTree(root->right);\n        if(root->left || root->right || root->val == 1) return root;\n        return nullptr;\n    }\n};\n"
  },
  {
    "path": "cpp/811-820/Bus Routes.cpp",
    "content": "class Solution {\npublic:\n    int numBusesToDestination(vector<vector<int>>& routes, int S, int T) {\n        unordered_map<int, unordered_set<int>> to_routes;\n        for (int i = 0; i < routes.size(); ++i) for (auto& j : routes[i]) to_routes[j].insert(i);\n        queue<pair<int, int>> bfs;\n        bfs.push(make_pair(S, 0));\n        unordered_set<int> seen = {S};\n        while (!bfs.empty()) {\n            int stop = bfs.front().first;\n            int bus = bfs.front().second;\n            bfs.pop();\n            if (stop == T) return bus;\n            for (const auto& route_i : to_routes[stop])\n                for (int next_stop : routes[route_i])\n                    if (seen.find(next_stop) == seen.end()) {\n                        seen.insert(next_stop);\n                        bfs.push(make_pair(next_stop, bus + 1));\n                    }\n        }\n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/811-820/Largest Sum of Averages.cpp",
    "content": "class Solution {\npublic:\n    double largestSumOfAverages(vector<int>& A, int K) {\n        int n = A.size();\n        vector<vector<double>> dp(n+1, vector<double>(K+1, 0));\n        \n        for (int i = 1; i <= n; i++) {\n            for (int j = 1; j <= K; j++) {\n                int temp = 0;\n                for (int v = i - 1; v >= 0; v--) {\n                    temp += A[v];\n                    int numElement = i - v;\n                    if (i - numElement < j - 1 || (i - numElement > 0 && j - 1 <= 0)) continue;\n                    dp[i][j] = max(dp[i][j], dp[i - numElement][j-1] + 1.0*temp/numElement);\n                }\n            }\n        }\n        \n        return dp[n][K];\n    }\n};\n"
  },
  {
    "path": "cpp/811-820/Linked List Components.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    int numComponents(ListNode* head, vector<int>& G) {\n        set<int> myset(G.begin(), G.end());\n        int ans = 0;\n        bool flag = false;\n        \n        while (head) {\n            int v = head->val;\n            if (myset.count(v) > 0) {\n                if (!flag) {\n                    flag = true;\n                }\n            } else {\n                if (flag) {\n                    ans++;\n                }\n                flag = false;\n            }\n            \n            head = head->next;\n        }\n        if (flag) ans++;\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/811-820/Most Common Word.cpp",
    "content": "class Solution {\npublic:\n    string mostCommonWord(string paragraph, vector<string>& banned) {\n        unordered_set<string> ban(banned.begin(), banned.end());\n        unordered_map<string, int> count;\n        for (auto & c: paragraph) c = isalpha(c) ? tolower(c) : ' ';\n        istringstream iss(paragraph);\n        string w, res;\n        int c = 0;\n        while (iss >> w) {\n            if (ban.find(w) == ban.end() && ++count[w] > c) {\n                res = w;\n                c = count[w];\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/811-820/Race Car.cpp",
    "content": "class Solution {\n    \n    int reverseSpeed(int speed) {\n        return speed > 0 ? -1 : 1;\n    }\n    \npublic:\n    // (pos, speed) determines current state\n    int racecar(int target) {\n        // {pos, speed}\n        unordered_set<string> visited;\n        queue<pair<int, int>> myqueue;\n        myqueue.push({0, 1});\n        visited.insert(\"0.1\");\n        int level = 0;\n        \n        while (!myqueue.empty()) {\n            \n            int mysize = myqueue.size();\n            \n            for (int i = 0; i < mysize; i++) {\n                pair<int, int> cur = myqueue.front();\n                myqueue.pop();\n                if (cur.first == target) {\n                    return level;\n                }\n\n                pair<int, int> first = make_pair(cur.first + cur.second, cur.second*2);\n                pair<int, int> second = make_pair(cur.first, reverseSpeed(cur.second));\n                string key1 = to_string(first.first) + \".\" + to_string(first.second);\n                string key2 = to_string(second.first) + \".\" + to_string(second.second);\n                \n                if (first.first >= 0 && first.first <= 2*target && visited.count(key1) == 0) {\n                    visited.insert(key1);\n                    myqueue.emplace(first);\n                }\n                if (second.first >= 0 && second.first <= 2*target && visited.count(key2) == 0) {\n                    visited.insert(key2);\n                    myqueue.emplace(second);\n                }\n            }\n            level++;\n        }\n        \n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/811-820/Short Encoding of Words.cpp",
    "content": "struct TrieNode {\n    TrieNode *nodes[26];\n    // Initialize your data structure here.\n    TrieNode() {\n        memset(nodes, 0, sizeof(nodes));\n    }\n};\n\nclass Trie {\npublic:\n    Trie() {\n        root = new TrieNode();\n    }\n    \n    // Inserts a word into the trie.\n    void insert(const string& s) {\n        TrieNode *tmp = root;\n        for(char ch : s) {\n            int index = ch - 'a';\n            if(tmp->nodes[index] == nullptr) {\n                tmp->nodes[index] = new TrieNode();\n            }\n            tmp = tmp->nodes[index];\n        }\n    }\n    \n    int getWordLen() {\n        return _getWordLen(root, 0);\n    }\n    \nprivate:\n    TrieNode* root;\n    \n    int _getWordLen(TrieNode* root, int depth) {\n        if (!root) return 0;\n        int ans = 0;\n        for (TrieNode* child : root->nodes) {\n            ans += _getWordLen(child, depth+1);\n        }\n        if (ans == 0) return depth + 1;\n        return ans;\n    }\n};\n\nclass Solution {\npublic:\n    int minimumLengthEncoding(vector<string>& words) {\n        Trie trie;\n        for (string str : words) {\n            reverse(str.begin(), str.end());\n            trie.insert(str);\n        }\n        \n        return trie.getWordLen();\n    }\n};\n"
  },
  {
    "path": "cpp/811-820/Subdomain Visit Count.cpp",
    "content": "class Solution {\npublic:\n    vector<string> subdomainVisits(vector<string>& cpdomains) {\n        unordered_map<string, int> m; \n\n        for (const auto& word : cpdomains)  {\n            int i = word.find (\" \"); \n            int n = stoi(word.substr (0, i)); \n            string s = word.substr (i+1, word.size ()-i-1);\n\n            for (int i = s.size ()-1; i >= 0; i--) {\n                if (s[i] == '.') m[s.substr (i+1, s.size ()-i-1)] += n; \n                else if (i == 0) m[s.substr (i,   s.size ()-i)  ] += n;\n            }\n        }\n\n        vector<string> v;\n        for (const auto& e : m) v.push_back (to_string (e.second) + \" \" + e.first);\n        return v;\n    }\n};\n"
  },
  {
    "path": "cpp/821-830/Binary Trees With Factors.cpp",
    "content": "class Solution {\npublic:\n    int numFactoredBinaryTrees(vector<int>& A) {\n        map<int, long> mymap;\n        sort(A.begin(), A.end());\n        unordered_set<int> myset(A.begin(), A.end());\n        \n        int mod = 1000000007;\n        long ans = 0;\n        \n        for (int i = 0; i < A.size(); i++) {\n            long temp = 1;\n            for (int j = 0; j < i; j++) {\n                if (A[i] % A[j] == 0) {\n                    int divide = A[i] / A[j];\n                    if (myset.count(divide) > 0) {\n                        long left = mymap[A[j]];\n                        long right = mymap[divide];\n                        temp += (left*right) % mod;\n                        temp = temp % mod;\n                    }\n                }\n            }\n            mymap[A[i]] = temp;\n            ans += mymap[A[i]];\n            ans %= mod;\n        }\n    \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/821-830/Card Flipping Game.cpp",
    "content": "class Solution {\npublic:\n    int flipgame(vector<int>& fronts, vector<int>& backs) {\n        unordered_set<int> same;\n        for (int i = 0; i < fronts.size(); ++i)\n            if (fronts[i] == backs[i])\n                same.insert(fronts[i]);\n\n        int ans = 2001;\n\n        for (int x: fronts)\n            if (same.count(x) == 0)\n                ans = min(ans, x);\n\n        for (int x: backs)\n            if (same.count(x) == 0)\n                ans = min(ans, x);\n\n        return ans % 2001;\n    }\n};\n"
  },
  {
    "path": "cpp/821-830/Consecutive Numbers Sum.cpp",
    "content": "class Solution {\npublic:\n    int consecutiveNumbersSum(int N) {\n        int ans = 1;\n        for (int i = 2; i * (i + 1) / 2 <= N; ++i) {\n            if ((N - i * (i + 1) / 2) % i == 0) ++ans;\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/821-830/Friends Of Appropriate Ages.cpp",
    "content": "class Solution {\npublic:\n    int numFriendRequests(vector<int>& ages) {\n        unordered_map<int, int> count;\n        for (int age : ages) count[age]++;\n        int res = 0;\n        for (const auto &a: count) {\n            for (const auto &b: count) {\n                if (request(a.first, b.first)) {\n                    res += a.second * (b.second - (a.first == b.first ? 1 : 0));\n                }\n            }\n        }\n        return res;\n    }\n\n    bool request(int a, int b) {\n        return !(b <= 0.5 * a + 7 || b > a || (b > 100 && a < 100));\n    }\n};\n"
  },
  {
    "path": "cpp/821-830/Goat Latin.cpp",
    "content": "class Solution {\npublic:\n    string toGoatLatin(string S) {\n        stringstream iss(S), oss;\n        string vowels(\"aeiouAEIOU\"), word, a;\n        while (iss >> word) {\n            a.push_back('a');\n            if (vowels.find(word[0]) != string::npos) // begin with a vowel\n                oss << word;\n            else // begin with a consonant\n                oss << word.substr(1) << word[0];\n            oss << \"ma\" << a << ' ';\n        }\n        string res = oss.str();\n        res.pop_back();\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/821-830/Making A Large Island.cpp",
    "content": "class Solution {\n    \n    int dfs(pair<int, int> pos, const pair<int, int>& root, const vector<vector<int>>& grid, map<pair<int, int>, pair<int, int>>& roots) {\n        roots[pos] = root;\n        \n        int m = grid.size();\n        int n = grid.front().size();\n        \n        pair<int, int> xys[4] = {{1,0}, {-1,0}, {0,1}, {0,-1}};\n        int area = 1;\n        for (int i = 0; i < 4; i++) {\n            int ni = pos.first + xys[i].first;\n            int nj = pos.second + xys[i].second;\n            if (ni < 0 || ni >= m || nj < 0 || nj >= n) continue;\n            if (grid[ni][nj] == 0) continue;\n            if (roots.find({ni, nj}) != roots.end()) continue;\n            area += dfs(make_pair(ni, nj), root, grid, roots);\n        }\n        return area;\n    }\n    \npublic:\n    int largestIsland(vector<vector<int>>& grid) {\n        map<pair<int, int>, int> areas; // coordinate -> area\n        map<pair<int, int>, pair<int, int>> roots;\n        \n        int m = grid.size();\n        int n = grid.front().size();\n        int ans = 0;\n        \n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                if (grid[i][j] == 0) continue;\n                pair<int, int> cur = make_pair(i, j);\n                if (roots.find(cur) == roots.end()) {\n                    int area = dfs(cur, cur, grid, roots);\n                    areas[cur] = area;\n                    ans = max(ans, area);\n                }\n            }\n        }\n        \n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                if (grid[i][j] == 0) {\n                    set<pair<int, int>> used;\n                    pair<int, int> xys[4] = {{1,0}, {-1,0}, {0,1}, {0,-1}};\n                    int area = 1;\n                    for (int k = 0; k < 4; k++) {\n                        int ni = i + xys[k].first;\n                        int nj = j + xys[k].second;\n                        if (ni < 0 || ni >= m || nj < 0 || nj >= n) continue;\n                        if (grid[ni][nj] == 0) continue;\n                        pair<int, int> curRoot = roots[make_pair(ni, nj)];\n                        if (used.count(curRoot) == 0) {\n                            used.insert(curRoot);\n                            area += areas[curRoot];\n                        }\n                    }\n                    ans = max(ans, area);\n                }\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/821-830/Most Profit Assigning Work.cpp",
    "content": "class Solution {\npublic:\n    int maxProfitAssignment(vector<int>& difficulty, vector<int>& profit, vector<int>& worker) {\n        vector<pair<int,int>> jobs;\n        int N = profit.size(), res = 0, i = 0, maxp = 0;\n        for (int j = 0; j < N; ++j) jobs.push_back(make_pair(difficulty[j], profit[j]));\n        sort(jobs.begin(), jobs.end());\n        sort(worker.begin(), worker.end());\n        for (int ability : worker) {\n            while (i < N && ability >= jobs[i].first) maxp = max(jobs[i++].second, maxp);\n            res += maxp;\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/821-830/Positions of Large Groups.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> largeGroupPositions(string S) {\n        vector<vector<int>> ans;\n        \n        for (int i = 0; i < S.size(); ++i) {\n            int begin = i;\n            int count = 1;\n            \n            while (i + 1 < S.size() && S[i] == S[i + 1]) ++i, ++count;\n            \n            if (count >= 3)\n                ans.push_back({begin, begin + count - 1});\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/821-830/Shortest Distance to a Character.cpp",
    "content": "// Time Complexity: O(n)\n// Space COmplexity: O(n)\n\nclass Solution {\npublic:\n    vector<int> shortestToChar(string S, char C) {\n        vector<int> ans(S.length(), 0);\n        int previous = -1;\n        for (int i = 0; i < S.length(); i++) {\n            if (S[i] == C) previous = i;\n            ans[i] = previous < 0 ? INT_MAX : i - previous;\n        }\n        \n        int next = INT_MAX;\n        for (int i = S.length() - 1; i >= 0; i--) {\n            if (S[i] == C) next = i;\n            int temp = next == INT_MAX ? INT_MAX : next - i;\n            ans[i] = min(ans[i], temp);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/821-830/Unique Letter String.cpp",
    "content": "class Solution {\npublic:\n    int uniqueLetterString(string S) {\n        int ans = 0;\n        map<char, int> lastPos, lastlastPos;\n        for (int i = 0; i < 128; i++) { lastPos[i] = lastlastPos[i] = -1; }\n        int tmp = 0;\n        \n        for (int i = 0; i < S.length(); i++) {\n            char ch = S[i];\n            if (lastPos[ch] < 0) {\n                // ....A  we should add the previous\n                tmp += (i - lastPos[ch]);\n            } else {\n                // A...A....A  we should add the second half and remove the first half\n                tmp += (i - lastPos[ch]);\n                tmp -= (lastPos[ch] - lastlastPos[ch]);\n                lastlastPos[ch] = lastPos[ch];\n            }\n            ans += tmp;\n            lastPos[ch] = i;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/831-840/Find And Replace in String.cpp",
    "content": "class Solution {\npublic:\n    string findReplaceString(string S, vector<int>& indexes, vector<string>& sources, vector<string>& targets) {\n        if (indexes.empty() || S.empty()) return S;\n        map<int, pair<string, string>> mymap;\n        for (int i = 0; i < indexes.size(); i++) {\n            mymap[indexes[i]] = make_pair(sources[i], targets[i]);\n        }\n        \n        stringstream ss;\n        for (int i = 0; i < S.length(); i++) {\n            if (mymap.find(i) != mymap.end()) {\n                string s = mymap[i].first;\n                string t = mymap[i].second;\n                if (i + s.length() > S.length()) {\n                    ss << S[i];\n                } else {\n                    string temp = S.substr(i, s.length());\n                    if (temp == s) {\n                        ss << t;\n                        i += (s.length() - 1);\n                    } else {\n                        ss << S[i];\n                    }\n                }\n            } else {\n                ss << S[i];\n            }\n        }\n        return ss.str();\n    }\n};\n"
  },
  {
    "path": "cpp/831-840/Flipping an Image.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {\n        if (A.empty() || A.front().empty()) return A;\n        for (auto& v : A) reverse(v.begin(), v.end());\n        for (auto& v : A) {\n            for (int& e : v) {\n                e = 1 - e;\n            }\n        }\n        return A;\n    }\n};\n"
  },
  {
    "path": "cpp/831-840/Image Overlap.cpp",
    "content": "class Solution {\npublic:\n    int largestOverlap(vector<vector<int>>& A, vector<vector<int>>& B) {\n        if (A.empty() || A.front().empty()) {\n            return 0;\n        }\n        \n        int n = A.size();\n        int res = 0;\n        for (int i = 1 - n; i <= n -1; i++) {\n            for (int j = 1-n; j <= n-1; j++) {\n                int cur = 0;\n                for (int k = max(i, 0); k < min(i + n, n); k++) {\n                    for (int l = max(j, 0); l < min(j + n, n); l++) {\n                        if (A[k -i][l - j] == 1 && B[k][l] == 1) {\n                            cur ++;\n                        }\n                    }\n                }\n                res = max(res, cur);\n            }\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/831-840/Magic Squares In Grid.cpp",
    "content": "class Solution {\n    \n    bool validate(int i, int j, vector<vector<int>>& grid) {\n        if (i + 2 >= grid.size() || j + 2 >= grid.front().size()) return false;\n        int sum1 = grid[i][j] + grid[i][j+1] + grid[i][j+2];\n        int sum2 = grid[i+1][j] + grid[i+1][j+1] + grid[i+1][j+2];\n        int sum3 = grid[i+2][j] + grid[i+2][j+1] + grid[i+2][j+2];\n        int sum4 = grid[i][j] + grid[i+1][j] + grid[i+2][j];\n        int sum5 = grid[i][j+1] + grid[i+1][j+1] + grid[i+2][j+1];\n        int sum6 = grid[i][j+2] + grid[i+1][j+2] + grid[i+2][j+2];\n        int sum7 = grid[i][j] + grid[i+1][j+1] + grid[i+2][j+2];\n        int sum8 = grid[i][j+2] + grid[i+1][j+1] + grid[i+2][j];\n        set<int> myset{grid[i][j], grid[i][j+1], grid[i][j+2], grid[i+1][j], grid[i+1][j+1], grid[i+1][j+2], grid[i+2][j], grid[i+2][j+1], grid[i+2][j+2]};\n        if (myset.size() != 9) return false;\n        if (*myset.begin() != 1) return false;\n        if (*myset.rbegin() != 9) return false;\n        if (sum1 != sum2) return false;\n        if (sum1 != sum3) return false;\n        if (sum1 != sum4) return false;\n        if (sum1 != sum5) return false;\n        if (sum1 != sum6) return false;\n        if (sum1 != sum7) return false;\n        if (sum1 != sum8) return false;\n        return true;\n    }\n    \npublic:\n    int numMagicSquaresInside(vector<vector<int>>& grid) {\n        int ans = 0;\n        if (grid.empty() || grid.front().empty()) return 0;\n        int m = grid.size();\n        int n = grid.front().size();\n        \n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                if (validate(i, j, grid)) {\n                    ans++;\n                }\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/831-840/Masking Personal Information.cpp",
    "content": "class Solution {\n    \n    string processEmail(string& S) {\n        for (int i = 0; i < S.length(); i++) S[i] = tolower(S[i]);\n        int index = S.find('@');\n        string ans;\n        ans.push_back(S[0]);\n        ans += \"*****\" + S.substr(index-1);\n        return ans;\n    }\n    \n    string processPhone(const string& S) {\n        string filterS;\n        for (char ch : S) if (isdigit(ch)) filterS += ch;\n        string ans;\n        int num = filterS.length() - 10;\n        if (num > 0) {\n            ans += '+';\n            ans += string(num, '*');\n            ans += '-';\n        }\n        ans += \"***-***-\";\n        ans += filterS.substr(filterS.length() - 4);\n        return ans;\n    }\n    \npublic:\n    string maskPII(string S) {\n        if (S.find('@') != string::npos) {\n            return processEmail(S);\n        } else {\n            return processPhone(S);\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/831-840/New 21 Game.cpp",
    "content": "class Solution {\npublic:\n    // dp[i]: probability of get points i\n    // dp[i] = sum(last W dp values) / W\n    double new21Game(int N, int K, int W) {\n        if (K == 0 || N >= K + W) return 1.0;\n        vector<double> dp(N + 1);\n        dp[0] = 1.0;\n        double Wsum = 1.0, res = 0.0;\n        for (int i = 1; i <= N; ++i) {\n            dp[i] = Wsum / W;\n            if (i < K) Wsum += dp[i]; else res += dp[i];\n            if (i - W >= 0) Wsum -= dp[i - W];\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/831-840/Push Dominoes.cpp",
    "content": "class Solution {\npublic:\n    // 'R......R' => 'RRRRRRRR'\n    // 'R......L' => 'RRRRLLLL' or 'RRRR.LLLL'\n    // 'L......R' => 'L......R'\n    // 'L......L' => 'LLLLLLLL'\n    string pushDominoes(string dominoes) {\n        dominoes = 'L' + dominoes + 'R';\n        string res = \"\";\n        for (int i = 0, j = 1; j < dominoes.length(); ++j) {\n            if (dominoes[j] == '.') continue;\n            int middle = j - i - 1;\n            if (i > 0) res += dominoes[i];\n            if (dominoes[i] == dominoes[j]) res += string(middle, dominoes[i]);\n            else if (dominoes[i] == 'L' && dominoes[j] == 'R') res += string(middle, '.');\n            else res += string(middle / 2, 'R') + string(middle % 2,'.') + string(middle / 2, 'L');\n            i = j;\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/831-840/Rectangle Overlap.cpp",
    "content": "class Solution {\n    int overlapLen(int a1, int a2, int b1, int b2) {\n        if (a1 > b1) return overlapLen(b1, b2, a1, a2);\n        int left = b1;\n        int right = min(a2, b2);\n        if (right <= left) return 0;\n        return right - left;\n    }\npublic:\n    bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) {\n        return overlapLen(rec1[0], rec1[2], rec2[0], rec2[2]) > 0 && overlapLen(rec1[1], rec1[3], rec2[1], rec2[3]) > 0;\n    }\n};\n"
  },
  {
    "path": "cpp/831-840/Similar String Groups.cpp",
    "content": "class UF {\n    \nprivate:\n    vector<int> parent;\n    vector<int> rank;\n    int count;\n    int N;\n    \npublic:\n    \n    UF(int N) : parent(N), rank(N, 0), N(N), count(N) {\n        for (int i = 0; i < N; i++) {\n            parent[i] = i;\n        }\n    }\n    \n    int find(int p) {\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];    // path compression by halving\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    int getCount() const {\n        return count;\n    }\n    \n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    void Union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rootP == rootQ) return;\n        \n        // make root of smaller rank point to root of larger rank\n        if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;\n        else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;\n        else {\n            parent[rootQ] = rootP;\n            rank[rootP]++;\n        }\n        count--;\n    }\n};\n\nclass Solution {\n    \n    bool similar(const string &a, const string &b) {\n        int n = 0;\n        for (int i = 0; i < a.size(); i++)\n            if (a[i] != b[i] && ++n > 2)\n                return false;\n        return true;\n    }\n    \npublic:\n    int numSimilarGroups(vector<string>& A) {\n        UF uf(A.size());\n        for (int i = 0; i < A.size(); i++)\n            for (int j = i + 1; j < A.size(); j++)\n                if (similar(A[i], A[j]))\n                    uf.Union(i, j);\n        return uf.getCount();\n    }\n};\n"
  },
  {
    "path": "cpp/831-840/Sum of Distances in Tree.cpp",
    "content": "class Solution {\n    \n    int dfs(int start, vector<int>& myNodes, vector<bool>& visited, map<int, vector<int>>& graph, int level, int& res) {\n        visited[start] = true;\n        \n        int nodeNum = 1;\n        for (int neig : graph[start]) {\n            if (visited[neig]) continue;\n            nodeNum += dfs(neig, myNodes, visited, graph, level+1, res);\n        }\n        myNodes[start] = nodeNum;\n        res += level;\n        return nodeNum;\n    }\n    \n    void dfs2(int start, vector<int>& myNodes, map<int, vector<int>>& graph, vector<int>& ans, int distanceOfStart) {\n        if (ans[start] < 0) {\n            int mine = myNodes[start] - 1;\n            int other =myNodes.size() - mine - 2;\n            ans[start] = distanceOfStart + (other - mine);\n        }\n        \n        for (int neig : graph[start]) {\n            if (ans[neig] > 0) continue;\n            dfs2(neig, myNodes, graph, ans, ans[start]);\n        }\n    }\n    \npublic:\n    vector<int> sumOfDistancesInTree(int N, vector<vector<int>>& edges) {\n        map<int, vector<int>> graph;\n        \n        for (auto& edge : edges) {\n            int u = edge[0];\n            int v = edge[1];\n            graph[u].push_back(v);\n            graph[v].push_back(u);\n        }\n        \n        int distanceOfStart = 0;\n        vector<int> myNodes(N, 0);\n        vector<bool> visited(N, false);\n        dfs(0, myNodes, visited, graph, 0, distanceOfStart);\n        \n        \n        vector<int> ans(N, -1);\n        ans[0] =distanceOfStart;\n        dfs2(0, myNodes, graph, ans, distanceOfStart);\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/841-850/Backspace String Compare.cpp",
    "content": "class Solution {\n    \n    string parse(const string& str) {\n        stack<char> mystack;\n        int i = 0;\n        while (i < str.length()) {\n            if (str[i] != '#') {\n                mystack.push(str[i]);\n            } else if (!mystack.empty()){\n                mystack.pop();\n            }\n            i++;\n        }\n        string ans;\n        while (!mystack.empty()) {\n            ans += mystack.top();\n            mystack.pop();\n        }\n        return ans;\n    }\n    \npublic:\n    bool backspaceCompare(string S, string T) {\n        return parse(S) == parse(T);\n    }\n};\n"
  },
  {
    "path": "cpp/841-850/Guess the Word.cpp",
    "content": "/**\n * // This is the Master's API interface.\n * // You should not implement it, or speculate about its implementation\n * class Master {\n *   public:\n *     int guess(string word);\n * };\n */\nclass Solution {\n    \n    int similarity(string& s1, string& s2) {\n        int n = s1.length();\n        int ans = 0;\n        \n        for (int i = 0; i < n; i++) {\n            if (s1[i] == s2[i]) {\n                ans++;\n            }\n        }\n        \n        return ans;\n    }\n    \npublic:\n    void findSecretWord(vector<string>& wordlist, Master& master) {\n        vector<string> v(wordlist);\n        for (int i = 0; i < 10; i++) {\n            string candidate = v[v.size()/2];\n            int n = master.guess(candidate);\n            if (n == 6) return;\n            vector<string> temp;\n            for (int i = 0; i < v.size(); i++) {\n                if (v[i] == candidate) continue;\n                int similar = similarity(candidate, v[i]);\n                if (similar == n) temp.push_back(v[i]);\n            }\n            v = temp;\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/841-850/Hand of Straights.cpp",
    "content": "class Solution {\npublic:\n    bool isNStraightHand(vector<int>& hand, int W) {\n        map<int, int> mymap;\n        for (int e : hand) mymap[e]++;\n        \n        while (!mymap.empty()) {\n            int small = (mymap.begin())->first;\n            for (int i = 0; i < W; i++) {\n                if (mymap[small] > 0) {\n                    mymap[small]--;\n                    if (mymap[small] == 0) {\n                        mymap.erase(small);\n                    }\n                } else {\n                    return false;\n                }\n                small++;\n            }\n        }\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/841-850/Keys and Rooms.cpp",
    "content": "class Solution {\n    void dfs(int u, const vector<vector<int>>& rooms, vector<bool>& visited) {\n        for (int v : rooms[u]) {\n            if (!visited[v]) {\n                visited[v] = true;\n                dfs(v, rooms, visited);\n            }\n        }\n    }\npublic:\n    bool canVisitAllRooms(vector<vector<int>>& rooms) {\n        int n = rooms.size();\n        if (n < 2) return true;\n        vector<bool> visited(n, false);\n        visited[0] = true;\n        \n        dfs(0, rooms, visited);\n        \n        for (bool b : visited) {\n            if (!b) return false;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/841-850/Longest Mountain in Array.cpp",
    "content": "class Solution {\npublic:\n    int longestMountain(vector<int>& A) {\n        int n = A.size();\n        vector<int> dp1(n, 1);\n        vector<int> dp2(n, 1);\n        \n        for (int i = 1; i < n; i++) {\n            if (A[i] > A[i-1]) {\n                dp1[i] = dp1[i-1]+1;\n            } else {\n                dp1[i] = 1;\n            }\n        }\n        \n        for (int i = n-1; i >= 1; i--) {\n            if (A[i-1] > A[i]) {\n                dp2[i-1] = dp2[i]+1;\n            } else {\n                dp2[i-1] = 1;\n            }\n        }\n        \n        int ans = 1;\n        \n        for (int i = 0; i < n; i++) {\n            if (dp1[i] > 1 && dp2[i] > 1) {\n                ans = max(ans, dp1[i] + dp2[i] - 1);\n            }\n        }\n        \n        return ans >= 3 ? ans : 0;\n    }\n};\n"
  },
  {
    "path": "cpp/841-850/Maximize Distance to Closest Person.cpp",
    "content": "class Solution {\npublic:\n    int maxDistToClosest(vector<int>& seats) {\n        int last = -1;\n        \n        int ans = 0;\n        \n        for (int i = 0; i < seats.size(); i++) {\n            if (seats[i] == 1) {\n                if (last < 0) {\n                    ans = i;\n                } else {\n                    ans = max(ans, (i - last)/2);\n                }\n                last = i;\n            }\n        }\n        \n        ans = max(ans, (int)seats.size() - last - 1);\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/841-850/Shifting Letters.cpp",
    "content": "class Solution {\n    \n    char convert(char c, int x) {\n        return (((c-'a')+x)%26) + 'a';\n    }\n    \npublic:\n    string shiftingLetters(string S, vector<int>& shifts) {\n        for (int i = shifts.size() - 1; i >= 1; i--) {\n            shifts[i-1] += (shifts[i]%26);\n        }\n        for (int i = 0; i < S.length(); i++) {\n            S[i] = convert(S[i], shifts[i]);\n        }\n        return S;\n    }\n};\n"
  },
  {
    "path": "cpp/841-850/Shortest Path Visiting All Nodes.cpp",
    "content": "class Solution {\n    \n    int getKey(const pair<int, set<int>>& e) {\n        long key = e.first << 20;;\n        \n        for (int i = 0; i < 12; i++) {\n            if (e.second.count(i) > 0) {\n                key = key | (1 << i);\n            }\n        }\n        \n        return key;\n    }\n    \npublic:\n    int shortestPathLength(vector<vector<int>>& graph) {\n        \n        int n = graph.size();\n        int ans = INT_MAX;\n        unordered_map<int, int> cache;\n        \n        for (int i = 0; i < n; i++) {\n            set<int> unvisited;\n            \n            for (int k = 0; k < n; k++) {\n                if (k != i) unvisited.insert(k);\n            }\n            queue<pair<int, set<int>>> myqueue;\n            myqueue.push(make_pair(i, unvisited));\n            int key = getKey(make_pair(i, unvisited));\n            cache[key] = 0;\n            \n            while (!myqueue.empty()) {\n                pair<int, set<int>> cur = myqueue.front();\n                myqueue.pop();\n                int key = getKey(cur);\n                \n                if (cur.second.empty()) {\n                    ans = min(ans, cache[key]);\n                    break;\n                }\n                \n                int step = cache[key];\n                \n                for (int v : graph[cur.first]) {\n                    set<int> newUnvisited = (cur.second);\n                    newUnvisited.erase(v);\n                    pair<int, set<int>> newPair = make_pair(v, newUnvisited);\n                    int nkey = getKey(newPair);\n                    if (cache.count(nkey) > 0 && (cache[nkey] <= step + 1)) continue;\n                    cache[nkey] = step+1;\n                    myqueue.emplace(newPair);\n                }\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/841-850/Split Array into Fibonacci Sequence.cpp",
    "content": "class Solution {\n    \n    bool dfs(long n1, long n2, string& S, int pos, int l, vector<int>& ans) {\n        if (pos >= S.length()) {\n            return l >= 3;\n        }\n        long n3 = n1 + n2;\n        if (n1 > INT_MAX || n2 > INT_MAX || n3 > INT_MAX) return false;\n        string s = to_string(n3);\n        int len = s.length();\n        if (S.length() - pos < len) return false;\n        if (S.substr(pos, len) != s) return false;\n        ans.push_back(n3);\n        bool f = dfs(n2, n3, S, pos + len, l+1, ans);\n        if (f) return true;\n        ans.pop_back();\n        return false;\n    }\n    \npublic:\n    vector<int> splitIntoFibonacci(string S) {\n        vector<int> ans;\n        if (S.size() < 3) return ans;\n        int n = S.length();\n        \n        for (int len1 = 1; len1 <= min(10, n/2+1); len1++) {\n            string str1 = S.substr(0, len1);\n            if (str1[0] == '0' && len1 > 1) continue;\n            long num1 = stol(str1);\n            ans.push_back(num1);\n            for (int len2 = 1; len2 <= min(10, n/2+1); len2++) {\n                string str2 = S.substr(len1, len2);\n                if (str2[0] == '0' && len2 > 1) break;\n                long num2 = stol(str2);\n                ans.push_back(num2);\n                if (dfs(num1, num2, S, len1+len2, 2, ans)) return ans;\n                ans.pop_back();\n            }\n            ans.pop_back();\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/851-860/Buddy Strings.cpp",
    "content": "class Solution {\npublic:\n    bool buddyStrings(string A, string B) {\n        if (A.length() != B.length()) return false;\n        if (A == B && set<char>(A.begin(), A.end()).size() < A.size()) return true;\n        vector<int> dif;\n        for (int i = 0; i < A.length(); ++i) if (A[i] != B[i]) dif.push_back(i);\n        return dif.size() == 2 && A[dif[0]] == B[dif[1]] && A[dif[1]] == B[dif[0]];\n    }\n};\n"
  },
  {
    "path": "cpp/851-860/Car Fleet.cpp",
    "content": "class Solution {\npublic:\n    int carFleet(int target, vector<int>& position, vector<int>& speed) {\n        int n = position.size();\n        vector<pair<int, double>> arrays(n);\n        \n        for (int i = 0; i < n; ++i)\n            arrays[i] = make_pair(position[i], (target - position[i])*1.0 / speed[i]);\n        \n        auto cmp = [](const pair<int, double>& p1, const pair<int, double>& p2) {\n            return p1.first > p2.first;\n        };\n        sort(arrays.begin(), arrays.end(), cmp);\n\n        int ans = 0, t = 0;\n        while (t < n-1) {\n            if (arrays[t].second < arrays[t+1].second) ans++;\n            else arrays[t+1] = arrays[t];\n            t++;\n        }\n\n        return ans + (t == n-1 ? 1 : 0);\n    }\n};\n"
  },
  {
    "path": "cpp/851-860/Exam Room.cpp",
    "content": "class ExamRoom {\n    \n    set<int> taken;\n    int n;\n    \npublic:\n    ExamRoom(int N) {\n        n = N;\n    }\n    \n    int seat() {\n        if (taken.empty()) {\n            taken.insert(0);\n            return 0;\n        }\n  \n        int ans = 0;\n        int len = -1;\n\n        if (taken.count(0) == 0) {\n            len = max(len, *taken.begin());\n            ans = 0;\n        }\n\n        int prevSeat = -1;\n        for (int currentSeat : taken) {\n            if (prevSeat < 0) {\n                prevSeat = currentSeat;\n            } else {\n                // 6, 9 candidatelen = (6+9)/2 = 7 candidatelen = min(7-6, 9-7)\n                int candidatePos = (currentSeat + prevSeat) / 2;\n                int candidateLen = min(candidatePos - prevSeat, currentSeat - candidatePos);\n                if (candidateLen > len) {\n                    len = candidateLen;\n                    ans = candidatePos;\n                }\n                prevSeat = currentSeat;\n            }\n        }\n  \n        if (taken.count(n-1) == 0) {\n            int candidateLen = n - 1 - *taken.rbegin();\n            if (candidateLen > len) {\n                ans = n - 1;\n            }\n        }\n  \n        taken.insert(ans);\n  \n        return ans;\n    }\n    \n    void leave(int p) {\n        if (taken.count(p) > 0) {\n            taken.erase(p);\n        }\n    }\n};\n\n/**\n * Your ExamRoom object will be instantiated and called as such:\n * ExamRoom obj = new ExamRoom(N);\n * int param_1 = obj.seat();\n * obj.leave(p);\n */\n"
  },
  {
    "path": "cpp/851-860/K-Similar Strings.cpp",
    "content": "class Solution {\npublic:\n    int kSimilarity(string A, string B) {\n        if(A == B) return 0;\n        \n        unordered_set<string> visit;\n        queue<pair<string, int>> q;\n        \n        int n = A.size();\n        int step = 0;\n        \n        int i = 0;\n        for(; i < n; ++i) {\n            if(A[i] != B[i]) break;\n        }\n        \n        q.push({A, i});\n        visit.insert(A);\n        \n        while (!q.empty()) {\n            int size = q.size();\n            \n            for (int i = 0; i < size; ++i) {\n                string t = move(q.front().first);\n                int index = q.front().second;\n                q.pop();\n                \n                if(t == B) return step;\n                \n                while(t[index] == B[index]) ++index;\n                for(int i = index +1; i < n; ++i) {\n                    if(t[i] == B[index] && t[i] != B[i]) {\n                        swap(t[index], t[i]);\n                        \n                        if(visit.count(t) == 0) {\n                            q.push({t, index+1});\n                            visit.insert(t);\n                        }\n                        \n                        swap(t[index], t[i]);\n                    }\n                }\n                \n            }\n            \n            ++step;\n        }\n        \n        return step;\n    }\n};\n"
  },
  {
    "path": "cpp/851-860/Lemonade Change.cpp",
    "content": "class Solution {\npublic:\n    bool lemonadeChange(vector<int>& bills) {\n        map<int, int> mymap;\n        \n        for (int e : bills) {\n            if (e == 5) {\n                mymap[5]++;\n            } else if (e == 10) {\n                mymap[10]++;\n                if (mymap[5] == 0) return false;\n                mymap[5]--;\n            } else {\n                mymap[20]++;\n                int remain = 15;\n                if (mymap[10] > 0) {\n                    remain = 5;\n                    mymap[10]--;\n                }\n                \n                while (remain > 0) {\n                    if (mymap[5] > 0) {\n                        mymap[5]--;\n                        remain -= 5;\n                    } else {\n                        return false;\n                    }\n                }\n            }\n        }\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/851-860/Loud and Rich.cpp",
    "content": "class Solution {\npublic:\n    vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) {\n        unordered_map<int, vector<int>> richer2;\n        for (const auto& v : richer)\n            richer2[v[1]].push_back(v[0]);\n        vector<int> ans(quiet.size(), -1);\n        for (int i = 0; i < quiet.size(); i++) \n            dfs(i, quiet, ans, richer2);\n        return ans;\n    }\n\n    int dfs(int i, const vector<int>& quiet, vector<int>& ans, unordered_map<int, vector<int>>& richer2) {\n        if (ans[i] >= 0) return ans[i];\n        ans[i] = i;\n        for (int j : richer2[i])\n            if (quiet[ans[i]] > quiet[dfs(j, quiet, ans, richer2)])\n                ans[i] = ans[j];\n        return ans[i];\n    }\n};\n"
  },
  {
    "path": "cpp/851-860/Peak Index in a Mountain Array.cpp",
    "content": "class Solution {\npublic:\n    int peakIndexInMountainArray(vector<int>& A) {\n        for (int i = 0; i < A.size(); i++) {\n            if (A[i] > A[i+1]) {\n                return i;\n            }\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/851-860/Score of Parentheses.cpp",
    "content": "class Solution {\n    \n    int dfs(const string& S, int& i) {\n        int sum = 0;\n        \n        for (i; i < S.length(); i++) {\n            if (S[i] == '(') {\n                i++;\n                sum += dfs(S, i);\n            } else if (S[i] == ')') {\n                if (sum == 0) return 1;\n                return 2*sum;\n            }\n        }\n        \n        return sum;\n    }\n    \npublic:\n    int scoreOfParentheses(string S) {\n        int i = 0;\n        return dfs(S, i);\n    }\n};\n"
  },
  {
    "path": "cpp/861-870/Advantage Shuffle.cpp",
    "content": "class Solution {\npublic:\n    vector<int> advantageCount(vector<int>& A, vector<int>& B) {\n        multiset<int> s(begin(A), end(A));\n        for (int i = 0; i < B.size(); ++i) {\n            auto p = *s.rbegin() <= B[i] ? s.begin() : s.upper_bound(B[i]);\n            A[i] = *p;\n            s.erase(p);\n        }\n        return A;\n    }\n};\n"
  },
  {
    "path": "cpp/861-870/All Nodes Distance K in Binary Tree.cpp",
    "content": "// Solution 1: O(n) Time, O(n) Space\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    vector<int> ans;   \n    unordered_map<TreeNode*, TreeNode*> parent;  // son=>parent  \n    unordered_set<TreeNode*> visit;    //record visied node\n    \n    void findParent(TreeNode* node) {\n        if (node == nullptr) return;\n        if (node->left != nullptr) {\n            parent[node->left] = node;\n            findParent(node->left);\n        }\n        if (node->right != nullptr){\n            parent[node->right] = node;\n            findParent(node->right);\n        }\n    }\n    \n    void dfs(TreeNode* node, int K){\n        if (node == nullptr || visit.count(node) > 0) {\n            return;\n        }\n        visit.insert(node);\n        if (K == 0) {\n            ans.push_back(node->val);\n            return;\n        }\n        dfs(node->left, K-1);\n        dfs(node->right, K-1);\n        dfs(parent[node], K-1);\n    }\n    \n    vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {\n        findParent(root);\n        dfs(target, K);\n        return ans;\n    }\n};\n\n// Solution 2: O(n) Time, O(lgn) Space\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    bool FindPath(TreeNode* root, TreeNode* target, vector<bool>& paths) {\n        if (root == nullptr) {\n            return false;\n        }\n        if (target == root) {\n            return true;\n        }\n        \n        bool l = FindPath(root->left, target, paths);\n        if (l) {\n            paths.push_back(false);\n            return true;\n        }\n        bool r = FindPath(root->right, target, paths);\n        if (r) {\n            paths.push_back(true);\n            return true;\n        }\n        \n        return false;\n    }\n    \n    void FindAnswer(TreeNode* root, vector<int>& ans, int dis, int K) {\n        if (root == nullptr || dis > K) {\n            return;\n        }\n        if (dis == K) {\n            ans.push_back(root->val);\n            return;\n        }\n        FindAnswer(root->left, ans, dis + 1, K);\n        FindAnswer(root->right, ans, dis + 1, K);\n    }\n    \npublic:\n    vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {\n        vector<bool> paths;\n        FindPath(root, target, paths);\n        reverse(paths.begin(), paths.end());\n        \n        vector<int> ans;\n        for (int i = 0; i < paths.size(); i++) {\n            if (paths.size() - i == K) {\n                ans.push_back(root->val);\n            }\n            bool path = paths[i];\n            if (path == false) {\n                FindAnswer(root->right, ans, paths.size() + 1 - i, K);\n                root = root->left;\n            } else {\n                FindAnswer(root->left, ans, paths.size() + 1 - i, K);\n                root = root->right;\n            }\n        }\n        FindAnswer(root, ans, 0, K);\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/861-870/Binary Gap.cpp",
    "content": "class Solution {\npublic:\n    int binaryGap(int N) {\n        int last = -1, ans = 0;\n        for (int i = 0; i < 32; ++i)\n            if (((N >> i) & 1) > 0) {\n                if (last >= 0)\n                    ans = max(ans, i - last);\n                last = i;\n            }\n\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/861-870/Prime Palindrome.cpp",
    "content": "class Solution {\npublic:\n    int primePalindrome(int N) {\n        if (N == 1 || N == 2) return 2;\n        if (N % 2 == 0) N++;\n        long t, r = 0, d;\n \n        while (true) {\n            t = N;\n\n            while(t) {\n              r = r * 10; \n              r = r + t % 10;\n              t = t / 10;\n            }\n\n            if (r == N) {\n              d = (int)sqrt(N);\n              long c = 2;\n              for (; c <= d; c++) {\n                if (N % c == 0) break;\n              }\n              if (c == d + 1)\n                break;\n            }\n            \n            r = 0;\n            N += 2;\n        }\n        \n        return N;\n    }\n};\n"
  },
  {
    "path": "cpp/861-870/Reordered Power of 2.cpp",
    "content": "class Solution {\npublic:\n    bool reorderedPowerOf2(int N) {\n        long c = counter(N);\n        for (int i = 0; i < 32; i++)\n            if (counter(1 << i) == c) return true;\n        return false;\n    }\n\n    long counter(int N) {\n        long res = 0;\n        for (; N; N /= 10) res += pow(10, N % 10);\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/861-870/Score After Flipping Matrix.cpp",
    "content": "class Solution {\npublic:\n    int matrixScore(vector<vector<int>> A) {\n        int M = A.size(), N = A[0].size(), res = (1 << (N - 1)) * M;\n        for (int j = 1; j < N; j++) {\n            int cur = 0;\n            for (int i = 0; i < M; i++) cur += A[i][j] == A[i][0];\n            res += max(cur, M - cur) * (1 << (N - j - 1));\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/861-870/Smallest Subtree with all the Deepest Nodes.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    int maxDeep;\n    \n    int maxDepth(TreeNode* root) {\n        if(!root)\n            return 0;\n        return 1 + max(maxDepth(root->left), maxDepth(root->right));\n    }\n    \n    TreeNode* dfs(TreeNode* root, int deep) {\n        if (!root) return nullptr;\n        if (deep == maxDeep) return root;\n        \n        TreeNode* l = dfs(root->left, deep+1);\n        TreeNode* r = dfs(root->right, deep+1);\n        \n        if (l && r) return root;\n        if (l && !r) return l;\n        if (r && !l) return r;\n        return nullptr;\n    }\n    \npublic:\n    TreeNode* subtreeWithAllDeepest(TreeNode* root) {\n        if (root == nullptr) return nullptr;\n        maxDeep = maxDepth(root);\n        return dfs(root, 1);\n    }\n};\n"
  },
  {
    "path": "cpp/861-870/Transpose Matrix.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> transpose(vector<vector<int>>& A) {\n        if (A.empty()) return vector<vector<int>>();\n        int m = A.size();\n        int n = A[0].size();\n        \n        vector<vector<int>> ans (n, vector<int>(m, 0));\n        \n        for (int i = 0; i < m; i++) {\n            for (int j = 0; j < n; j++) {\n                ans[j][i] = A[i][j];\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/871-880/Implement Rand10() Using Rand7().cpp",
    "content": "// The rand7() API is already defined for you.\n// int rand7();\n// @return a random integer in the range 1 to 7\n\nclass Solution {\npublic:\n    int rand10() {\n        while (true) {\n            int n = 7 * rand7() + rand7() - 8;\n            if (n < 40) return n % 10 + 1;\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/871-880/Koko Eating Bananas.cpp",
    "content": "class Solution {\npublic:\n    int minEatingSpeed(vector<int>& piles, int H) {\n        int l = 1, r = 1e9;\n        while (l < r) {\n            int m = (l + r) / 2, total = 0;\n            for (int p : piles) total += ceil(p*1.0 / m);\n            if (total > H) l = m + 1; else r = m;\n        }\n        return l;\n    }\n};\n"
  },
  {
    "path": "cpp/871-880/Leaf-Similar Trees.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    int next(stack<TreeNode*>& mystack) {\n        while (true) {\n            TreeNode* cur = mystack.top();\n            mystack.pop();\n            if (cur->right) {\n                mystack.push(cur->right);\n            }\n            if (cur->left) {\n                mystack.push(cur->left);\n            }\n            if (!cur->left && !cur->right) {\n                return cur->val;\n            }\n        }\n    }\n    \npublic:\n    bool leafSimilar(TreeNode* root1, TreeNode* root2) {\n        stack<TreeNode*> stackOne;\n        stackOne.push(root1);\n        stack<TreeNode*> stackTwo;\n        stackTwo.push(root2);\n        \n        while (true) {\n            if (stackOne.empty() && stackTwo.empty()) {\n                return true;\n            }\n            if (!stackOne.empty() && !stackTwo.empty()) {\n                int v1 = next(stackOne);\n                int v2 = next(stackTwo);\n                if (v1 != v2) return false;\n            } else {\n                return false;\n            }\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/871-880/Length of Longest Fibonacci Subsequence.cpp",
    "content": "class Solution {\npublic:\n    int lenLongestFibSubseq(vector<int>& A) {\n        unordered_map<int, int> m;\n        int N = A.size(), res = 0;\n        int dp[N][N];\n        for (int j = 0; j < N; ++j) {\n            m[A[j]] = j;\n            for (int i = 0; i < j; ++i) {\n                int k = m.find(A[j] - A[i]) == m.end() ? -1 : m[A[j] - A[i]];\n                dp[i][j] = (A[j] - A[i] < A[i] && k >= 0) ? dp[k][i] + 1 : 2;\n                res = max(res, dp[i][j]);\n            }\n        }\n        return res > 2 ? res : 0;\n    }\n};\n"
  },
  {
    "path": "cpp/871-880/Middle of the Linked List.cpp",
    "content": "/**\n * Definition for singly-linked list.\n * struct ListNode {\n *     int val;\n *     ListNode *next;\n *     ListNode(int x) : val(x), next(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    ListNode* middleNode(ListNode* head) {\n        ListNode *slow(head), *fast(head->next);\n        \n        while (fast) {\n            slow = slow->next;\n            fast = fast->next;\n            if (fast) fast = fast->next;\n        }\n        \n        return slow;\n    }\n};\n"
  },
  {
    "path": "cpp/871-880/Stone Game.cpp",
    "content": "class Solution {\npublic:\n    bool stoneGame(vector<int>& piles) {\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/881-890/Boats to Save People.cpp",
    "content": "class Solution {\npublic:\n    int numRescueBoats(vector<int>& people, int limit) {\n        sort(people.begin(), people.end());\n        \n        int i = 0, j = people.size() - 1;\n        int ans = 0;\n        \n        while (i <= j) {\n            if (people[i] + people[j] <= limit) {\n                i++;\n            }\n            j--;\n            ans++;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/881-890/Possible Bipartition.cpp",
    "content": "class Solution {\npublic:\n    bool possibleBipartition(int N, vector<vector<int>>& dislikes) {\n        vector<int> color(N+1, 0);\n        map<int, vector<int>> al;\n        for (auto& d: dislikes) {\n            al[d[0]].push_back(d[1]);\n            al[d[1]].push_back(d[0]);\n        }\n        queue<int> q;\n        for (auto e : al) {\n            if (color[e.first] == 0) { // untouched person\n                color[e.first] = 1;\n                q.push(e.first);\n                while (!q.empty()) {\n                    int s = q.front(); q.pop();\n                    for (int x : al[s]) { // all neighbors of s\n                        if (color[x] == 0) {\n                            color[x] = 3 - color[s];\n                            q.push(x);\n                        }\n                        else if (color[x] != 3 - color[s])\n                            return false;\n                    }\n                }\n            }\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/881-890/Projection Area of 3D Shapes.cpp",
    "content": "class Solution {\npublic:\n    int projectionArea(vector<vector<int>>& grid) {\n        int ans = 0;\n        int n = grid.size();\n        \n        for (auto& v : grid) {\n            for (int v : v) {\n                ans += (v > 0);\n            }\n            ans += *(max_element(v.begin(), v.end()));\n        }\n        \n        for (int i = 0; i < n; i++) {\n            int temp = 0;\n            for (int j = 0; j < n; j++) {\n                temp = max(temp, grid[j][i]);\n            }\n            ans += temp;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/881-890/Uncommon Words from Two Sentences.cpp",
    "content": "class Solution {\npublic:\n    vector<string> uncommonFromSentences(string A, string B) {\n        unordered_map<string, int> count;\n        istringstream iss(A + \" \" + B);\n        while (iss >> A) count[A]++;\n        vector<string> res;\n        for (auto& w: count)\n            if (w.second == 1)\n                res.emplace_back(move(w.first));\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/891-900/Maximum Frequency Stack.cpp",
    "content": "class FreqStack {\n    \n    map<int, int> freq;\n    map<int, stack<int>> mystack;\n    \n    int maxFreq;\n\npublic:\n    FreqStack() {\n        maxFreq = 0;\n    }\n    \n    void push(int x) {\n        freq[x]++;\n        mystack[freq[x]].push(x);\n        maxFreq = max(freq[x], maxFreq);\n    }\n    \n    int pop() {\n        int retVal = mystack[maxFreq].top();\n        mystack[maxFreq].pop();\n        freq[retVal]--;\n        if (mystack[maxFreq].empty()) {\n            maxFreq--;\n        }\n        return retVal;\n    }\n};\n\n/**\n * Your FreqStack object will be instantiated and called as such:\n * FreqStack obj = new FreqStack();\n * obj.push(x);\n * int param_2 = obj.pop();\n */\n"
  },
  {
    "path": "cpp/911-920/Complete Binary Tree Inserter.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass CBTInserter {\n    TreeNode* myroot;\n    queue<TreeNode*> myqueue;\npublic:\n    CBTInserter(TreeNode* root) {\n        myroot = root;\n        myqueue.push(root);\n        while (true) {\n            if (myqueue.front()->left && myqueue.front()->right) {\n                myqueue.push(myqueue.front()->left);\n                myqueue.push(myqueue.front()->right);\n                myqueue.pop();\n            } else {\n                break;\n            }\n        }\n    }\n    \n    int insert(int v) {\n        TreeNode* cur = new TreeNode(v);\n        int retVal = myqueue.front()->val;\n        if (myqueue.front()->left == nullptr) {\n            myqueue.front()->left = cur;\n        } else {\n            myqueue.front()->right = cur;\n            myqueue.push(myqueue.front()->left);\n            myqueue.push(cur);\n            myqueue.pop();\n        }\n        return retVal;\n    }\n    \n    TreeNode* get_root() {\n        return myroot;\n    }\n};\n\n/**\n * Your CBTInserter object will be instantiated and called as such:\n * CBTInserter obj = new CBTInserter(root);\n * int param_1 = obj.insert(v);\n * TreeNode* param_2 = obj.get_root();\n */\n"
  },
  {
    "path": "cpp/911-920/Maximum Sum Circular Subarray.cpp",
    "content": "class Solution {\npublic:\n    int maxSubarraySumCircular(vector<int>& A) {\n        int sum = 0;\n        int cur_max = 0;\n        int max_so_far = INT_MIN;\n        int cur_min = 0;\n        int min_so_far = INT_MAX;\n        \n        for (int v : A) {\n            cur_max = max(cur_max + v, v);\n            max_so_far = max(max_so_far, cur_max);\n            cur_min = min(cur_min + v, v);\n            min_so_far = min(min_so_far, cur_min);\n            \n            sum += v;\n        }\n        \n        if (max_so_far <= 0) return max_so_far;\n        return max(max_so_far, sum - min_so_far);\n    }\n};\n"
  },
  {
    "path": "cpp/911-920/Number of Music Playlists.cpp",
    "content": "class Solution {\npublic:\n    int numMusicPlaylists(int N, int L, int K) {\n        int MOD = 1000000007;\n\n        vector<vector<long>> dp (L+1, vector<long>(N+1, 0));\n        dp[0][0] = 1;\n        for (int i = 1; i <= L; ++i)\n            for (int j = 1; j <= N; ++j) {\n                dp[i][j] += dp[i-1][j-1] * (N-j+1);\n                dp[i][j] += dp[i-1][j] * max(j-K, 0);\n                dp[i][j] %= MOD;\n            }\n\n        return dp[L][N];\n    }\n};\n"
  },
  {
    "path": "cpp/911-920/Online Election.cpp",
    "content": "class TopVotedCandidate {\npublic:\n    map<int, int> m;\n    TopVotedCandidate(vector<int> persons, vector<int> times) {\n        int n = persons.size(), lead = -1;\n        unordered_map<int, int> count;\n        for (int i = 0; i < n; ++i) m[times[i]] = persons[i];\n        for (auto it : m) {\n            if (++count[it.second] >= count[lead])lead = it.second;\n            m[it.first] = lead;\n        }\n    }\n\n    int q(int t) {\n        return (--m.upper_bound(t))-> second;\n    }\n};\n\n/**\n * Your TopVotedCandidate object will be instantiated and called as such:\n * TopVotedCandidate obj = new TopVotedCandidate(persons, times);\n * int param_1 = obj.q(t);\n */\n"
  },
  {
    "path": "cpp/911-920/Partition Array into Disjoint Intervals.cpp",
    "content": "class Solution {\npublic:\n    int partitionDisjoint(vector<int>& A) {\n        int n = A.size(), pmax = 0;\n        vector<int> B(n);\n        B[n - 1] = A[n - 1];\n        for (int i = n - 2; i > 0; --i)\n            B[i] = min(A[i], B[i + 1]);\n        for (int i = 1; i < n; ++i) {\n            pmax = max(pmax, A[i - 1]);\n            if (pmax <= B[i]) return i;\n        }\n    }\n};\n"
  },
  {
    "path": "cpp/911-920/Reverse Only Letters.cpp",
    "content": "class Solution {\npublic:\n    string reverseOnlyLetters(string S) {\n        int i = 0, j = S.length() - 1;\n        while (i < j) {\n            while (!isalpha(S[i])) i++;\n            while (!isalpha(S[j])) j--;\n            if (i < j) swap(S[i], S[j]);\n            i++;\n            j--;\n        }\n        return S;\n    }\n};\n"
  },
  {
    "path": "cpp/911-920/Word Subsets.cpp",
    "content": "class Solution {\npublic:\n    vector<string> wordSubsets(vector<string>& A, vector<string>& B) {\n        vector<int> uni(26), tmp(26);\n        int i;\n        for (const string& b : B) {\n            tmp = counter(b);\n            for (i = 0; i < 26; ++i)\n                uni[i] = max(uni[i], tmp[i]);\n        }\n        vector<string> res;\n        for (const string& a : A) {\n            tmp = counter(a);\n            for (i = 0; i < 26; ++i)\n                if (tmp[i] < uni[i]) break;\n            if (i == 26) res.push_back(a);\n        }\n        return res;\n    }\n\n    vector<int> counter(const string& word) {\n        vector<int> count(26);\n        for (char c : word) count[c - 'a']++;\n        return count;\n    }\n};\n"
  },
  {
    "path": "cpp/911-920/X of a Kind in a Deck of Cards.cpp",
    "content": "class Solution {\npublic:\n    bool hasGroupsSizeX(vector<int>& deck) {\n        map<int, int> mymap;\n        for (int e : deck) mymap[e]++;\n        int gcd = mymap[deck[0]];\n        for (const auto& e : mymap) gcd = __gcd(gcd, e.second);\n        return gcd >= 2;\n    }\n};w\n"
  },
  {
    "path": "cpp/921-930/3Sum With Multiplicity.cpp",
    "content": "class Solution {\n    \n    long MOD = 1000000007;\n    \n    long getCount(int a, int b, int c, unordered_map<int, int>& mymap) {\n        long v = 0;\n        long ta = mymap[a];\n        long tb = mymap[b];\n        long tc = mymap[c];\n        if (a == b && b == c) {\n            v = ta*(ta-1)*(ta-2)/6;\n        } else if (a == b) {\n            v = tc*tb*(tb-1)/2;\n        } else if (b == c) {\n            v = ta*tb*(tb-1)/2;\n        } else {\n            v = ta*tb*tc;\n        }\n        return v%MOD;\n    }\n    \npublic:\n    int threeSumMulti(vector<int>& A, int target) {\n        sort(A.begin(), A.end());\n        unordered_map<int, int> mymap;\n        for (int e : A) mymap[e]++;\n        long ans = 0;\n        \n        for (int i = 0; i < A.size(); i++) {\n            if (3*A[i] > target) break;\n            while (i > 0 && i < A.size() && A[i] == A[i-1]) i++;\n            for (int j = i + 1; j < A.size(); j++) {\n                while (j < A.size() && A[j] != A[i] && A[j] == A[j-1]) j++;\n                while (j > 1 && j < A.size() && A[j] == A[j-2]) j++;\n                if (j >= A.size()-1) break;\n                if (2*A[j] > target - A[i]) break;\n                int v = target - A[i] - A[j];\n                if (mymap.count(v) > 0) {\n                    ans = (ans + getCount(A[i], A[j], v, mymap)) % MOD;\n                }\n                \n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/921-930/Binary Subarrays With Sum.cpp",
    "content": "class Solution {\npublic:\n    int numSubarraysWithSum(vector<int>& A, int S) {\n        unordered_map<int, int> mymap;\n        int sum = 0;\n        int ans = 0;\n        mymap[0] = -1;\n        for (int i = 0; i < A.size(); i++) {\n            sum += A[i];\n            if (A[i] == 1) mymap[sum] = i;\n            \n            if (sum >= S) {\n                int needed = sum - S;\n                int idx2 = mymap.count(needed+1) == 0 ? i : mymap[needed+1];\n                int idx1 = mymap[needed];\n                ans += (idx2 - idx1);\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/921-930/Flip String to Monotone Increasing.cpp",
    "content": "class Solution {\npublic:\n    int minFlipsMonoIncr(string S) {\n        int rightZero = 0;\n        for (char ch : S) if (ch == '0') rightZero++;\n        \n        int ans = min(rightZero, (int)S.size() - rightZero);\n        \n        int leftOne = 0;\n        for (int i = 0; i < S.size(); i++) {\n            ans = min(ans, rightZero + leftOne);\n            if (S[i] == '1') leftOne++;\n            else rightZero--;\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/921-930/Long Pressed Name.cpp",
    "content": "class Solution {\npublic:\n    bool isLongPressedName(string name, string typed) {\n        int i = 0;\n        for (char ch : name) {\n            if (typed[i] == ch) { i++; continue; }\n            while (i > 0 && i < typed.size() && typed[i] == typed[i-1]) i++;\n            if (typed[i] == ch) { i++; continue; }\n            else return false;\n        }\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/921-930/Minimize Malware Spread.cpp",
    "content": "class Solution {\n    \n    vector<int> parents;\n    \npublic:\n    int minMalwareSpread(vector<vector<int>>& graph, vector<int>& initial) {\n        int n = graph.size();\n        for (int i = 0; i < n; ++i) parents.push_back(i);\n        for (int i = 0; i < n; ++i)\n            for (int j = i + 1; j < n; ++j)\n                if (graph[i][j]) uni(i, j);\n        vector<int> area(n, 0), malware(n, 0);\n        for (int i = 0; i < n; ++i) area[find(i)]++;\n        for (int i : initial) malware[find(i)]++;\n        int maxarea = 1, idx = initial[0];\n        for (int i : initial) {\n            if (malware[find(i)] == 1 && area[find(i)] > maxarea) {\n                maxarea = area[find(i)];\n                idx = i;\n            }\n            if (maxarea == 1) {\n                idx = min(idx, i);\n            }\n        }\n        return idx;\n    }\n\n    int find(int x) {\n        if (x != parents[x])\n            parents[x] = find(parents[x]);\n        return parents[x];\n    }\n    \n    void uni(int x, int y) {\n        parents[find(x)] = find(y);\n    }\n};\n"
  },
  {
    "path": "cpp/921-930/Minimum Add to Make Parentheses Valid.cpp",
    "content": "class Solution {\npublic:\n    int minAddToMakeValid(string S) {\n        int left = 0, ans = 0;\n        \n        for (char ch : S) {\n            if (ch == '(') {\n                left++;\n            } else {\n                if (left > 0) left--;\n                else ans++;\n            }\n        }\n        \n        return ans + left;\n    }\n};\n"
  },
  {
    "path": "cpp/921-930/Sort Array By Parity II.cpp",
    "content": "class Solution {\npublic:\n    vector<int> sortArrayByParityII(vector<int>& A) {\n        int i = 0, j = 1;\n        for (int k = 0; k < A.size(); k++) {\n            if (A[k] % 2 == 0) {\n                if (k % 2 == 0) continue;\n                swap(A[i], A[k]);\n                i += 2;\n            } else {\n                if (k % 2 == 1) continue;\n                swap(A[j], A[k]);\n                j += 2;\n            }\n            k--;\n        }\n        return A;\n    }\n};\n"
  },
  {
    "path": "cpp/921-930/Three Equal Parts.cpp",
    "content": "class Solution {\npublic:\n    vector<int> threeEqualParts(vector<int>& A) {\n        int numOfOne = 0;\n        for (int e : A) numOfOne += e;\n        \n        if (numOfOne == 0) return { 0, A.size()-1 };\n        \n        if (numOfOne % 3 != 0) return { -1, -1 };\n        \n        int expectedOne = numOfOne / 3;\n        \n        int paddingZero = 0;\n        int currentOne = 0;\n        int pos = A.size() - 1;\n        while (currentOne < expectedOne) {\n            if(A[pos] == 1) {\n                currentOne++;\n            } else {\n                if (currentOne == 0) {\n                    paddingZero++;\n                }\n            }\n            pos--;\n        }\n        \n        int currentPaddingZero = 0;\n        while (A[pos] == 0) {\n            currentPaddingZero++;\n            pos--;\n        }\n        if (currentPaddingZero < paddingZero) return { -1, -1 };\n        \n        int pos2 = pos + 1 + paddingZero;\n        \n        currentOne = 0;\n        while (currentOne < expectedOne) {\n            if(A[pos] == 1) {\n                currentOne++;\n            }\n            pos--;\n        }\n        \n        currentPaddingZero = 0;\n        while (pos >=0 && A[pos] == 0) {\n            currentPaddingZero++;\n            pos--;\n        }\n        if (currentPaddingZero < paddingZero) return { -1, -1 };\n        \n        int i = pos + paddingZero, j = pos2-1;\n        while (i >= 0 && j > pos) {\n            if (A[i] != A[j]) return { -1, -1 };\n            i--;\n            j--;\n        }\n        \n        return { pos + paddingZero, pos2 };\n    }\n};\n"
  },
  {
    "path": "cpp/921-930/Unique Email Addresses.cpp",
    "content": "class Solution {\npublic:\n    int numUniqueEmails(vector<string>& emails) {\n        set<string> uniqueEmails;\n        \n        for (string email : emails) {\n            string ans;\n            int idx = email.find('@');\n            for (char ch : email) {\n                if (ch == '.') continue;\n                if (ch == '+' || ch == '@') break;\n            }\n            ans = ans + email.substr(idx, email.size() - idx);\n            uniqueEmails.insert(ans);\n        }\n        \n        return uniqueEmails.size();\n    }\n};\n"
  },
  {
    "path": "cpp/931-940/Beautiful Array.cpp",
    "content": "class Solution {\npublic:\n    vector<int> beautifulArray(int N) {\n        vector<int> res = {1};\n        while (res.size() < N) {\n            vector<int> tmp;\n            for (int i : res) if (i * 2 - 1 <= N) tmp.push_back(i * 2 - 1);\n            for (int i : res) if (i * 2 <= N) tmp.push_back(i * 2);\n            res = tmp;\n        }\n        return res;\n    }\n};\n\n"
  },
  {
    "path": "cpp/931-940/Distinct Subsequences II.cpp",
    "content": "class Solution {\n    \npublic:\n    int distinctSubseqII(string S) {\n        // Create an array to store index of last \n        vector<int> last(256, -1);\n        int n = S.length(); \n        long dp[n+1];\n        long MOD = 1000000007;\n\n        // Empty substring has only one subsequence\n        dp[0] = 1; \n\n        for (int i = 1; i <= n; i++) { \n            dp[i] = (2*dp[i-1]) % MOD; \n\n            // If current character has appeared before, then remove all subsequences \n            // ending with previous occurrence. \n            if (last[S[i-1]] != -1) \n                dp[i] = (dp[i] + MOD - dp[last[S[i-1]]]) % MOD; \n \n            last[S[i-1]] = (i-1);\n        } \n\n        // Remove the empty string.\n        return dp[n] - 1; \n    }\n};\n"
  },
  {
    "path": "cpp/931-940/Knight Dialer.cpp",
    "content": "class Solution {\npublic:\n    int knightDialer(int N) {\n        vector<vector<long>> dp(2, vector<long>(10, 1));\n        long MOD = 1000000007;\n        for (int i = 1; i < N; i++) {\n            dp[1][0] = (dp[0][4] + dp[0][6]) % MOD;\n            dp[1][1] = (dp[0][6] + dp[0][8]) % MOD;\n            dp[1][2] = (dp[0][7] + dp[0][9]) % MOD;\n            dp[1][3] = (dp[0][4] + dp[0][8]) % MOD;\n            dp[1][4] = (dp[0][0] + dp[0][3] + dp[0][9]) % MOD;\n            dp[1][5] = 0;\n            dp[1][6] = (dp[0][0] + dp[0][1] + dp[0][7]) % MOD;\n            dp[1][7] = (dp[0][2] + dp[0][6]) % MOD;\n            dp[1][8] = (dp[0][1] + dp[0][3]) % MOD;\n            dp[1][9] = (dp[0][2] + dp[0][4]) % MOD;\n            dp[0] = dp[1];\n        }\n        \n        return accumulate(dp.front().begin(), dp.front().end(), 0l) % MOD;\n    }\n};\n"
  },
  {
    "path": "cpp/931-940/Minimum Area Rectangle.cpp",
    "content": "class Solution {\npublic:\n    int minAreaRect(vector<vector<int>>& points) {\n        set<pair<int, int>> myset;\n        for (const vector<int>& point : points) {\n            myset.insert({point[0], point[1]});\n        }\n        \n        int ans = INT_MAX;\n        \n        for (int i = 0; i < points.size(); i++) {\n            for (int j = i + 1; j < points.size(); j++) {\n                pair<int, int> a{points[i][0], points[j][1]};\n                pair<int, int> b{points[j][0], points[i][1]};\n                if (a.first != b.first && a.second != b.second &&\n                    myset.count(a) > 0 && myset.count(b) > 0) {\n                    int w = abs(a.first - b.first);\n                    int h = abs(a.second - b.second);\n                    ans = min(ans, w * h);\n                }\n            }\n        }\n        \n        return ans == INT_MAX ? 0 : ans;\n    }\n};\n"
  },
  {
    "path": "cpp/931-940/Minimum Falling Path Sum.cpp",
    "content": "class Solution {\npublic:\n    int minFallingPathSum(vector<vector<int>>& A) {\n        for (int i = 1; i < A.size(); ++i)\n            for (int j = 0; j < A.size(); ++j)\n                A[i][j] += min(A[i-1][j], min(A[i-1][max(0,j-1)], A[i-1][min((int)A.size()-1,j+1)]));\n        return *min_element(begin(A.back()), end(A.back()));\n    }\n};\n"
  },
  {
    "path": "cpp/931-940/Number of Recent Calls.cpp",
    "content": "class RecentCounter {\npublic:\n    queue<int> q;\n\n    RecentCounter() { }\n\n    int ping(int t) {\n        while (!q.empty() && q.front() < t-3000)\n            q.pop();\n    \n        q.push(t);\n        return q.size();\n    }\n};\n\n/**\n * Your RecentCounter object will be instantiated and called as such:\n * RecentCounter* obj = new RecentCounter();\n * int param_1 = obj->ping(t);\n */\n"
  },
  {
    "path": "cpp/931-940/Range Sum of BST.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    int dfs(TreeNode* root, int L, int R) {\n        if (root == nullptr) return 0;\n        int v = dfs(root->left, L, R) + dfs(root->right, L, R);\n        if (root->val >= L && root->val <= R) return v + root->val;\n        else return v;\n        \n    }\n    \npublic:\n    int rangeSumBST(TreeNode* root, int L, int R) {\n        return dfs(root, L, R);\n    }\n};\n"
  },
  {
    "path": "cpp/931-940/Reorder Log Files.cpp",
    "content": "class Solution {\npublic:\n    \n    vector<string> reorderLogFiles(vector<string>& logs) {\n        auto cmp = [](const string& l, const string& r) {\n            int lp = l.find(\" \");\n            int rp = r.find(\" \");\n            return l.substr(lp) < r.substr(rp);\n        };\n        // In-place partition\n        int left = logs.size() - 1;\n        int right = logs.size() - 1;\n        \n        while (left > -1) {\n            if (isdigit(logs[left].back())) {\n                swap(logs[left], logs[right]);\n                --right;\n            }\n            --left;\n        }\n        \n        // lexicographic order sort\n        sort(logs.begin(), logs.begin() + right + 1, cmp);\n        \n        return logs;\n    }\n};\n"
  },
  {
    "path": "cpp/931-940/Shortest Bridge.cpp",
    "content": "class Solution {\npublic:\n    int shortestBridge(vector<vector<int>>& A) {\n        int row = A.size();\n        int col = A[0].size();\n        int c, r;\n        \n        // find the first '1' (i.e. the first island) by scaning the matrix\n        for (int i = 0; i < row * col; i++) {\n            c = i % col;\n            r = i / col;\n            if (A[r][c] == 1)\n                break;\n        }\n\n        queue<pair<int,int>> q1,q2;\n        q1.push({r,c});\n        A[r][c] = -1;\n        \n        int d[][2] = {{-1,0}, {0,1}, {1,0}, {0, -1}};\n        while (!q1.empty()) {\n            auto cur = q1.front();\n            q1.pop();\n            for (int i = 0; i < 4; i++) {\n                int newr = cur.first + d[i][0];\n                int newc = cur.second + d[i][1];\n                \n                if (newr < 0 || newc < 0 || newr >= row || newc >= col) continue;\n                \n                if (A[newr][newc] == 1) {\n                    A[newr][newc] = -1;\n                    q1.push({newr, newc});\n                } else if (A[newr][newc] == 0) {\n                    A[newr][newc] = -1;\n                    q2.push({newr, newc});\n                }\n            }\n        }\n             \n        int step = 0;\n        while (!q2.empty()) {\n            auto size = q2.size();\n            step++;\n            for (int j = 0; j < size; j++) {\n                auto cur = q2.front();\n                q2.pop();\n                for (int i = 0; i < 4; i++) {\n                    int newr = cur.first + d[i][0];\n                    int newc = cur.second + d[i][1];\n\n                    if (newr < 0 || newc < 0 || newr >= row || newc >= col) continue;\n                    \n                    if (A[newr][newc] == -1) continue;\n                    \n                    if (A[newr][newc] == 1) return step;\n\n                    q2.push({newr, newc});\n                    A[newr][newc] = -1;\n                }\n            }            \n        }\n    }\n};\n"
  },
  {
    "path": "cpp/931-940/Stamping The Sequence.cpp",
    "content": "class Solution {\npublic:\n    vector<int> movesToStamp(string stamp, string target) {\n      vector<int> res;\n      int total_stamp = 0, turn_stamp = -1;\n      while (turn_stamp != 0) {\n          turn_stamp = 0;\n          for (int sz = stamp.size(); sz > 0; --sz) \n              for (int i = 0; i <= stamp.size() - sz; ++i) {\n                  string new_stamp = string(i, '*') + stamp.substr(i, sz) + string(stamp.size() - sz - i, '*');\n                  size_t pos = target.find(new_stamp);\n                  while (pos != string::npos) {\n                      res.push_back(pos);\n                      turn_stamp += sz;\n                      fill(begin(target) + pos, begin(target) + pos + stamp.size(), '*');\n                      pos = target.find(new_stamp);\n                  }\n              }\n          total_stamp += turn_stamp;\n      }\n      reverse(begin(res), end(res));\n      return total_stamp == target.size() ? res : vector<int>();\n    }\n};\n"
  },
  {
    "path": "cpp/941-950/Bag of Tokens.cpp",
    "content": "class Solution {\npublic:\n    int bagOfTokensScore(vector<int>& tokens, int P) {\n        sort(tokens.begin(), tokens.end());\n        \n        int i = 0, j = tokens.size() - 1;\n        int points = 0;\n        \n        while (true) {\n            while (i <= j && P >= tokens[i]) {\n                points++;\n                P -= tokens[i];\n                i++;\n            }\n            \n            if (i >= j || points <= 0) break;\n            \n            P += tokens[j];\n            j--;\n            points--;\n        }\n        \n        return points;\n    }\n};\n"
  },
  {
    "path": "cpp/941-950/DI String Match.cpp",
    "content": "class Solution {\npublic:\n    vector<int> diStringMatch(string S) {\n        vector<int> ans(S.size() + 1);\n        \n        int low = 0;\n        int high = S.size();\n        \n        for (int i = 0; i < S.size(); i++) {\n            if (S[i] == 'I') {\n                ans[i] = low;\n                low++;\n            } else {\n                ans[i] = high;\n                high--;\n            }\n        }\n        ans[S.size()] = low;\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/941-950/Delete Columns to Make Sorted.cpp",
    "content": "class Solution {\npublic:\n    int minDeletionSize(vector<string>& A) {\n        int res = 0;\n        if (A.empty()) return res;\n        for (int c = 0; c < A[0].size(); ++c)\n            for (int i = 1; i < A.size(); ++i) {\n                if (A[i - 1][c] > A[i][c]) {\n                    ++res;\n                    break;\n                }\n            }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/941-950/Minimum Increment to Make Array Unique.cpp",
    "content": "class Solution {\npublic:\n    int minIncrementForUnique(vector<int>& A) {\n        sort(A.begin(), A.end());\n        int res = 0, need = 0;\n        for (int a: A) {\n            res += max(need - a, 0);\n            need = max(a, need) + 1;\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/941-950/Most Stones Removed with Same Row or Column.cpp",
    "content": "class UF {\n    \nprivate:\n    vector<int> parent;\n    vector<int> rank;\n    int count;\n    int N;\n    \n    bool validate(int p) {\n        return (p >= 0 && p < N);\n    }\n    \npublic:\n    \n    UF(int N) : parent(N), rank(N, 0), N(N), count(N) {\n        for (int i = 0; i < N; i++) {\n            parent[i] = i;\n        }\n    }\n    \n    int find(int p) {\n        if (!validate(p)) return -1;\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];    // path compression by halving\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    int getCount() const {\n        return count;\n    }\n    \n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    void Union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rootP == rootQ) return;\n        \n        // make root of smaller rank point to root of larger rank\n        if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;\n        else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;\n        else {\n            parent[rootQ] = rootP;\n            rank[rootP]++;\n        }\n        count--;\n    }\n};\n\nclass Solution {\npublic:\n    int removeStones(vector<vector<int>>& stones) {\n        UF uf(20000);\n        \n        for (const vector<int>& stone: stones) {\n            uf.Union(stone[0], stone[1]+10000);\n        }\n        \n        set<int> myset;\n        for (const vector<int>& stone: stones) {\n            myset.insert(uf.find(stone[0]));\n        }\n        \n        return stones.size() - myset.size();\n    }\n};\n"
  },
  {
    "path": "cpp/941-950/Valid Mountain Array.cpp",
    "content": "class Solution {\npublic:\n    bool validMountainArray(vector<int>& A) {\n        if (A.size() < 3) return false;\n        if (A[1] <= A[0]) return false;\n        if (A[A.size()-2] <= A[A.size()-1]) return false;\n        int i = 0, j = A.size()-1;\n        while (A[i] < A[i+1]) i++;\n        while (A[j] < A[j-1]) j--;\n        return i == j;\n    }\n};\n"
  },
  {
    "path": "cpp/941-950/Validate Stack Sequences.cpp",
    "content": "class Solution {\npublic:\n    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {\n        stack<int> mystack;\n        int i = 0;\n        \n        for (int e : pushed) {\n            if (e == popped[i]) {\n                // check if we should pop more elements.\n                i++;\n                while (!mystack.empty() && mystack.top() == popped[i]) {\n                    mystack.pop();\n                    i++;\n                }\n            } else {\n                mystack.push(e);\n            }\n        }\n        \n        return mystack.empty();\n    }\n};\n"
  },
  {
    "path": "cpp/951-960/Check Completeness of a Binary Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    bool isCompleteTree(TreeNode* root) {\n        if (root == nullptr) return true;\n        queue<TreeNode*> myqueue;\n        myqueue.push(root);\n        \n        bool flag = false;\n        \n        while (!myqueue.empty()) {\n            TreeNode* node = myqueue.front();\n            myqueue.pop();\n            if (node->left) {\n                if (flag) return false;\n                myqueue.push(node->left);\n            } else {\n                flag = true;\n            }\n            \n            if (node->right) {\n                if (flag) return false;\n                myqueue.push(node->right);\n            } else {\n                flag = true;\n            }\n        }\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/951-960/Prison Cells After N Days.cpp",
    "content": "class Solution {\n    \n    vector<int> int2vec(int n) {\n        vector<int> result(8, 0);\n        for (int i = 0; i < 8; i++) {\n            int v = n & 1;\n            result[7 - i] = v;\n            n /= 2;\n        }\n        return result;\n    }\n    \n    int ith(int a, int i) {\n        return (a >> i) & 1; \n    }\n    \n    int transform(int num) {\n        int result = 0;\n        for (int i = 1; i <= 6; i++) {\n            int tmp = (ith(num, i-1) == ith(num, i+1));\n            result |= (tmp << i);\n        }\n        result &= 126;\n        return result;\n    }\n    \npublic:\n    vector<int> prisonAfterNDays(vector<int>& cells, int N) {\n        int start = 0;\n        for (auto p = cells.begin(); p != cells.end(); p++) {\n            start *= 2;\n            start |= *p;\n        }\n        \n        map<int, int> mymap;\n        map<int, int> step2v;\n        mymap[start] = 0;\n        step2v[0] = start;\n        \n        int i = 0;\n        while (i < N) {\n            start = transform(start);\n            i++;\n            if (mymap.count(start) == 1) {\n                int coef = i - mymap[start];\n                int mystep = ((N - i) % coef) + mymap[start];\n                return int2vec(step2v[mystep]);\n            }\n            mymap[start] = i;\n            step2v[i] = start;\n        }\n        \n        return int2vec(start);\n    }\n};\n"
  },
  {
    "path": "cpp/951-960/Regions Cut By Slashes.cpp",
    "content": "class UF {\n    \nprivate:\n    vector<int> parent;\n    vector<int> rank;\n    int count;\n    int N;\n    \npublic:\n    \n    UF(int N) : parent(N), rank(N, 0), N(N), count(N) {\n        for (int i = 0; i < N; i++) {\n            parent[i] = i;\n        }\n    }\n    \n    int find(int p) {\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];    // path compression by halving\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    int getCount() const {\n        return count;\n    }\n    \n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    void Union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rootP == rootQ) return;\n        \n        // make root of smaller rank point to root of larger rank\n        if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;\n        else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;\n        else {\n            parent[rootQ] = rootP;\n            rank[rootP]++;\n        }\n        count--;\n    }\n};\n\nclass Solution {\npublic:\n    int regionsBySlashes(vector<string>& grid) {\n        int n = grid.size();\n        UF uf(4*n*n);\n        \n        for (int r = 0; r < n; ++r) {\n            for (int c = 0; c < n; ++c) {\n                int root = 4 * (r * n + c);\n                char val = grid[r][c];\n                if (val != '\\\\') {\n                    uf.Union(root + 0, root + 1);\n                    uf.Union(root + 2, root + 3);\n                }\n                if (val != '/') {\n                    uf.Union(root + 0, root + 2);\n                    uf.Union(root + 1, root + 3);\n                }\n\n                // north south\n                if (r + 1 < n)\n                    uf.Union(root + 3, (root + 4 * n) + 0);\n                if (r - 1 >= 0)\n                    uf.Union(root + 0, (root - 4 * n) + 3);\n                // east west\n                if (c + 1 < n)\n                    uf.Union(root + 2, (root + 4) + 1);\n                if (c - 1 >= 0)\n                    uf.Union(root + 1, (root - 4) + 2);\n            }\n        }\n        \n        return uf.getCount();\n    }\n};\n"
  },
  {
    "path": "cpp/951-960/Verifying an Alien Dictionary.cpp",
    "content": "class Solution {\n    \n    bool check(const string& previous_word, const string& current_word, char* orders) {\n        int len = min(previous_word.length(), current_word.length());\n        for (int i = 0; i < len; i++) {\n            char p_ch = previous_word[i];\n            char c_ch = current_word[i];\n            if (orders[p_ch - 'a'] < orders[c_ch - 'a']) return true;\n            if (orders[p_ch - 'a'] > orders[c_ch - 'a']) return false;\n        }\n        return previous_word <= current_word;\n    }\n    \npublic:\n    bool isAlienSorted(vector<string>& words, string order) {\n        char orders[26];\n        for (int i = 0; i < order.length(); i++) {\n            orders[order[i] - 'a'] = i;\n        }\n        \n        for (int i = 1; i < words.size(); i++) {\n            const string& previous_word = words[i - 1];\n            const string& current_word = words[i];\n            if (!check(previous_word, current_word, orders)) {\n                return false;\n            }\n        }\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/961-970/N-Repeated Element in Size 2N Array.cpp",
    "content": "class Solution {\npublic:\n    int repeatedNTimes(vector<int>& A) {\n        for (auto i = 0; i < A.size() - 2; ++i) {\n            if (A[i] == A[i + 1] || A[i] == A[i + 2]) {\n                return A[i];\n            }\n        }\n        return A[A.size() - 1]; \n    }\n};\n"
  },
  {
    "path": "cpp/961-970/Pancake Sorting.cpp",
    "content": "class Solution {\npublic:\n    vector<int> pancakeSort(vector<int>& A) {\n        vector<int> res;\n        int x,i;\n        for (x = A.size(); x > 0; --x) {\n            for (i = 0; A[i] != x; ++i);\n            reverse(A.begin(), A.begin() + i + 1);\n            res.push_back(i + 1);\n            reverse(A.begin(), A.begin() + x);\n            res.push_back(x);\n        }\n        return res;\n    }\n};\n"
  },
  {
    "path": "cpp/971-980/Distribute Coins in Binary Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    int ans;\n    \n    // {num of nodes, num of coins}\n    pair<int, int> dfs(TreeNode* root) {\n        if (root == nullptr) return {0, 0};\n        auto leftRes = dfs(root->left);\n        auto rightRes = dfs(root->right);\n        if (leftRes.first > leftRes.second) {\n            ans += (leftRes.first - leftRes.second);\n        }\n        if (rightRes.first > rightRes.second) {\n            ans += (rightRes.first - rightRes.second);\n        }\n        int node = leftRes.first + rightRes.first + 1;\n        int coin = leftRes.second + rightRes.second + root->val;\n        if (coin > node) ans += (coin - node);\n        \n        return {node, coin};\n    }\n    \npublic:\n    int distributeCoins(TreeNode* root) {\n        ans = 0;\n        dfs(root);\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/971-980/K Closest Points to Origin.cpp",
    "content": "class Solution {\npublic:\n    vector<vector<int>> kClosest(vector<vector<int>>& points, int K) {\n        auto cmp = [&](const vector<int>& a, const vector<int>& b) {\n            return a[0] * a[0] + a[1] * a[1] <  b[0] * b[0] + b[1] * b[1]; \n        };\n        \n        nth_element(points.begin(), points.begin() + K, points.end(), cmp);\n        // sort(points.begin(), points.end(), cmp);\n        \n        vector<vector<int>> ans(points.begin(), points.begin() + K);\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/971-980/Largest Perimeter Triangle.cpp",
    "content": "class Solution {\npublic:\n    int largestPerimeter(vector<int>& A) {\n        sort(A.begin(), A.end());\n        for (int i = A.size() - 1; i >= 2; i--) {\n            if (A[i-2] + A[i-1] > A[i]) {\n                return A[i] + A[i-1] + A[i-2];\n            }\n        }\n        return 0;\n    }\n};\n"
  },
  {
    "path": "cpp/971-980/Longest Turbulent Subarray.cpp",
    "content": "class Solution {\npublic:\n    int maxTurbulenceSize(vector<int>& A) {\n        \n        int ans = 0;\n        int i = 0;\n        int currentFlag = 0;\n        int currentLen = 1;\n        \n        while (i + 1 < A.size()) {\n            if (A[i] < A[i+1]) {\n                if (currentFlag == -1) {\n                    currentLen++;\n                } else if (currentFlag == 1) {\n                    currentLen = 2;\n                } else {\n                    currentLen = 2;\n                }\n                currentFlag = 1;\n            } else if (A[i] > A[i+1]) {\n                if (currentFlag == -1) {\n                    currentLen = 2;\n                } else if (currentFlag == 1) {\n                    currentLen++;\n                } else {\n                    currentLen = 2;\n                }\n                currentFlag = -1;\n            } else {\n                currentFlag = 0;\n                currentLen = 1;\n            }\n            i++;\n            ans = max(currentLen, ans); \n        }\n        \n        return max(currentLen, ans);\n    }\n};\n"
  },
  {
    "path": "cpp/971-980/Squares of a Sorted Array.cpp",
    "content": "class Solution {\npublic:\n    vector<int> sortedSquares(vector<int>& A) {\n        vector<int> ans(A.size());\n        int i = 0, j = A.size() - 1;\n        int k = 0;\n        while (i <= j) {\n            if (abs(A[i]) >= abs(A[j])) {\n                ans[k] = A[i]*A[i];\n                i++;\n            } else {\n                ans[k] = A[j]*A[j];\n                j--;\n            }\n            k++;\n        }\n        reverse(ans.begin(), ans.end());\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/971-980/Subarray Sums Divisible by K.cpp",
    "content": "class Solution {\npublic:\n    int subarraysDivByK(vector<int>& A, int K) {\n        vector<int> record(K+1, 0);\n        record[0] = 1;\n        \n        int sum = 0;\n        int ans = 0;\n        for (int e : A) {\n            sum += e;\n            // Make it a positive number to avoid bad mod.\n            if (sum < 0) sum += (-1*sum / K) * K + K;\n            int target = sum % K;\n            // You can also remove following line.\n            sum = target;\n            ans += record[target];\n            record[target]++;\n        }\n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/971-980/Unique Paths III.cpp",
    "content": "class Solution {\n    \n    int dfs(vector<vector<int>>& grid, int i, int j, int w, int h, int n) {\n        if (i < 0 || i >= w || j < 0 || j >= h) return 0;\n        if (grid[i][j] == -1) return 0;\n        if (grid[i][j] == 999) return 0;\n        if (grid[i][j] == 2) {\n            if (n == -1) return 1;\n            else return 0;\n        }\n        \n        grid[i][j] = 999;\n        int ans = 0;\n        ans += dfs(grid, i-1, j, w, h, n-1);\n        ans += dfs(grid, i+1, j, w, h, n-1);\n        ans += dfs(grid, i, j-1, w, h, n-1);\n        ans += dfs(grid, i, j+1, w, h, n-1);\n        grid[i][j] = 0;\n        \n        return ans;\n    }\n    \npublic:\n    int uniquePathsIII(vector<vector<int>>& grid) {\n        int w = grid.size();\n        int h = grid.front().size();\n        \n        int n = 0;\n        int ii, jj;\n        for (int i = 0; i < w; i++) {\n            for (int j = 0; j < h; j++) {\n                if (grid[i][j] == 0) {\n                    n++;\n                }\n                if (grid[i][j] == 1) {\n                    ii = i;\n                    jj = j;\n                }\n            }\n        }\n        \n        return dfs(grid, ii, jj, w, h, n);\n    }\n};\n"
  },
  {
    "path": "cpp/981-990/Add to Array-Form of Integer.cpp",
    "content": "class Solution {\npublic:\n    vector<int> addToArrayForm(vector<int>& A, int K) {\n        reverse(A.begin(), A.end());\n        vector<int> B;\n        while (K > 0) {\n            int v = K % 10;\n            B.push_back(v);\n            K = K / 10;\n        }\n        \n        int carry = 0;\n        B.resize(max(A.size(), B.size()));\n        for (int i = 0; i < max(A.size(), B.size()); i++) {\n            int a = i < A.size() ? A[i] : 0;\n            int b = i < B.size() ? B[i] : 0;\n            int v = a + b + carry;\n            B[i] = v % 10;\n            carry = v / 10;\n        }\n        if (carry) {\n            B.push_back(1);\n        }\n        reverse(B.begin(), B.end());\n        return B;\n    }\n};\n"
  },
  {
    "path": "cpp/981-990/Interval List Intersections.cpp",
    "content": "class Solution {\n    vector<int> getInterval(const vector<int>& a, const vector<int>& b) {\n        vector<int> ans(2, 0);\n        ans[0] = max(a[0], b[0]);\n        ans[1] = min(a[1], b[1]);\n        return ans;\n    }\npublic:\n    vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {\n        int i = 0, j = 0;\n        vector<vector<int>> ans;\n        \n        while (i < A.size() && j < B.size()) {\n            const vector<int>& first = A[i];\n            const vector<int>& second = B[j];\n            \n            if (first[1] < second[0]) {\n                i++;\n            } else if (second[1] < first[0]) {\n                j++;\n            } else {\n                ans.emplace_back(getInterval(first, second));\n                if (first[1] < second[1]) {\n                    i++;\n                } else if (first[1] > second[1]) {\n                    j++;\n                } else {\n                    i++;\n                    j++;\n                }\n            }\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/981-990/Satisfiability of Equality Equations.cpp",
    "content": "class UF {\n    \nprivate:\n    vector<int> parent;\n    vector<int> rank;\n    int count;\n    int N;\n    \n    bool validate(int p) {\n        return (p >= 0 && p < N);\n    }\n    \npublic:\n    \n    UF(int N) : parent(N), rank(N, 0), N(N), count(N) {\n        for (int i = 0; i < N; i++) {\n            parent[i] = i;\n        }\n    }\n    \n    int find(int p) {\n        if (!validate(p)) return -1;\n        while (p != parent[p]) {\n            parent[p] = parent[parent[p]];    // path compression by halving\n            p = parent[p];\n        }\n        return p;\n    }\n    \n    int getCount() const {\n        return count;\n    }\n    \n    bool connected(int p, int q) {\n        return find(p) == find(q);\n    }\n    \n    void Union(int p, int q) {\n        int rootP = find(p);\n        int rootQ = find(q);\n        if (rootP == rootQ) return;\n        \n        // make root of smaller rank point to root of larger rank\n        if (rank[rootP] < rank[rootQ]) parent[rootP] = rootQ;\n        else if (rank[rootP] > rank[rootQ]) parent[rootQ] = rootP;\n        else {\n            parent[rootQ] = rootP;\n            rank[rootP]++;\n        }\n        count--;\n    }\n    \n    ~UF() {}\n};\n\nclass Solution {\npublic:\n    bool equationsPossible(vector<string>& equations) {\n        UF uf(256);\n        \n        // go through == first\n        for (const string& str : equations) {\n            if (str[1] == '=') {\n                uf.Union(str[0], str[3]);\n            }\n        }\n        \n        // then go through !=\n        for (const string& str : equations) {\n            if (str[1] == '!') {\n                if (uf.connected(str[0], str[3])) {\n                    return false;\n                }\n            }\n        }\n        \n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/981-990/String Without AAA or BBB.cpp",
    "content": "class Solution {\n\npublic:\n    string strWithout3a3b(int A, int B) {\n        string ans = \" \";\n        while (A > 0 || B > 0) {\n            if (A == B) {\n                A--;\n                B--;\n                ans = ans + (ans.back() == 'a' ? \"ba\" : \"ab\"); \n            } else if (A > B) {\n                if (ans.back() == 'a') {\n                    ans = ans + 'b';\n                    B--;\n                } else {\n                    ans = ans + 'a';\n                    A--;\n                    if (A > 0) {\n                        ans = ans + 'a';\n                        A--;\n                    }\n                }\n            } else {\n                if (ans.back() == 'b') {\n                    ans = ans + 'a';\n                    A--;\n                } else {\n                    ans = ans + 'b';\n                    B--;\n                    if (B > 0) {\n                        ans = ans + 'b';\n                        B--;\n                    }\n                }\n            }\n        }\n        return ans.substr(1);\n    }\n};\n"
  },
  {
    "path": "cpp/981-990/Time Based Key-Value Store.cpp",
    "content": "class TimeMap {\n    unordered_map<string, vector<pair<int, string>>> db;\npublic:\n    TimeMap() {\n        \n    }\n    \n    void set(string key, string value, int timestamp) {\n        db[key].push_back({timestamp, value});\n    }\n    \n    string get(string key, int timestamp) {\n        auto cmp = [](const pair<int, string>& lhs, const pair<int, string>& rhs) {\n            return lhs.first < rhs.first;\n        };\n        auto it = upper_bound(db[key].begin(), db[key].end(), make_pair(timestamp, \"\"), cmp);\n        if (it == db[key].begin()) {\n            return \"\";\n        } else {\n            it--;\n            return it->second;\n        }\n    }\n};\n\n/**\n * Your TimeMap object will be instantiated and called as such:\n * TimeMap* obj = new TimeMap();\n * obj->set(key,value,timestamp);\n * string param_2 = obj->get(key,timestamp);\n */\n"
  },
  {
    "path": "cpp/991-1000/Broken Calculator.cpp",
    "content": "class Solution {\n    map<int, int> cache;\npublic:\n    int brokenCalc(int X, int Y) {\n        int ans = 0;\n        while (Y > X) {\n            ans++;\n            if (Y % 2 == 1)\n                Y++;\n            else\n                Y /= 2;\n        }\n\n        return ans + X - Y;\n    }\n};\n"
  },
  {
    "path": "cpp/991-1000/Cousins in Binary Tree.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\n    \n    // {parent, depth}\n    bool getPD(TreeNode* root, int v, pair<TreeNode*, int>* res, int depth, TreeNode* parent) {\n        if (root == nullptr) return false;\n        if (root->val == v) {\n            res->first = parent;\n            res->second = depth;\n            return true;\n        }\n        bool flag = getPD(root->left, v, res, depth+1, root);\n        if (flag) return true;\n        flag = getPD(root->right, v, res, depth+1, root);\n        return flag;\n    }\n    \npublic:\n    bool isCousins(TreeNode* root, int x, int y) {\n        pair<TreeNode*, int> left, right;\n        getPD(root, x, &left, 0, nullptr);\n        getPD(root, y, &right, 0, nullptr);\n        if (left.second != right.second) return false;\n        if (left.first == right.first) return false;\n        return true;\n    }\n};\n"
  },
  {
    "path": "cpp/991-1000/Find the Town Judge.cpp",
    "content": "class Solution {\npublic:\n    int findJudge(int N, vector<vector<int>>& trust) {\n        map<int, int> mymap;\n        for (int i = 1; i <= N; i++) mymap[i] = 0;\n        for (const auto& e : trust) {\n            mymap[e[0]]--;\n            mymap[e[1]]++;\n        }\n        \n        for (const auto& iter : mymap) {\n            if (iter.second == N - 1) return iter.first;\n        }\n        \n        return -1;\n    }\n};\n"
  },
  {
    "path": "cpp/991-1000/Maximum Binary Tree II.cpp",
    "content": "/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}\n * };\n */\nclass Solution {\npublic:\n    TreeNode* insertIntoMaxTree(TreeNode* root, int val) {\n        if (root != nullptr && root->val > val) {\n            root->right = insertIntoMaxTree(root->right, val);\n            return root;\n        }\n        TreeNode* node = new TreeNode(val);\n        node->left = root;\n        return node;\n    }\n};\n"
  },
  {
    "path": "cpp/991-1000/Minimum Number of K Consecutive Bit Flips.cpp",
    "content": "class Solution {\npublic:\n    int minKBitFlips(vector<int>& A, int K) {\n        int ans = 0;\n        int flag = 0;\n        map<int, int> mymap;\n        \n        for (int i = 0; i < A.size(); i++) {\n            flag ^= mymap[i];\n            \n            if (A[i] + flag == 1) continue;\n            \n            // flip\n            ans++;\n            flag = 1 - flag;\n            \n            if (i + K > A.size()) return -1;\n            \n            mymap[i+K] = 1 - mymap[i+K];\n        }\n        \n        return ans;\n    }\n};\n    \n"
  },
  {
    "path": "cpp/991-1000/Number of Squareful Arrays.cpp",
    "content": "class Solution {\n    \n    int ans;\n    set<string> ans_set;\n    \n    void dfs(int i, const vector<vector<int>>& graph, const vector<int>& A, bool* visited, string temp, int count) {\n        visited[i] = true;\n        temp += to_string(A[i]);\n        \n        if (count == graph.size()) {\n            if (ans_set.count(temp) == 0) {\n                ans++;\n                ans_set.insert(temp);\n            }\n        } else {\n            set<int> performance;\n            for (int k = 0; k < graph[i].size(); k++) {\n                int index = graph[i][k];\n                if (performance.count(A[index]) == 1) continue;\n                if (visited[index] == false) {\n                    performance.insert(A[index]);\n                    dfs(index, graph, A, visited, temp, count+1);\n                }\n            }\n        }\n        \n        visited[i] = false;\n    }\n    \npublic:\n    int numSquarefulPerms(vector<int>& A) {\n        vector<vector<int>> graph(A.size(), vector<int>());\n        \n        for (int i = 0; i < A.size(); i++) {\n            for (int j = 0; j < A.size(); j++) {\n                if (i == j) continue;\n                int val = A[i] + A[j];\n                int root = sqrt(val);\n                if (root*root == val) {\n                    graph[i].push_back(j);\n                    graph[j].push_back(i);\n                }\n            }\n        }\n        \n        bool visited[12] = {false};\n        \n        set<int> performance;\n        for (int i = 0; i < A.size(); i++) {\n            if (performance.count(A[i]) == 1) continue;\n            performance.insert(A[i]);\n            dfs(i, graph, A, visited, \"\", 1);\n        }\n        \n        return ans;\n    }\n};\n"
  },
  {
    "path": "cpp/991-1000/Rotting Oranges.cpp",
    "content": "class Solution {\npublic:\n    int orangesRotting(vector<vector<int>>& grid) {\n        // BFS\n        queue<pair<int, int>> rot;\n        int previous_fresh = -1;\n        int fresh = 0;\n        int h = grid.size();\n        int w = grid.front().size();\n        \n        for (int i = 0; i < grid.size(); i++) {\n            for (int j = 0; j < grid[i].size(); j++) {\n                if (grid[i][j] == 1) {\n                    fresh++;\n                } else if (grid[i][j] == 2) {\n                    rot.push({i, j});\n                }\n            }\n        }\n        \n        int day = 0;\n        while (!rot.empty() && fresh > 0) {\n            previous_fresh = fresh;\n            int n = rot.size();\n            \n            for (int i = 0; i < n; i++) {\n                auto e = rot.front();\n                rot.pop();\n                \n                pair<int, int> directions[4] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n                \n                for (int j = 0; j < 4; j++) {\n                    int newi = e.first + directions[j].first;\n                    int newj = e.second + directions[j].second;\n                    if (newi < 0 || newj < 0 || newi >= h || newj >= w) continue;\n                    \n                    if (grid[newi][newj] == 1) {\n                        fresh--;\n                        rot.push({newi, newj});\n                        grid[newi][newj] = 2;\n                    }\n                }\n            }\n            \n            day++;\n        }\n        \n        return fresh == 0 ? day : -1;\n    }\n};\n"
  },
  {
    "path": "golang/001-010/Add Two Numbers.go",
    "content": "/**\n * Definition for singly-linked list.\n * type ListNode struct {\n *     Val int\n *     Next *ListNode\n * }\n */\nfunc addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {\n    carry := 0\n    var virtual_head *ListNode = new(ListNode)\n    copy_virtual_head := virtual_head\n    for l1 != nil || l2 != nil || carry > 0 {\n        v1 := 0\n        v2 := 0\n        if l1 != nil { \n            v1 = l1.Val\n            l1 = l1.Next\n        }\n        if l2 != nil {\n            v2 = l2.Val\n            l2 = l2.Next\n        }\n        tmp := v1 + v2 + carry\n        carry = tmp/10\n        var new_node *ListNode = new(ListNode)\n        new_node.Val = tmp%10;\n        virtual_head.Next = new_node\n        virtual_head = new_node\n    }\n    return copy_virtual_head.Next\n}\n"
  },
  {
    "path": "golang/001-010/Longest Substring Without Repeating Characters.go",
    "content": "func lengthOfLongestSubstring(s string) int {\n    var i, maximum_len int = 0, 0\n    mymap := make(map[byte]int)\n    \n    for j := 0; j < len(s); j++ {\n        mymap[s[j]]++\n        for mymap[s[j]] == 2 && i < j {\n            mymap[s[i]]--\n            i++\n        }\n        \n        if maximum_len < j - i + 1 {\n            maximum_len = j - i + 1\n        }\n    }\n    \n    return maximum_len\n}\n"
  },
  {
    "path": "golang/001-010/Two Sum.go",
    "content": "func twoSum(nums []int, target int) []int {\n    mymap := make(map[int]int)\n    for i := 0; i < len(nums); i++ {\n        j, ok := mymap[target-nums[i]]\n        if ok {\n            result := []int{j, i}\n            return result\n        }\n        mymap[nums[i]] = i\n    }\n    result := []int{-1, -1}\n    return result\n}\n"
  },
  {
    "path": "java/201-210/Happy Number.java",
    "content": "public class Solution {\n    \n    public int convert(String str) {\n        int val = 0;\n        for (int i = 0, n = str.length(); i < n; i++) {\n            int c = str.charAt(i) - '0';\n            val += c*c;\n        }\n        return val;\n    }\n    \n    public boolean isHappy(int n) {\n        Map m1 = new HashMap();\n        \n        while(n != 1) {\n            m1.put(n, true);\n            n = convert(Integer.toString(n));\n            if(m1.containsKey(n)) return false;\n        }\n        return true;\n    }\n}"
  },
  {
    "path": "java/291-300/Nim Game.java",
    "content": "public class Solution {\n    public boolean canWinNim(int n) {\n        return n%4 != 0;\n    }\n}"
  },
  {
    "path": "java/331-340/Counting Bits.java",
    "content": "/*\n * 0000 0001 0010 0011 0100 0101 0110 0111 1000\n *  0     1    1   2     1    2    2    3    1\n */\npublic class Solution {\n    public int[] countBits(int num) {\n        int[] result = new int[num+1];\n        if(num == 0) return result;\n        \n        int loops = 1;\n        \n        while(true) {\n            for(int k = 0;k < loops;k++) {\n                int index = k+loops;\n                if(index > num)\n                    return result;\n                result[index] = result[k]+1;\n            }\n            loops *= 2;\n        }\n    }\n}"
  },
  {
    "path": "java/331-340/Nested List Weight Sum.java",
    "content": "/**\n * // This is the interface that allows for creating nested lists.\n * // You should not implement it, or speculate about its implementation\n * public interface NestedInteger {\n *\n *     // @return true if this NestedInteger holds a single integer, rather than a nested list.\n *     public boolean isInteger();\n *\n *     // @return the single integer that this NestedInteger holds, if it holds a single integer\n *     // Return null if this NestedInteger holds a nested list\n *     public Integer getInteger();\n *\n *     // @return the nested list that this NestedInteger holds, if it holds a nested list\n *     // Return null if this NestedInteger holds a single integer\n *     public List<NestedInteger> getList();\n * }\n */\npublic class Solution {\n    \n    public int helper(List<NestedInteger> nestedList, int depth) {\n        int sum = 0;\n        for (int i = 0; i < nestedList.size(); i++) {\n            if(nestedList.get(i).isInteger())\n                sum += nestedList.get(i).getInteger() * depth;\n            else\n                sum += helper(nestedList.get(i).getList(), depth+1);\n        }\n        return sum;\n    }\n    \n    public int depthSum(List<NestedInteger> nestedList) {\n        return helper(nestedList, 1);\n    }\n}"
  },
  {
    "path": "python/001-010/Median of Two Sorted Arrays.py",
    "content": "def findMedianSortedArrays(self, A, B):\n    l = len(A) + len(B)\n    if l % 2 == 1:\n        return self.kth(A, B, l // 2)\n    else:\n        return (self.kth(A, B, l // 2) + self.kth(A, B, l // 2 - 1)) / 2.\n\ndef kth(self, a, b, k):\n    if not a:\n        return b[k]\n    if not b:\n        return a[k]\n    ia, ib = len(a) // 2 , len(b) // 2\n    ma, mb = a[ia], b[ib]\n    \n    # when k is bigger than the sum of a and b's median indices\n    if ia + ib < k:\n        # if a's median is bigger than b's, b's first half doesn't include k\n        if ma > mb:\n            return self.kth(a, b[ib + 1:], k - ib - 1)\n        else:\n            return self.kth(a[ia + 1:], b, k - ia - 1)\n    # when k is smaller than the sum of a and b's indices\n    else:\n    # if a's median is bigger than b's, a's second half doesn't include k\n    if ma > mb:\n        return self.kth(a[:ia], b, k)\n        else:\n            return self.kth(a, b[:ib], k)"
  },
  {
    "path": "python/011-020/Valid Parentheses.py",
    "content": "class Solution:\n    # @param {string} s\n    # @return {boolean}\n    def isValid(self, s):\n        stack = []\n        dict = {\"]\":\"[\", \"}\":\"{\", \")\":\"(\"}\n        for char in s:\n            if char in dict.values():\n                stack.append(char)\n            elif char in dict.keys():\n                if stack == [] or dict[char] != stack.pop():\n                    return False\n            else:\n                return False\n        return not stack"
  },
  {
    "path": "python/021-030/Reverse Nodes in k-Group.py",
    "content": "#!/usr/bin/env python\n# coding=utf-8\n\n# Definition for singly-linked list.\n# class ListNode:\n#     def __init__(self, x):\n#         self.val = x\n#         self.next = None\n\nclass Solution:\n    # @param {ListNode} head\n    # @param {integer} k\n    # @return {ListNode}\n    def reverseKGroup(self, head, k):\n        if not head or k < 2:\n            return head\n\n        ret = head\n        for i in range(k-1):\n            ret = ret.next\n            if not ret:\n                return head\n\n        prev,cur = None,head\n        for i in range(k):\n            tmp = cur.next\n            cur.next = prev\n            prev = cur\n            cur = tmp\n\n        head.next = self.reverseKGroup(cur, k)\n        return ret"
  },
  {
    "path": "python/031-040/Combination Sum II.py",
    "content": "class Solution:\n    # @param {integer[]} candidates\n    # @param {integer} target\n    # @return {integer[][]}\n    def combinationSum2(self, candidates, target):\n        candidates.sort()\n        result = []\n        tmp = []\n        self.help(tmp, candidates, 0, target, result)\n        return result\n    \n    def help(self, now, candidates, index, target, result):\n        i = index\n        while i < len(candidates):\n            if candidates[i] < target:\n                now.append(candidates[i]);\n                self.help(now, candidates, i+1, target-candidates[i], result)\n                del now[-1]\n                while i < len(candidates)-1 and candidates[i] == candidates[i+1]:\n                    i += 1\n            elif candidates[i] == target:\n                temp = now[:]\n                temp.append(candidates[i])\n                result.append(temp)\n                return\n            i += 1"
  },
  {
    "path": "python/031-040/Combination Sum.py",
    "content": "#!/usr/bin/env python\n# coding=utf-8\n\nclass Solution:\n    # @param {integer[]} candidates\n    # @param {integer} target\n    # @return {integer[][]}\n    def combinationSum(self, candidates, target):\n        candidates.sort()\n        result = []\n        tmp = []\n        self.help(tmp, candidates, 0, target, result)\n        return result\n    \n    def help(self, now, candidates, index, target, result):\n        for i in range(index, len(candidates)):\n            if candidates[i] < target:\n                now.append(candidates[i]);\n                self.help(now, candidates, i, target-candidates[i], result)\n                del now[-1]\n            elif candidates[i] == target:\n                now.append(candidates[i])\n                temp = now[:]\n                result.append(temp)\n                del now[-1]"
  },
  {
    "path": "python/031-040/Next Permutation.py",
    "content": "class Solution(object):\n    def nextPermutation(self, nums):\n        \"\"\"\n            :type nums: List[int]\n            :rtype: void Do not return anything, modify nums in-place instead.\n            \"\"\"\n        i = len(nums) - 2\n        while i >= 0 and nums[i] >= nums[i+1]:\n            i -= 1\n        left = i+1\n        right = len(nums)-1;\n        while left < right:\n            nums[left], nums[right] = nums[right], nums[left]\n            left += 1\n            right -= 1\n        \n        if i == -1:\n            return\n        \n        j = 0\n        v = 100000000\n        for k in range(i+1, len(nums)):\n            if nums[k] > nums[i] and nums[k] < v:\n                j = k\n                v = nums[k]\n        nums[i], nums[j] = nums[j], nums[i]"
  },
  {
    "path": "python/031-040/Search Insert Position.py",
    "content": "class Solution:\n    # @param {integer[]} nums\n    # @param {integer} target\n    # @return {integer}\n    def searchInsert(self, nums, target):\n        lo = 0\n        hi = len(nums) - 1\n        while lo <= hi:\n            mid = lo + (hi - lo) / 2\n            if target < nums[mid]:\n                hi = mid - 1\n            elif target > nums[mid]:\n                lo = mid + 1\n            else:\n                return mid\n\n    return lo;"
  },
  {
    "path": "python/031-040/Search for a Range.py",
    "content": "class Solution:\n    # @param {integer[]} nums\n    # @param {integer} target\n    # @return {integer[]}\n    def searchRange(self, nums, target):\n        low = 0\n        high = len(nums)-1\n        res = []\n        \n        while low <= high:\n            mid = (low+high)/2\n            if(nums[mid] < target):\n                low = mid+1\n            elif(nums[mid] > target):\n                high = mid-1\n            else:\n                bound1 = bound2 = mid\n                while bound1 >= 0 and nums[bound1] == nums[mid]:\n                    bound1 -= 1\n                while bound2 < len(nums) and nums[bound2] == nums[mid]:\n                    bound2 += 1\n                res.append(bound1+1)\n                res.append(bound2-1)\n                break\n        \n        if(len(res) == 0):\n            res.append(-1)\n            res.append(-1)\n            \n        return res\n"
  },
  {
    "path": "python/031-040/Sudoku Solver.py",
    "content": "class Solution:\n    \n    def help(self, board, i, j, rows, cols, rec):\n        if i == 9:\n            return True\n        \n        nexti = nextj = 0\n        if j != 8:\n            nexti = i\n            nextj = j + 1\n        else:\n            nexti = i + 1\n        \n        if board[i][j] != '.':\n            return self.help(board, nexti, nextj, rows, cols, rec)\n        else:\n            t = (i/3)*3+j/3\n            for k in range(9):\n                if rows[i][k] == False and cols[k][j] == False and rec[t][k] == False:\n                    rows[i][k] = cols[k][j] = rec[t][k] = True\n                    board[i][j] = chr(49+k)\n                    check = self.help(board, nexti, nextj, rows, cols, rec)\n                    if check:\n                        return True\n                    rows[i][k] = cols[k][j] = rec[t][k] = False\n                    board[i][j] = '.'\n        return False\n    \n    \n    # @param {character[][]} board\n    # @return {void} Do not return anything, modify board in-place instead.\n    def solveSudoku(self, board):\n        rows, cols, rec = [[False] * 9 for i in range(9)], [[False] * 9 for i in range(9)], [[False] * 9 for i in range(9)]\n        for i in range(9):\n            for j in range(9):\n                if board[i][j] != '.':\n                    index = int(board[i][j]) - 1\n                    k = (i/3)*3 + j/3\n                    rows[i][index] = cols[index][j] = rec[k][index] = True\n        self.help(board, 0, 0, rows, cols, rec)"
  },
  {
    "path": "python/031-040/Valid Sudoku.py",
    "content": "class Solution:\n    # @param {character[][]} board\n    # @return {boolean}\n    def isValidSudoku(self, board):\n        if not board:\n            return False\n        \n        row, col, box = [[False] * 9 for i in range(9)], [[False] * 9 for i in range(9)], [[False] * 9 for i in range(9)]\n        \n        for i in range(9):\n            for j in range(9):\n                num = board[i][j]\n                if num != '.':\n                    index = int(num) - 1\n                    k = i / 3 * 3 + j / 3\n                    if row[i][index] or col[j][index] or box[k][index]:\n                        return False\n                    \n                    row[i][index] = col[j][index] = box[k][index] = True\n        \n    return True"
  },
  {
    "path": "python/041-050/Jump Game II.py",
    "content": "class Solution:\n    # @param {integer[]} nums\n    # @return {integer}\n    def jump(self, nums):\n        step = 0\n        nextstep = 0\n        count = 0\n        \n        for i in range(len(nums)):\n            if i+nums[i] > nextstep:\n                nextstep = i + nums[i]\n            if i == step and i != len(nums)-1:\n                count += 1\n                step = nextstep\n        \n        return count"
  },
  {
    "path": "python/041-050/Rotate Image.py",
    "content": "class Solution:\n    # @param {integer[][]} matrix\n    # @return {void} Do not return anything, modify matrix in-place instead.\n    def rotate(self, matrix):\n        n = len(matrix)-1\n        i = 0\n        while i <= n -i:\n            j = i\n            while j <= n - i - 1:\n                tmp = matrix[j][n-i]\n                matrix[j][n-i] = matrix[i][j]\n                matrix[i][j] = matrix[n-j][i]\n                matrix[n-j][i] = matrix[n-i][n-j]\n                matrix[n-i][n-j] = tmp\n                j += 1\n            i += 1"
  },
  {
    "path": "python/051-060/Jump Game.py",
    "content": "class Solution:\n    # @param {integer[]} nums\n    # @return {boolean}\n    def canJump(self, nums):\n        l = len(nums)\n        res = 0\n        for i in range(l):\n            if i <= res:\n                res = max(res, i+nums[i]);\n        if res >= l-1:\n            return True\n        return False"
  },
  {
    "path": "python/051-060/Permutation Sequence.py",
    "content": "class Solution(object):\n    def getPermutation(self, n, k):\n        \"\"\"\n            :type n: int\n            :type k: int\n            :rtype: str\n            \"\"\"\n        numset = ['1','2','3','4','5','6','7','8','9']\n        pTable = [1]*10\n        for i in range(1,10):\n            pTable[i] = i * pTable[i-1]\n        \n        res = ''\n        while n > 0:\n            temp = (k-1)/pTable[n-1]\n            res += numset[temp]\n            del numset[temp]\n            k -= temp * pTable[n-1]\n            n -= 1\n        \n        return res"
  },
  {
    "path": "python/061-070/Minimum Path Sum.py",
    "content": "class Solution:\n    # @param {integer[][]} grid\n    # @return {integer}\n    def minPathSum(self, grid):\n        n = len(grid);\n        m = len(grid[0]);\n        p = [([0] * m) for i in range(n)]\n        p[0][0] = grid[0][0];\n        \n        for k in range (1, n):\n            p[k][0] = p[k-1][0]+grid[k][0];\n        for k in range (1, m):\n            p[0][k] = p[0][k-1]+grid[0][k];\n        \n        for i in range (1, n):\n            for j in range (1, m):\n                    p[i][j] = min(p[i-1][j], p[i][j-1]) + grid[i][j];\n        \n        return p[n-1][m-1];\n"
  },
  {
    "path": "python/061-070/Sqrt(x).py",
    "content": "class Solution:\n    # @param {integer} x\n    # @return {integer}\n    def mySqrt(self, x):\n        if x == 0:\n            return 0\n        k = 1.0\n        while abs(k*k-x) >= 1:\n            k = (k+x/k)/2\n        return int(k)"
  },
  {
    "path": "python/061-070/Unique Paths II.py",
    "content": "class Solution:\n    # @param {integer[][]} obstacleGrid\n    # @return {integer}\n    def uniquePathsWithObstacles(self, obstacleGrid):\n        m = len(obstacleGrid)\n        n = len(obstacleGrid[0])\n        if obstacleGrid[0][0] == 1 or obstacleGrid[m-1][n-1] == 1:\n            return 0\n        table = [([0] * (n+1)) for i in range(m+1)]\n        table[1][1] = 1\n        for i in range(1,m+1):\n            for j in range(1,n+1):\n                if i == 1 and j == 1:\n                    continue\n                if obstacleGrid[i-1][j-1] == 1:\n                    table[i][j] = 0\n                else:\n                    table[i][j] = table[i-1][j] + table[i][j-1]\n        return table[m][n]"
  },
  {
    "path": "python/061-070/Unique Paths.py",
    "content": "class Solution:\n    # @param {integer} m\n    # @param {integer} n\n    # @return {integer}\n    def uniquePaths(self, m, n):\n        table = [([0] * (n+1)) for i in range(m+1)]\n        table[1][1] = 1\n        for i in range(1,m+1):\n            for j in range(1,n+1):\n                if i == 1 and j == 1:\n                    continue\n                table[i][j] = table[i-1][j] + table[i][j-1]\n        return table[m][n]"
  },
  {
    "path": "python/061-070/Valid Number.py",
    "content": "class Solution:\n    # @param {string} s\n    # @return {boolean}\n    def isNumber(self, s):\n        try:\n            num = float(s.strip())\n            return True\n        except:\n            return False\n"
  },
  {
    "path": "python/071-080/Edit Distance.py",
    "content": "class Solution:\n    # @param {string} word1\n    # @param {string} word2\n    # @return {integer}\n    def minDistance(self, word1, word2):\n        n,m = len(word1), len(word2)\n        p = [[0]*(m+1) for _ in range(n+1)]\n        \n        for i in range(1, n+1):\n            p[i][0] = i\n        for i in range(1, m+1):\n            p[0][i] = i\n        \n        for i in range(1, n+1):\n            for j in range(1, m+1):\n                f = 1 if word1[i-1] != word2[j-1] else 0\n                p[i][j] = min(p[i-1][j]+1, p[i][j-1]+1, p[i-1][j-1]+f);\n        \n        return p[n][m]"
  },
  {
    "path": "python/081-090/Largest Rectangle in Histogram.py",
    "content": "class Solution:\n    # @param {integer[]} height\n    # @return {integer}\n    def largestRectangleArea(self, height):\n        res = 0\n        height.append(0)\n        mystack = []\n        \n        for i in range(len(height)):\n            if len(mystack) == 0 or height[i] >= height[mystack[-1]]:\n                mystack.append(i)\n            else:\n                while len(mystack) > 0 and height[i] < height[mystack[-1]]:\n                    h = height[mystack[-1]]\n                    del mystack[-1]\n                    width = i if len(mystack) == 0 else i - 1 - mystack[-1]\n                    res = max(res, width*h)\n                mystack.append(i)\n        return res"
  },
  {
    "path": "python/081-090/Maximal Rectangle.py",
    "content": "class Solution:\n    # @param {character[][]} matrix\n    # @return {integer}\n    def maximalRectangle(self, matrix):\n        if len(matrix) == 0:\n            return 0\n        h = [0] * (len(matrix[0])+1)\n        res = 0\n        \n        for i in range(len(matrix)):\n            matrix[i].append('0')\n            mystack = []\n            \n            for j in range(len(matrix[i])):\n                if matrix[i][j] == '1':\n                    h[j] += 1\n                else:\n                    h[j] = 0\n                \n                if len(mystack) == 0 or h[j] >= h[mystack[-1]]:\n                    mystack.append(j)\n                else:\n                    while len(mystack) > 0 and h[j] < h[mystack[-1]]:\n                        height = h[mystack[-1]]\n                        del mystack[-1]\n                        width = j if len(mystack) == 0 else j - 1 - mystack[-1]\n                        res = max(res, width*height)\n                    mystack.append(j)\n        \n        return res"
  },
  {
    "path": "python/081-090/Remove Duplicates from Sorted List II.py",
    "content": "# Definition for singly-linked list.\n# class ListNode:\n#     def __init__(self, x):\n#         self.val = x\n#         self.next = None\nclass Solution:\n    # @param {ListNode} head\n    # @return {ListNode}\n    def deleteDuplicates(self, head):\n        nhead = ListNode(0)\n        prev = -2**31\n        res = nhead\n        \n        while head:\n            if head.val != prev and (not head.next or head.val != head.next.val) :\n                nhead.next = head\n                nhead = head\n            prev = head.val\n            head = head.next\n        \n        nhead.next = None\n        return res.next"
  },
  {
    "path": "python/081-090/Remove Duplicates from Sorted List.py",
    "content": "# Definition for singly-linked list.\n# class ListNode:\n#     def __init__(self, x):\n#         self.val = x\n#         self.next = None\n\nclass Solution:\n    # @param {ListNode} head\n    # @return {ListNode}\n    def deleteDuplicates(self, head):\n        node = head\n        while node and node.next:\n            if node.val == node.next.val:\n                node.next = node.next.next\n            else:\n                node = node.next\n        return head"
  },
  {
    "path": "python/091-100/Decode Ways.py",
    "content": "#!/usr/bin/env python\n# coding=utf-8\n\nclass Solution:\n    # @param {string} s\n    # @return {integer}\n    def numDecodings(self, s):\n        if not s:\n            return 0\n        \n        dp = [0]*(len(s)+1)\n        dp[0] = 1\n        for i in xrange(len(s)):\n            if self.isValid(s[i]):\n                dp[i+1] = dp[i]\n            if i>0 and self.isValid(s[i-1:i+1]):\n                dp[i+1] += dp[i-1]\n        return dp[-1]\n    \n    def isValid(self,s):\n        if len(s) == 1 and 0<int(s) <10:\n            return True\n        if len(s) == 2 and 10 <= int(s) <= 26:\n            return True"
  },
  {
    "path": "python/091-100/Interleaving String.py",
    "content": "class Solution:\n    # @param {string} s1\n    # @param {string} s2\n    # @param {string} s3\n    # @return {boolean}\n    def isInterleave(self, s1, s2, s3):\n        m = len(s1)\n        n = len(s2)\n        if m+n != len(s3):\n            return False\n        \n        table = [([False] * (m+1)) for i in range(n+1)]\n        table[0][0] = True\n        for i in range (1, m+1):\n            if s3[i-1] == s1[i-1] and table[0][i-1] == True:\n                table[0][i] = True\n        for i in range (1, n+1):\n            if s3[i-1] == s2[i-1] and table[i-1][0] == True:\n                table[i][0] = True\n    \n        for i in range (1, n+1):\n            for j in range(1, m+1):\n                if s3[i+j-1] == s2[i-1] and table[i-1][j] == True:\n                    table[i][j] = True\n                if s3[i+j-1] == s1[j-1] and table[i][j-1] == True:\n                    table[i][j] = True\n\n                        return table[n][m]"
  },
  {
    "path": "python/101-110/Symmetric Tree.py",
    "content": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, x):\n#         self.val = x\n#         self.left = None\n#         self.right = None\nimport Queue\n\nclass Solution:\n    # @param {TreeNode} root\n    # @return {boolean}\n    def isSymmetric(self, root):\n        if not root:\n            return True\n        myqueue = Queue.Queue()\n        myqueue.put(root.left)\n        myqueue.put(root.right)\n        \n        while not myqueue.empty():\n            left = myqueue.get();\n            right = myqueue.get();\n            if not left and not right:\n                continue\n            if left and not right:\n                return False\n            if right and not left:\n                return False\n            if left.val != right.val:\n                return False\n            \n            myqueue.put(left.left)\n            myqueue.put(right.right)\n            myqueue.put(left.right)\n            myqueue.put(right.left)\n        \n                return True"
  },
  {
    "path": "python/111-120/Path Sum.py",
    "content": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, x):\n#         self.val = x\n#         self.left = None\n#         self.right = None\n\nclass Solution:\n    # @param {TreeNode} root\n    # @param {integer} sum\n    # @return {boolean}\n    def hasPathSum(self, root, sum):\n        if not root :\n            return False\n        if not root.left and not root.right and sum == root.val:\n            return True\n        return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)\n"
  },
  {
    "path": "python/111-120/Populating Next Right Pointers in Each Node II.py",
    "content": "# Definition for binary tree with next pointer.\n# class TreeLinkNode:\n#     def __init__(self, x):\n#         self.val = x\n#         self.left = None\n#         self.right = None\n#         self.next = None\n\nclass Solution:\n    # @param root, a tree link node\n    # @return nothing\n    def connect(self, root):\n        if not root:\n            return\n    \n        while True:\n            cur = root\n            pre = None\n            while cur:\n                if cur.left:\n                    if not pre:\n                        pre = cur.left\n                        root = pre\n                    else:\n                        pre.next = cur.left\n                        pre = pre.next\n            \n                if cur.right:\n                    if not pre:\n                        pre = cur.right\n                        root = pre\n                    else:\n                        pre.next = cur.right\n                        pre = pre.next\n        \n                            cur = cur.next\n                                \n                                if not pre:\n                                break"
  },
  {
    "path": "python/111-120/Populating Next Right Pointers in Each Node.py",
    "content": "# Definition for binary tree with next pointer.\n# class TreeLinkNode:\n#     def __init__(self, x):\n#         self.val = x\n#         self.left = None\n#         self.right = None\n#         self.next = None\n\nclass Solution:\n    # @param root, a tree link node\n    # @return nothing\n    def connect(self, root):\n        if not root:\n            return\n        \n        while root.left:\n            cur = root\n            pre = None\n            while cur:\n                if pre:\n                    pre.next = cur.left\n                cur.left.next = cur.right\n                pre = cur.right\n                cur = cur.next\n            root = root.left"
  },
  {
    "path": "python/121-130/Best Time to Buy and Sell Stock.py",
    "content": "class Solution:\n    # @param {integer[]} prices\n    # @return {integer}\n    def maxProfit(self, prices):\n        res = 0\n        minimum = 2**31-1\n        for e in prices:\n            res = max(res, e - minimum)\n            minimum = min(minimum, e) \n        return res\n"
  },
  {
    "path": "python/121-130/Binary Tree Maximum Path Sum.py",
    "content": "class TreeNode:\n    def __init__(self, x):\n        self.val = x\n        self.left = None\n        self.right = None\n\nclass Solution:\n    \n    # @param {TreeNode} root\n    # @return {integer}\n    def maxPathSum(self, root):\n        Solution.result = -10000000\n        self.help(root)\n        return Solution.result\n    \n    def help(self,root):\n        if not root:\n            return 0\n        l = self.help(root.left)\n        r = self.help(root.right)\n        if l < 0:\n            l = 0\n        if r < 0:\n            r = 0\n        tmp = l + r + root.val\n        Solution.result = max(Solution.result, tmp)\n        tmp = root.val + max(l, r)\n        return tmp\n\n\nroot = TreeNode(1);\nl = TreeNode(2);\nroot.left = l\nS = Solution()\nprint S.maxPathSum(root)"
  },
  {
    "path": "python/121-130/Word Ladder II.py",
    "content": "class Solution:\n    # @param start, a string\n    # @param end, a string\n    # @param dict, a set of string\n    # @return a list of lists of string\n    def findLadders(self, start, end, dict):\n        level = {start}\n        parents = collections.defaultdict(set)\n        while level and end not in parents:\n            next_level = collections.defaultdict(set)\n            for node in level:\n                for char in string.ascii_lowercase:\n                    for i in range(len(start)):\n                        n = node[:i]+char+node[i+1:]\n                        if n in dict and n not in parents:\n                            next_level[n].add(node)\n            level = next_level\n            parents.update(next_level)\n        res = [[end]]\n        while res and res[0][0] != start:\n            res = [[p]+r for r in res for p in parents[r[0]]]\n        return res"
  },
  {
    "path": "python/121-130/Word Ladder.py",
    "content": "class Solution:\n    # @param {string} beginWord\n    # @param {string} endWord\n    # @param {set<string>} wordDict\n    # @return {integer}\n    def ladderLength(self, beginWord, endWord, wordDict):\n        dis = {}\n        dis[beginWord] = 1\n        chars = string.ascii_lowercase\n        myqueue = [beginWord]\n        \n        while len(myqueue) > 0:\n            word = myqueue[0]\n            del myqueue[0]\n            if word == endWord:\n                break\n            for i in range(len(word)):\n                for c in chars:\n                    newWord = word[:i] + c + word[i+1:]\n                    if newWord in wordDict and newWord not in dis:\n                        dis[newWord] = dis[word]+1\n                        myqueue.append(newWord)\n    \n        if endWord not in dis:\n            return 0\nreturn dis[endWord]"
  },
  {
    "path": "python/131-140/Candy.py",
    "content": "class Solution:\n    # @param {integer[]} ratings\n    # @return {integer}\n    def candy(self, ratings):\n        l = len(ratings)\n        p = [1]*l\n        \n        for i in range(l-1):\n            if ratings[i+1] > ratings[i]:\n                p[i+1] = p[i]+1\n        for i in range(l-1, 0, -1):\n            if ratings[i-1] > ratings[i]:\n                p[i-1] = max(p[i-1], p[i]+1)\n        \n        return sum(p)"
  },
  {
    "path": "python/131-140/Clone Graph.py",
    "content": "# Definition for a undirected graph node\n# class UndirectedGraphNode:\n#     def __init__(self, x):\n#         self.label = x\n#         self.neighbors = []\n\nclass Solution:\n    dict = {}\n    # @param node, a undirected graph node\n    # @return a undirected graph node\n    def cloneGraph(self, node):\n        if not node:\n            return None\n        \n        if node not in self.dict:\n            self.dict[node] = UndirectedGraphNode(node.label)\n            for e in node.neighbors:\n                self.dict[node].neighbors.append(self.cloneGraph(e))\n\n    return self.dict[node]"
  },
  {
    "path": "python/131-140/Single Number II.py",
    "content": "class Solution:\n    # @param {integer[]} nums\n    # @return {integer}\n    def singleNumber(self, nums):\n        tmp = set(nums)\n        v = sum(tmp)*3 -sum(nums)\n        return v/2\n\n\ns = Solution()\nitems = [2,2,3,2]\nprint s.singleNumber(items)"
  },
  {
    "path": "python/141-150/Binary Tree Postorder Traversal.py",
    "content": "# Definition for a binary tree node.\n# class TreeNode:\n#     def __init__(self, x):\n#         self.val = x\n#         self.left = None\n#         self.right = None\n\nclass Solution:\n    # @param {TreeNode} root\n    # @return {integer[]}\n    def postorderTraversal(self, root):\n        v = []\n        if not root:\n            return v\n        \n        stacks = []\n        stacks.append(root)\n        \n        while len(stacks) > 0:\n            root = stacks[-1]\n            del stacks[-1]\n            v.append(root.val)\n            \n            if root.left:\n                stacks.append(root.left)\n            if root.right:\n                stacks.append(root.right)\n        \n        v.reverse()\n    return v"
  },
  {
    "path": "python/141-150/LRU Cache.py",
    "content": "class LRUCache:\n    \n    # @param capacity, an integer\n    def __init__(self, capacity):\n        self.capacity = capacity\n        self.cache = collections.OrderedDict()\n    \n    # @return an integer\n    def get(self, key):\n        if not key in self.cache:\n            return -1\n        value = self.cache.pop(key)\n        self.cache[key] = value\n        return value\n    \n    # @param key, an integer\n    # @param value, an integer\n    # @return nothing\n    def set(self, key, value):\n        if key in self.cache:\n            self.cache.pop(key)\n        elif len(self.cache) == self.capacity:\n            self.cache.popitem(last=False)\n        self.cache[key] = value"
  },
  {
    "path": "python/151-160/Find Minimum in Rotated Sorted Array II.py",
    "content": "class Solution:\n    # @param {integer[]} nums\n    # @return {integer}\n    def findMin(self, nums):\n        start = 0\n        end = len(nums)-1\n        \n        while start < end:\n            if nums[start] < nums[end]:\n                return nums[start]\n            \n            mid = (start+end)/2\n            if(nums[mid] > nums[start]):\n                start = mid+1\n            elif(nums[mid] < nums[start]):\n                end = mid\n            else:\n                start += 1\n\n    return nums[start]"
  },
  {
    "path": "python/151-160/Find Minimum in Rotated Sorted Array.py",
    "content": "class Solution:\n    # @param {integer[]} nums\n    # @return {integer}\n    def findMin(self, nums):\n        start = 0\n        end = len(nums)-1\n        \n        while start < end:\n            if nums[start] < nums[end]:\n                return nums[start]\n            \n            mid = (start+end)/2\n            if(nums[mid] >= nums[start]):\n                start = mid+1\n            else:\n                end = mid\n\n    return nums[start]"
  },
  {
    "path": "python/161-170/Majority Element.py",
    "content": "class Solution:\n    # @param {integer[]} nums\n    # @return {integer}\n    def majorityElement(self, nums):\n        stack = []\n        for e in nums:\n            if len(stack) == 0:\n                stack.append(e)\n            else:\n                if stack[-1] == e:\n                    stack.append(e)\n                else:\n                    del stack[-1]\n        return stack[0]\n"
  },
  {
    "path": "python/161-170/Maximum Gap.py",
    "content": "import math\n\nclass Solution:\n    # @param num, a list of integer\n    # @return an integer\n    def maximumGap(self, num):\n        if len(num) < 2 or min(num) == max(num):\n            return 0\n        a, b = min(num), max(num)\n        gap = int(math.ceil((b-a)*1.0/(len(num)-1)))\n        bucket = [[None, None] for _ in range((b-a)/gap+1)]\n        for n in num:\n            b = bucket[int((n-a)/gap)]\n            b[0] = n if b[0] is None else min(b[0], n)\n            b[1] = n if b[1] is None else max(b[1], n)\n        bucket = [b for b in bucket if b[0] is not None]\n        return max(bucket[i][0]-bucket[i-1][1] for i in range(1, len(bucket)))\n\nitems = [1,1,1,1,1,5,5,5,5,5]\ns = Solution()\nprint s.maximumGap(items)"
  },
  {
    "path": "python/171-180/Largest Number.py",
    "content": "class Solution:\n    # @param {integer[]} nums\n    # @return {string}\n    def largestNumber(self, nums):\n        num = [str(x) for x in nums]\n        num.sort(cmp = lambda x,y : cmp(y+x, x+y))\n        return \"\".join(num).lstrip('0') or '0'"
  },
  {
    "path": "python/181-190/Best Time to Buy and Sell Stock IV.py",
    "content": "#!/usr/bin/env python\n# coding=utf-8\n\nclass Solution:\n    # @param {integer} k\n    # @param {integer[]} prices\n    # @return {integer}\n    def maxProfit(self, k, prices):\n        l = len(prices)\n        if l < 2:\n            return 0\n        if k >= l/2:\n            res = 0\n            for i in range(l-1):\n                if prices[i+1] > prices[i]:\n                    res = res + prices[i+1] - prices[i]\n            return res\n    \n        p = [[0]*(l+1) for _ in range(k+1)]\n        for i in range(1,k+1):\n            temp = -prices[0]\n            for j in range(1,l+1):\n                p[i][j] = max(p[i][j-1], temp+prices[j-1])\n                temp = max(temp, p[i-1][j-1]-prices[j-1])\n        return p[k][l]"
  },
  {
    "path": "python/181-190/Repeated DNA Sequences.py",
    "content": "class Solution:\n    # @param {string} s\n    # @return {string[]}\n    def findRepeatedDnaSequences(self, s):\n        result = []\n        t = i = 0\n        ss = len(s)\n        if ss < 10:\n            return result\n        dic = {}\n        \n        while i < 9:\n            t = t << 3 | ord(s[i]) & 7\n            i = i + 1\n        \n        while i < ss:\n            t = t << 3 & 0x3FFFFFFF | ord(s[i]) & 7\n            i = i + 1\n            \n            if t in dic:\n                dic[t] = dic[t]+1\n            else:\n                dic[t] = 1\n            if dic[t] == 2:\n                result.append(s[i-10:i]);\n\n        return result\n\ns = Solution()\nst = \"AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT\"\nprint s.findRepeatedDnaSequences(st)"
  },
  {
    "path": "python/191-200/Binary Tree Right Side View.py",
    "content": "#!/usr/bin/env python\n# coding=utf-8\n\nclass Solution:\n    # @param {TreeNode} root\n    # @return {integer[]}\n    def rightSideView(self, root):\n        items = []\n        self.help(root, items, 0)\n        return items\n    \n    def help(self, root, items, height):\n        if not root:\n            return\n        if(height == len(items)):\n            items.append(root.val)\n        self.help(root.right, items, height+1)\n        self.help(root.left, items, height+1)"
  },
  {
    "path": "python/191-200/House Robber.py",
    "content": "class Solution:\n    # @param {integer[]} nums\n    # @return {integer}\n    def rob(self, nums):\n        if not nums:\n            return 0\n        if(len(nums) == 1):\n            return nums[0]\n        \n        p = [0]*len(nums)\n        p[0] = nums[0]\n        p[1] = max(nums[0], nums[1])\n        \n        for i in range(2, len(nums)):\n            p[i] = max(p[i-2] + nums[i], p[i-1])\n        \n        return p[-1]"
  },
  {
    "path": "python/201-210/Count Primes.py",
    "content": "import math\n\nclass Solution:\n    # @param {integer} n\n    # @return {integer}\n    def countPrimes(self, n):\n        if n <= 2:\n            return 0\n        c = int(math.sqrt(n))\n        b = [False] * n;\n        \n        for i in range(3, c+1):\n            if not b[i]:\n                j = i*i\n                k = i << 1\n                while j < n:\n                    b[j] = True\n                    j += k\n        \n        res = 1\n        for i in range(3, n, 2):\n            if not b[i]:\n                res += 1\n        return res"
  },
  {
    "path": "python/201-210/Implement Trie (Prefix Tree).py",
    "content": "class TrieNode:\n    # Initialize your data structure here.\n    def __init__(self):\n        self.children = collections.defaultdict(TrieNode)\n        self.isWord = False\n        \nclass Trie:\n\n    def __init__(self):\n        self.root = TrieNode()\n\n    # @param {string} word\n    # @return {void}\n    # Inserts a word into the trie.\n    def insert(self, word):\n        cur = self.root\n        for e in word:\n            cur = cur.children[e]\n        cur.isWord = True\n\n    # @param {string} word\n    # @return {boolean}\n    # Returns if the word is in the trie.\n    def search(self, word):\n        cur = self.root\n        for e in word:\n            cur = cur.children.get(e)\n            if not cur:\n                return False\n        return cur.isWord\n        \n\n    # @param {string} prefix\n    # @return {boolean}\n    # Returns if there is any word in the trie\n    # that starts with the given prefix.\n    def startsWith(self, prefix):\n        cur = self.root\n        for e in prefix:\n            cur = cur.children.get(e)\n            if not cur:\n                return False\n        return True\n\n# Your Trie object will be instantiated and called as such:\n# trie = Trie()\n# trie.insert(\"somestring\")\n# trie.search(\"key\")\n"
  },
  {
    "path": "python/211-220/House Robber II.py",
    "content": "class Solution:\n    # @param {integer[]} nums\n    # @return {integer}\n    def rob(self, nums):\n        if not nums:\n            return 0\n        if len(nums) == 1:\n            return nums[0]\n        \n        pre1 = cur1 = 0\n        for i in range(len(nums)-1):\n            temp = pre1\n            pre1 = cur1\n            cur1 = max(temp+nums[i], pre1)\n        \n        pre2 = cur2 = 0\n        for i in range(1, len(nums)):\n            temp = pre2\n            pre2 = cur2\n            cur2 = max(temp+nums[i], pre2)\n        \n        return max(cur1, cur2)"
  },
  {
    "path": "python/221-230/Maximal Square.py",
    "content": "class Solution:\n    # @param {character[][]} matrix\n    # @return {integer}\n    def maximalSquare(self, matrix):\n        if len(matrix) == 0:\n            return 0\n        h = [0] * (len(matrix[0])+1)\n        res = 0\n        \n        for i in range(len(matrix)):\n            matrix[i].append('0')\n            mystack = []\n            \n            for j in range(len(matrix[i])):\n                if matrix[i][j] == '1':\n                    h[j] += 1\n                else:\n                    h[j] = 0\n                \n                if len(mystack) == 0 or h[j] >= h[mystack[-1]]:\n                    mystack.append(j)\n                else:\n                    while len(mystack) > 0 and h[j] < h[mystack[-1]]:\n                        height = h[mystack[-1]]\n                        del mystack[-1]\n                        width = j if len(mystack) == 0 else j - 1 - mystack[-1]\n                        side = min(height, width)\n                        res = max(res, side*side)\n                    mystack.append(j)\n        \n        return res"
  },
  {
    "path": "python/231-240/Palindrome Linked List.py",
    "content": "# Definition for singly-linked list.\n# class ListNode:\n#     def __init__(self, x):\n#         self.val = x\n#         self.next = None\n\nclass Solution:\n    # @param {ListNode} head\n    # @return {boolean}\n    def isPalindrome(self, head):\n        if not head or not head.next:\n            return True\n        \n        slow = fast = head\n        while fast.next and fast.next.next:\n            slow = slow.next\n            fast = fast.next.next\n        fast = self.reverse(slow.next)\n        \n        while fast:\n            if head.val != fast.val:\n                return False\n            fast = fast.next\n            head = head.next\n        \n        return True\n    \n    \n    def reverse(self, head):\n        prev = tmp = None\n        while head:\n            tmp = head.next\n            head.next = prev\n            prev = head\n            head = tmp\n        return prev"
  },
  {
    "path": "python/231-240/Product of Array Except Self.py",
    "content": "class Solution:\n    # @param {integer[]} nums\n    # @return {integer[]}\n    def productExceptSelf(self, nums):\n        ls = len(nums)\n        result = [0]*ls\n        result[0] = 1\n        tmp = 1\n        \n        for i in range(1,ls):\n            result[i] = result[i-1]*nums[i-1]\n        for i in range(ls-2, -1, -1):\n            tmp = tmp * nums[i+1]\n            result[i] = result[i]*tmp\n        \n        return result\n\n\nitems = [0,1]\ns = Solution()\nprint s.productExceptSelf(items)"
  },
  {
    "path": "python/231-240/a.py",
    "content": "class Solution:\n    # @param {integer[]} nums\n    # @param {integer} k\n    # @return {integer[]}\n    def maxSlidingWindow(self, nums, k):\n        myqueue,res = [],[]\n        for i in range(len(nums)):\n            if len(myqueue) > 0 and myqueue[0] == i - k:\n                del myqueue[0]\n            while len(myqueue) > 0 and nums[myqueue[-1]] < nums[i]:\n                del myqueue[-1]\n            myqueue.append(i)\n            if i >= k - 1:\n                res.append(nums[myqueue[0]])\n\n    return res"
  },
  {
    "path": "scala/0001-0010/Add Two Numbers.scala",
    "content": "/**\n * Definition for singly-linked list.\n * class ListNode(_x: Int = 0, _next: ListNode = null) {\n *   var next: ListNode = _next\n *   var x: Int = _x\n * }\n */\nobject Solution {\n    def addTwoNumbers(l1: ListNode, l2: ListNode): ListNode = {\n        def addTwoNumbersHelper(l1: ListNode, l2: ListNode, carry: Int): ListNode = {\n            if (l1 == null && l2 == null) if (carry == 0) null else ListNode(carry)\n            else if (l1 == null) addTwoNumbersHelper(ListNode(0), l2, carry)\n            else if (l2 == null) addTwoNumbersHelper(l1, ListNode(0), carry)\n            else ListNode((l1.x + l2.x + carry) % 10, addTwoNumbersHelper(l1.next, l2.next, (l1.x + l2.x + carry) / 10 ))\n        }\n        \n        addTwoNumbersHelper(l1, l2, 0)\n    }\n}\n"
  },
  {
    "path": "scala/0001-0010/Longest Substring Without Repeating Characters.scala",
    "content": "import scala.collection._\n\nobject Solution {\n    def lengthOfLongestSubstring(s: String): Int = {\n        val mymap = mutable.Map[Int, Int]()\n        var start = 0\n        var ans = 0\n        \n        for (i <- 0 until s.length()) {\n            val ch = s(i)\n            if (mymap.contains(ch)) {\n                start = Math.max(start, mymap(ch) + 1)\n            }\n            \n            mymap(ch) = i\n            ans = Math.max(ans, i - start + 1)\n        }\n        \n        ans\n    }\n}\n"
  },
  {
    "path": "scala/0001-0010/Palindrome Number.scala",
    "content": "object Solution {\n    def isPalindrome(x: Int): Boolean = {\n        if (x < 0) return false\n        val s = x.toString\n        \n        for( i <- 0 to s.length()/2 ) {\n            if (s(i) != s(s.length() - i - 1)) return false\n        }\n        \n        true\n    }\n}\n"
  },
  {
    "path": "scala/0001-0010/Two Sum.scala",
    "content": "import scala.collection._\n\nobject Solution {\n  def twoSum(nums: Array[Int], target: Int): Array[Int] = {\n    val map = mutable.Map[Int, Int]()\n    for (i <- 0 until nums.length) {\n      val num = target - nums(i)\n      if (map.contains(num)) {\n        return Array(map(num), i)\n      }\n      map.put(nums(i), i)\n    }\n    \n      return Array(0, 0)\n  }\n}\n"
  },
  {
    "path": "scala/0011-0020/Longest Common Prefix.scala",
    "content": "import scala.util.control.Breaks._\n\nobject Solution {\n    def longestCommonPrefix(strs: Array[String]): String = {\n        if (strs.isEmpty) {\n            return \"\"\n        }\n        \n        var prefix = strs(0)\n        \n        for (i <- 1 until strs.length) {\n            val str = strs(i)\n            \n            var k = 0;\n            \n            breakable {\n                while (k < math.min(prefix.length, str.length)) {\n                    if (prefix(k) != str(k)) { \n                        break\n                    }\n                    k += 1\n                }\n            }\n            \n            prefix = prefix.substring(0, k)\n        }\n        \n        return prefix;\n    }\n}\n"
  },
  {
    "path": "scala/0011-0020/Roman to Integer.scala",
    "content": "object Solution {\n    def romanToInt(s: String): Int = {\n        val table = Map(\n            'I' -> 1,\n            'V' -> 5,\n            'X' -> 10,\n            'L' -> 50,\n            'C' -> 100,\n            'D' -> 500,\n            'M' -> 1000 \n        )\n        \n        var result = 0\n        \n        for (i <- 0 until s.length()) {\n            if (i < s.length()-1 && table(s(i)) < table(s(i+1)) ) {\n                result -= table(s(i))\n            } else {\n                result += table(s(i))\n            }\n        }\n        \n        result\n    }\n}\n"
  }
]